Web Variante in Go V0.1
This commit is contained in:
1 parent
f9e3e94629
commit
692b9b6ef8
60 files changed
+13140
No files matched your search
@@ -0,0 +1,8 @@
|
||||
# Laufzeitdaten
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
dist/
|
||||
|
||||
# Lokale Binaries
|
||||
/lektorenplan
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
# LektorenPlan Web
|
||||
|
||||
Browserbasierte, funktional entsprechende Umsetzung der macOS-App
|
||||
**LektorenPlan**: Gottesdienstplan, Gottesdienstordnung, Teamverwaltung,
|
||||
Statistik, Austausch, liturgischer Kalender, PDF/ Druck und eine
|
||||
Mehrbenutzerverwaltung mit Mandanten.
|
||||
|
||||
Die Webversion läuft als einzelner Go-Prozess mit einer SQLite-Datenbank. Sie
|
||||
ist **CGO-frei** und lässt sich damit unkompliziert für Linux/arm64 (z. B.
|
||||
Raspberry Pi, ARM-Server, Docker) bauen. Die bestehende macOS-App bleibt
|
||||
unverändert nutzbar.
|
||||
|
||||
## Funktionsumfang
|
||||
|
||||
- **Gottesdienstplan** mit Tageszeilen, Lesungen, Kirchenspalten, Feiertagen
|
||||
und farblich markierter Liturgie
|
||||
- **Automatische Planung** mit Ausschlüssen, Präferenzen, Fairness und
|
||||
Doppelrollen-Regeln; manuelle Nachsteuerung inklusive Sperren
|
||||
- **Gottesdienstordnung** mit wiederkehrenden Vorlagen, Ausnahmen und
|
||||
Sondergottesdiensten (auch außerhalb der Kirche)
|
||||
- **Team & Abwesenheiten** mit Rollen, Präferenzen, Monatslimits und
|
||||
Einsatzhistorie
|
||||
- **Statistik** über Besetzung, Fairness, Monatsverlauf und Kirchenverteilung
|
||||
- **Austausch** per JSON-Export und zweistufigem Import mit Vorschau
|
||||
- **Liturgischer Kalender** für das Erzbistum Köln mit Online-Aktualisierung,
|
||||
Offline-Snapshot und lokaler Berechnung als Rückfallebene
|
||||
- **PDF/Druck** in zwei Varianten: A4 quer als vollständiger Plan und A4 hoch
|
||||
als kompakte Gottesdienstliste
|
||||
- **Mandanten, Konten und Kirchen** zentral über die Administration verwalten
|
||||
|
||||
## Schnellstart
|
||||
|
||||
Voraussetzung: Go 1.27 oder neuer.
|
||||
|
||||
```bash
|
||||
cd web
|
||||
go run . -seed-demo -demo
|
||||
```
|
||||
|
||||
Anschließend <http://localhost:8080> öffnen.
|
||||
|
||||
Die Demo-Datenbank wird beim ersten Start angelegt. Mit den dokumentierten
|
||||
Demo-Zugängen erhält man sofort einen vollständigen Plan:
|
||||
|
||||
| Konto | Passwort | Rolle |
|
||||
|----------|------------|---------------|
|
||||
| `admin` | `admin123` | Administrator |
|
||||
| `editor` | `editor123`| Redakteur |
|
||||
| `reader` | `reader123`| Leser |
|
||||
|
||||
> Die Demo-Zugänge sind ausschließlich für lokale Tests gedacht. In einer
|
||||
> produktiven Installation `-seed-demo` weglassen und ein eigenes
|
||||
> Administratorkonto anlegen.
|
||||
|
||||
Ohne `-seed-demo` und ohne vorhandene Konten erzeugt der Server automatisch
|
||||
einen Administrator. Wird kein Passwort übergeben, wird ein einmaliges
|
||||
Zufallspasswort im Log ausgegeben:
|
||||
|
||||
```bash
|
||||
go run . -db /var/lib/lektorenplan/lektorenplan.db \
|
||||
-admin-user admin -admin-password 'ein-sicheres-passwort'
|
||||
```
|
||||
|
||||
## Konfiguration
|
||||
|
||||
Alle Flags lassen sich auch über Umgebungsvariablen setzen:
|
||||
|
||||
| Flag | Umgebungsvariable | Standard | Bedeutung |
|
||||
|------|-------------------|----------|-----------|
|
||||
| `-addr` | `LP_ADDR` | `:8080` | HTTP-Listenadresse |
|
||||
| `-db` | `LP_DB` | `lektorenplan.db` | Pfad zur SQLite-Datei |
|
||||
| `-seed-demo` | `LP_SEED_DEMO` | `false` | Demo-Mandanten und Demo-Konten anlegen |
|
||||
| `-admin-user` | `LP_ADMIN_USER` | `admin` | Benutzername des ersten Administrators |
|
||||
| `-admin-password` | `LP_ADMIN_PASSWORD` | – | Passwort des ersten Administrators |
|
||||
| `-secure-cookies` | `LP_SECURE_COOKIES` | `false` | Cookies nur über HTTPS senden |
|
||||
| `-demo` | `LP_DEMO_MODE` | `false` | Demo-Hinweis in der Oberfläche anzeigen |
|
||||
| `-sync-liturgy` | `LP_SYNC_LITURGY` | `true` | Liturgischen Kalender täglich im Hintergrund aktualisieren |
|
||||
|
||||
## Rollen und Mandanten
|
||||
|
||||
Jedes Konto hat genau eine globale Rolle:
|
||||
|
||||
- **Administrator** verwaltet alle Mandanten, Konten und Kirchen und darf überall
|
||||
planen.
|
||||
- **Redakteur** bearbeitet die ihm freigegebenen Mandanten.
|
||||
- **Leser** sieht die ihm freigegebenen Mandanten ausschließlich lesend.
|
||||
|
||||
Planungsdaten (Kirchen, Personen, Vorlagen, Gottesdienste, Einteilungen,
|
||||
Abwesenheiten und Einstellungen) sind immer einem Mandanten zugeordnet.
|
||||
Administratoren sehen alle Mandanten; Redakteure und Leser nur die in
|
||||
`memberships` eingetragenen. Der aktive Mandant wird über die Seitenleiste
|
||||
gewechselt.
|
||||
|
||||
## Bauen und testen
|
||||
|
||||
```bash
|
||||
cd web
|
||||
|
||||
gofmt -l .
|
||||
go vet ./...
|
||||
go test ./...
|
||||
go build ./...
|
||||
|
||||
# statisches Linux/arm64-Binary
|
||||
./scripts/build-linux-arm64.sh
|
||||
# → dist/lektorenplan-linux-arm64
|
||||
```
|
||||
|
||||
Das Binary ist statisch gelinkt und benötigt auf dem Zielsystem weder libc
|
||||
noch eine SQLite-Installation.
|
||||
|
||||
## Deployment (Linux/arm64)
|
||||
|
||||
Beispiel für eine Installation unter `/opt/lektorenplan`:
|
||||
|
||||
```bash
|
||||
# Binary auf den Server kopieren
|
||||
scp dist/lektorenplan-linux-arm64 server:/tmp/lektorenplan
|
||||
|
||||
ssh server
|
||||
sudo useradd --system --home /opt/lektorenplan --shell /usr/sbin/nologin lektorenplan
|
||||
sudo install -d -o lektorenplan -g lektorenplan /opt/lektorenplan /var/lib/lektorenplan
|
||||
sudo install -m 0755 -o lektorenplan -g lektorenplan \
|
||||
/tmp/lektorenplan /opt/lektorenplan/lektorenplan
|
||||
```
|
||||
|
||||
Dienst einrichten (Vorlage: [`scripts/lektorenplan.service`](scripts/lektorenplan.service)):
|
||||
|
||||
```bash
|
||||
sudo cp scripts/lektorenplan.service /etc/systemd/system/
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now lektorenplan
|
||||
```
|
||||
|
||||
Empfohlen ist ein Reverse Proxy mit TLS (Caddy, nginx oder Traefik), der auf
|
||||
`127.0.0.1:8080` weiterleitet. Dabei `LP_SECURE_COOKIES=true` setzen. Der
|
||||
Server sollte nicht direkt öffentlich erreichbar sein.
|
||||
|
||||
### Betrieb und Sicherheit
|
||||
|
||||
- **Backups:** SQLite-Datei regelmäßig sichern, idealerweise mit
|
||||
`sqlite3 /var/lib/lektorenplan/lektorenplan.db ".backup ..."` oder im
|
||||
laufenden Betrieb über einen Dateisystem-Snapshot. WAL-Dateien
|
||||
(`-wal`, `-shm`) gehören zum konsistenten Stand.
|
||||
- **Passwörter:** bcrypt-Hashes, serverseitige Sitzungen, HttpOnly-Cookies,
|
||||
CSRF-Schutz auf allen schreibenden Formularen.
|
||||
- **Erster Login:** Nach dem Anlegen des Administrators das Initialpasswort
|
||||
ändern und Demo-Konten entfernen bzw. deaktivieren.
|
||||
- **Updates:** Neue Binärdatei austauschen und Dienst neu starten. Das
|
||||
Datenbankschema wird beim Start automatisch migriert.
|
||||
- **Netzwerk:** Der Prozess lauscht standardmäßig auf allen Interfaces. Für
|
||||
einen Proxy-Betrieb `-addr 127.0.0.1:8080` verwenden.
|
||||
|
||||
## Projektstruktur
|
||||
|
||||
```
|
||||
web/
|
||||
├── main.go Start, Flags, Bootstrap, täglicher Liturgie-Sync
|
||||
├── domain/ Modelle, Datumslogik, Planer, Statistik, Liturgie
|
||||
├── liturgy/ Online-API, Offline-Snapshot, lokale Berechnung
|
||||
├── store/ SQLite-Schema, Mandanten, Konten, Planungsdaten
|
||||
├── pdf/ PDF-Renderer (A4 quer und A4 hoch)
|
||||
├── web/ HTTP-Server, Handler, Templates, CSS/JS
|
||||
│ ├── templates/ serverseitige html/template-Seiten
|
||||
│ └── static/ Stylesheet und progressive JavaScript-Helfer
|
||||
└── scripts/ Build- und Deployment-Vorlagen
|
||||
```
|
||||
|
||||
## Liturgische Daten
|
||||
|
||||
Der liturgische Kalender stammt von
|
||||
[www.eucharistiefeier.de](https://www.eucharistiefeier.de). Für die Jahre
|
||||
2025–2028 ist ein Offline-Snapshot eingebettet. Die Anwendung aktualisiert den
|
||||
aktuellen und den Folgejahrgang täglich im Hintergrund, sofern
|
||||
`LP_SYNC_LITURGY` nicht deaktiviert ist. Schlägt der Online-Abruf fehl, werden
|
||||
fehlende Tage lokal berechnet, damit Planung und PDF-Export weiterhin
|
||||
funktionieren.
|
||||
|
||||
> Daten von www.eucharistiefeier.de – fair use, ausschließlich zur Anzeige.
|
||||
> Die Daten bleiben Eigentum der Quelle.
|
||||
|
||||
## Hinweis zur macOS-App
|
||||
|
||||
Die Webversion liegt vollständig unter `web/` und verwendet ein eigenes
|
||||
Go-Modul. Die SwiftUI-App unter `Sources/` wird dadurch nicht verändert. Beide
|
||||
Varianten können parallel gebaut und betrieben werden.
|
||||
@@ -0,0 +1,290 @@
|
||||
// Package domain contains the planning rules shared by the web application.
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// All app dates are calendar days anchored at noon in the Europe/Berlin time
|
||||
// zone. Noon avoids daylight-saving surprises while the ISO key stays stable.
|
||||
var Berlin = loadBerlin()
|
||||
|
||||
func loadBerlin() *time.Location {
|
||||
if loc, err := time.LoadLocation("Europe/Berlin"); err == nil {
|
||||
return loc
|
||||
}
|
||||
return time.UTC
|
||||
}
|
||||
|
||||
func Normalize(t time.Time) time.Time {
|
||||
y, m, d := t.In(Berlin).Date()
|
||||
return time.Date(y, m, d, 12, 0, 0, 0, Berlin)
|
||||
}
|
||||
|
||||
func Today() time.Time {
|
||||
return Normalize(time.Now())
|
||||
}
|
||||
|
||||
func DateFromKey(key string) (time.Time, bool) {
|
||||
t, err := time.ParseInLocation("2006-01-02", key, Berlin)
|
||||
if err != nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return Normalize(t), true
|
||||
}
|
||||
|
||||
func MustDate(key string) time.Time {
|
||||
t, ok := DateFromKey(key)
|
||||
if !ok {
|
||||
return Today()
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func Key(t time.Time) string {
|
||||
return t.In(Berlin).Format("2006-01-02")
|
||||
}
|
||||
|
||||
func KeyYMD(year, month, day int) string {
|
||||
return fmt.Sprintf("%04d-%02d-%02d", year, month, day)
|
||||
}
|
||||
|
||||
func AddingDays(days int, t time.Time) time.Time {
|
||||
return Normalize(Normalize(t).AddDate(0, 0, days))
|
||||
}
|
||||
|
||||
func AddingMonths(months int, t time.Time) time.Time {
|
||||
t = Normalize(t)
|
||||
y, m, d := t.Date()
|
||||
first := time.Date(y, m, 1, 12, 0, 0, 0, Berlin).AddDate(0, months, 0)
|
||||
last := first.AddDate(0, 1, -1)
|
||||
if d > last.Day() {
|
||||
d = last.Day()
|
||||
}
|
||||
return time.Date(first.Year(), first.Month(), d, 12, 0, 0, 0, Berlin)
|
||||
}
|
||||
|
||||
func AddingYears(years int, t time.Time) time.Time {
|
||||
t = Normalize(t)
|
||||
return time.Date(t.Year()+years, t.Month(), t.Day(), 12, 0, 0, 0, Berlin)
|
||||
}
|
||||
|
||||
func ordinal(t time.Time) int64 {
|
||||
y, m, d := Normalize(t).Date()
|
||||
return time.Date(y, m, d, 0, 0, 0, 0, time.UTC).Unix() / 86400
|
||||
}
|
||||
|
||||
func DaysBetween(start, end time.Time) int {
|
||||
return int(ordinal(end) - ordinal(start))
|
||||
}
|
||||
|
||||
func DaysInRange(r DayRange) []time.Time {
|
||||
if r.Start.After(r.End) {
|
||||
return nil
|
||||
}
|
||||
var result []time.Time
|
||||
for cursor := Normalize(r.Start); !cursor.After(r.End); cursor = AddingDays(1, cursor) {
|
||||
result = append(result, cursor)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Weekday follows the Swift app's convention: 1 = Sunday … 7 = Saturday.
|
||||
func Weekday(t time.Time) int {
|
||||
return int(Normalize(t).Weekday()) + 1
|
||||
}
|
||||
|
||||
func IsSunday(t time.Time) bool { return Weekday(t) == 1 }
|
||||
func IsSaturday(t time.Time) bool { return Weekday(t) == 7 }
|
||||
|
||||
var weekdayNames = []string{"", "Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"}
|
||||
var shortWeekdayNames = []string{"", "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"}
|
||||
var monthNames = []string{"", "Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"}
|
||||
var shortMonthNames = []string{"", "Jan.", "Feb.", "März", "Apr.", "Mai", "Juni", "Juli", "Aug.", "Sept.", "Okt.", "Nov.", "Dez."}
|
||||
|
||||
func WeekdayName(t time.Time) string { return weekdayNames[Weekday(t)] }
|
||||
func ShortWeekdayName(t time.Time) string { return shortWeekdayNames[Weekday(t)] }
|
||||
func MonthName(t time.Time) string { return monthNames[int(Normalize(t).Month())] }
|
||||
func ShortMonthName(t time.Time) string { return shortMonthNames[int(Normalize(t).Month())] }
|
||||
|
||||
func LongString(t time.Time) string {
|
||||
return fmt.Sprintf("%s, %d. %s %d", WeekdayName(t), DayNumber(t), MonthName(t), Year(t))
|
||||
}
|
||||
|
||||
func MediumString(t time.Time) string {
|
||||
return fmt.Sprintf("%d. %s %d", DayNumber(t), ShortMonthName(t), Year(t))
|
||||
}
|
||||
|
||||
func DayNumber(t time.Time) int { return Normalize(t).Day() }
|
||||
func Month(t time.Time) int { return int(Normalize(t).Month()) }
|
||||
func Year(t time.Time) int { return Normalize(t).Year() }
|
||||
|
||||
func StartOfYear(t time.Time) time.Time {
|
||||
return time.Date(Year(t), 1, 1, 12, 0, 0, 0, Berlin)
|
||||
}
|
||||
|
||||
func EndOfYear(t time.Time) time.Time {
|
||||
return time.Date(Year(t), 12, 31, 12, 0, 0, 0, Berlin)
|
||||
}
|
||||
|
||||
func StartOfMonth(t time.Time) time.Time {
|
||||
y, m, _ := Normalize(t).Date()
|
||||
return time.Date(y, m, 1, 12, 0, 0, 0, Berlin)
|
||||
}
|
||||
|
||||
func EndOfMonth(t time.Time) time.Time {
|
||||
return AddingDays(-1, AddingMonths(1, StartOfMonth(t)))
|
||||
}
|
||||
|
||||
func StartOfQuarter(t time.Time) time.Time {
|
||||
m := Month(t)
|
||||
quarterStart := ((m-1)/3)*3 + 1
|
||||
return time.Date(Year(t), time.Month(quarterStart), 1, 12, 0, 0, 0, Berlin)
|
||||
}
|
||||
|
||||
func EndOfQuarter(t time.Time) time.Time {
|
||||
return AddingDays(-1, AddingMonths(3, StartOfQuarter(t)))
|
||||
}
|
||||
|
||||
func Quarter(t time.Time) int { return (Month(t)-1)/3 + 1 }
|
||||
|
||||
func MonthKey(t time.Time) string {
|
||||
return fmt.Sprintf("%04d-%02d", Year(t), Month(t))
|
||||
}
|
||||
|
||||
func TimeString(minutes int) string {
|
||||
if minutes < 0 {
|
||||
minutes = 0
|
||||
}
|
||||
h := minutes / 60
|
||||
m := minutes % 60
|
||||
if h > 23 {
|
||||
h = 23
|
||||
}
|
||||
if m > 59 {
|
||||
m = 59
|
||||
}
|
||||
return fmt.Sprintf("%02d:%02d", h, m)
|
||||
}
|
||||
|
||||
func Minutes(hour, minute int) int { return hour*60 + minute }
|
||||
|
||||
func ParseTimeString(s string) (int, bool) {
|
||||
var h, m int
|
||||
if _, err := fmt.Sscanf(strings.TrimSpace(s), "%d:%d", &h, &m); err != nil {
|
||||
return 0, false
|
||||
}
|
||||
if h < 0 || h > 23 || m < 0 || m > 59 {
|
||||
return 0, false
|
||||
}
|
||||
return h*60 + m, true
|
||||
}
|
||||
|
||||
// DayRange is an inclusive calendar-day range.
|
||||
type DayRange struct {
|
||||
Start time.Time
|
||||
End time.Time
|
||||
}
|
||||
|
||||
func NewDayRange(start, end time.Time) DayRange {
|
||||
a, b := Normalize(start), Normalize(end)
|
||||
if a.After(b) {
|
||||
a, b = b, a
|
||||
}
|
||||
return DayRange{Start: a, End: b}
|
||||
}
|
||||
|
||||
func RangeFromKeys(startKey, endKey string) DayRange {
|
||||
start := MustDate(startKey)
|
||||
end, ok := DateFromKey(endKey)
|
||||
if !ok {
|
||||
end = start
|
||||
}
|
||||
return NewDayRange(start, end)
|
||||
}
|
||||
|
||||
func QuarterRange(date time.Time) DayRange {
|
||||
return NewDayRange(StartOfQuarter(date), EndOfQuarter(date))
|
||||
}
|
||||
|
||||
func YearRange(year int) DayRange {
|
||||
return NewDayRange(MustDate(KeyYMD(year, 1, 1)), MustDate(KeyYMD(year, 12, 31)))
|
||||
}
|
||||
|
||||
func MonthRange(date time.Time) DayRange {
|
||||
return NewDayRange(StartOfMonth(date), EndOfMonth(date))
|
||||
}
|
||||
|
||||
func DaysRange(count int, from time.Time) DayRange {
|
||||
if count < 1 {
|
||||
count = 1
|
||||
}
|
||||
return NewDayRange(from, AddingDays(count-1, from))
|
||||
}
|
||||
|
||||
func (r DayRange) Days() []time.Time { return DaysInRange(r) }
|
||||
func (r DayRange) DayCount() int { return DaysBetween(r.Start, r.End) + 1 }
|
||||
func (r DayRange) Contains(t time.Time) bool {
|
||||
d := Normalize(t)
|
||||
return !d.Before(r.Start) && !d.After(r.End)
|
||||
}
|
||||
func (r DayRange) MonthCount() int {
|
||||
return (Year(r.End)-Year(r.Start))*12 + Month(r.End) - Month(r.Start) + 1
|
||||
}
|
||||
|
||||
func (r DayRange) Title() string {
|
||||
return MediumString(r.Start) + " – " + MediumString(r.End)
|
||||
}
|
||||
|
||||
func (r DayRange) ShortTitle() string {
|
||||
startLabel := fmt.Sprintf("%d. %s", DayNumber(r.Start), ShortMonthName(r.Start))
|
||||
endLabel := fmt.Sprintf("%d. %s", DayNumber(r.End), ShortMonthName(r.End))
|
||||
if Year(r.Start) == Year(r.End) {
|
||||
return fmt.Sprintf("%s – %s %d", startLabel, endLabel, Year(r.End))
|
||||
}
|
||||
return fmt.Sprintf("%s %d – %s %d", startLabel, Year(r.Start), endLabel, Year(r.End))
|
||||
}
|
||||
|
||||
func (r DayRange) LongTitle() string {
|
||||
return fmt.Sprintf("%s bis %s · %d Tage", LongString(r.Start), LongString(r.End), r.DayCount())
|
||||
}
|
||||
|
||||
func (r DayRange) Clamped(bounds DayRange) DayRange {
|
||||
start, end := r.Start, r.End
|
||||
if start.Before(bounds.Start) {
|
||||
start = bounds.Start
|
||||
}
|
||||
if end.After(bounds.End) {
|
||||
end = bounds.End
|
||||
}
|
||||
if end.Before(start) {
|
||||
end = start
|
||||
}
|
||||
return NewDayRange(start, end)
|
||||
}
|
||||
|
||||
func (r DayRange) Extend(monthsBefore, monthsAfter int) DayRange {
|
||||
return NewDayRange(AddingMonths(-monthsBefore, r.Start), AddingMonths(monthsAfter, r.End))
|
||||
}
|
||||
|
||||
// CurrentChurchYear returns the liturgical year containing the date.
|
||||
func CurrentChurchYear(date time.Time) DayRange {
|
||||
y := Year(date)
|
||||
thisAdvent := AdventStart(y)
|
||||
if date.Before(thisAdvent) {
|
||||
return NewDayRange(AdventStart(y-1), ChristKing(y))
|
||||
}
|
||||
return NewDayRange(thisAdvent, ChristKing(y+1))
|
||||
}
|
||||
|
||||
func SortedKeys(m map[string]int) []string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Liturgical calendar primitives shared by the store, the local fallback and
|
||||
// the web views.
|
||||
|
||||
func EasterSunday(year int) time.Time {
|
||||
a := year % 19
|
||||
b := year / 100
|
||||
c := year % 100
|
||||
d := b / 4
|
||||
e := b % 4
|
||||
f := (b + 8) / 25
|
||||
g := (b - f + 1) / 3
|
||||
h := (19*a + b - d - g + 15) % 30
|
||||
i := c / 4
|
||||
k := c % 4
|
||||
l := (32 + 2*e + 2*i - h - k) % 7
|
||||
m := (a + 11*h + 22*l) / 451
|
||||
month := (h + l - 7*m + 114) / 31
|
||||
day := ((h + l - 7*m + 114) % 31) + 1
|
||||
return MustDate(KeyYMD(year, month, day))
|
||||
}
|
||||
|
||||
func easterOffset(offset, year int) time.Time {
|
||||
return AddingDays(offset, EasterSunday(year))
|
||||
}
|
||||
|
||||
func AshWednesday(year int) time.Time { return easterOffset(-46, year) }
|
||||
func PalmSunday(year int) time.Time { return easterOffset(-7, year) }
|
||||
func HolyThursday(year int) time.Time { return easterOffset(-3, year) }
|
||||
func GoodFriday(year int) time.Time { return easterOffset(-2, year) }
|
||||
func HolySaturday(year int) time.Time { return easterOffset(-1, year) }
|
||||
func Ascension(year int) time.Time { return easterOffset(39, year) }
|
||||
func Pentecost(year int) time.Time { return easterOffset(49, year) }
|
||||
func CorpusChristi(year int) time.Time { return easterOffset(60, year) }
|
||||
func SacredHeart(year int) time.Time { return easterOffset(68, year) }
|
||||
func TrinitySunday(year int) time.Time { return easterOffset(56, year) }
|
||||
|
||||
// AdventStart returns the first Sunday of Advent in the given year.
|
||||
func AdventStart(year int) time.Time {
|
||||
christmasEve := MustDate(KeyYMD(year, 12, 24))
|
||||
sunday := christmasEve
|
||||
for Weekday(sunday) != 1 {
|
||||
sunday = AddingDays(-1, sunday)
|
||||
}
|
||||
return AddingDays(-21, sunday)
|
||||
}
|
||||
|
||||
// ChristKing returns the feast of Christ the King for the given year.
|
||||
func ChristKing(year int) time.Time { return AddingDays(-7, AdventStart(year)) }
|
||||
|
||||
// BaptismOfTheLord returns the end of the Christmas season.
|
||||
func BaptismOfTheLord(year int) time.Time {
|
||||
epiphany := MustDate(KeyYMD(year, 1, 6))
|
||||
sunday := AddingDays(1, epiphany)
|
||||
for Weekday(sunday) != 1 {
|
||||
sunday = AddingDays(1, sunday)
|
||||
}
|
||||
if Month(epiphany) == 1 && DayNumber(epiphany) >= 7 {
|
||||
return AddingDays(1, epiphany)
|
||||
}
|
||||
return sunday
|
||||
}
|
||||
|
||||
// SeasonFor maps a date onto the liturgical season.
|
||||
func SeasonFor(date time.Time) LiturgicalSeason {
|
||||
day := Normalize(date)
|
||||
y := Year(day)
|
||||
advent := AdventStart(y)
|
||||
christmas := MustDate(KeyYMD(y, 12, 25))
|
||||
baptism := BaptismOfTheLord(y)
|
||||
ash := AshWednesday(y)
|
||||
holyThursday := HolyThursday(y)
|
||||
easter := EasterSunday(y)
|
||||
pentecost := Pentecost(y)
|
||||
|
||||
switch {
|
||||
case !day.Before(advent) && day.Before(christmas):
|
||||
return SeasonAdvent
|
||||
case !day.Before(christmas) || !day.After(baptism):
|
||||
return SeasonChristmas
|
||||
case !day.Before(ash) && day.Before(holyThursday):
|
||||
return SeasonLent
|
||||
case !day.Before(easter) && !day.After(pentecost):
|
||||
return SeasonEaster
|
||||
case day.After(pentecost) && day.Before(advent):
|
||||
return SeasonOrdinary
|
||||
default:
|
||||
return SeasonOrdinary
|
||||
}
|
||||
}
|
||||
|
||||
// SymbolFor picks a decorative feast symbol from the title and rank.
|
||||
func SymbolFor(title string, rank LiturgicalRank, date time.Time) FeastSymbol {
|
||||
t := strings.ToLower(title)
|
||||
switch {
|
||||
case strings.Contains(t, "weihnacht"), strings.Contains(t, "geburt des herrn"), strings.Contains(t, "erscheinung"):
|
||||
return FeastStar
|
||||
case strings.Contains(t, "ostern"), strings.Contains(t, "auferstehung"):
|
||||
return FeastSun
|
||||
case strings.Contains(t, "pfingst"), strings.Contains(t, "heiliger geist"):
|
||||
return FeastFlame
|
||||
case strings.Contains(t, "fronleichnam"), strings.Contains(t, "abendmahl"), strings.Contains(t, "gründonnerstag"):
|
||||
return FeastCandle
|
||||
case strings.Contains(t, "herz jesu"):
|
||||
return FeastHeart
|
||||
case strings.Contains(t, "christkönig"), strings.Contains(t, "allerheiligen"):
|
||||
return FeastCrown
|
||||
case strings.Contains(t, "maria"), strings.Contains(t, "mariä"):
|
||||
return FeastLily
|
||||
case strings.Contains(t, "kreuz"), strings.Contains(t, "kreuzerhöhung"):
|
||||
return FeastCross
|
||||
case strings.Contains(t, "taufe"):
|
||||
return FeastDove
|
||||
case strings.Contains(t, "wort gottes"), strings.Contains(t, "evangel"):
|
||||
return FeastBook
|
||||
case strings.Contains(t, "lichtmess"), strings.Contains(t, "darstellung"):
|
||||
return FeastCandle
|
||||
}
|
||||
if rank == RankSolemnity || rank == RankFeast {
|
||||
return FeastCross
|
||||
}
|
||||
return FeastBook
|
||||
}
|
||||
@@ -0,0 +1,859 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Role is a service role. Lector and helper do not exclude each other.
|
||||
type Role string
|
||||
|
||||
const (
|
||||
RoleLector Role = "lector"
|
||||
RoleHelper Role = "helper"
|
||||
)
|
||||
|
||||
var AllRoles = []Role{RoleLector, RoleHelper}
|
||||
|
||||
func (r Role) Title() string {
|
||||
if r == RoleHelper {
|
||||
return "Kommunionhelfer"
|
||||
}
|
||||
return "Lektor"
|
||||
}
|
||||
|
||||
func (r Role) Plural() string {
|
||||
if r == RoleHelper {
|
||||
return "Kommunionhelfer"
|
||||
}
|
||||
return "Lektoren"
|
||||
}
|
||||
|
||||
func (r Role) ShortCode() string {
|
||||
if r == RoleHelper {
|
||||
return "K"
|
||||
}
|
||||
return "L"
|
||||
}
|
||||
|
||||
func (r Role) Complementary() Role {
|
||||
if r == RoleLector {
|
||||
return RoleHelper
|
||||
}
|
||||
return RoleLector
|
||||
}
|
||||
|
||||
func (r Role) IsValid() bool { return r == RoleLector || r == RoleHelper }
|
||||
|
||||
type ChurchSymbol string
|
||||
|
||||
const (
|
||||
SymbolBasilica ChurchSymbol = "basilica"
|
||||
SymbolGothic ChurchSymbol = "gothic"
|
||||
SymbolModern ChurchSymbol = "modern"
|
||||
SymbolRotunda ChurchSymbol = "rotunda"
|
||||
SymbolRoundTower ChurchSymbol = "roundTower"
|
||||
SymbolChapel ChurchSymbol = "chapel"
|
||||
)
|
||||
|
||||
var AllChurchSymbols = []ChurchSymbol{
|
||||
SymbolBasilica, SymbolGothic, SymbolModern, SymbolRotunda, SymbolRoundTower, SymbolChapel,
|
||||
}
|
||||
|
||||
func (s ChurchSymbol) Caption() string {
|
||||
switch s {
|
||||
case SymbolBasilica:
|
||||
return "Romanische Basilika"
|
||||
case SymbolGothic:
|
||||
return "Neugotische Kirche"
|
||||
case SymbolModern:
|
||||
return "Moderner Kirchenbau"
|
||||
case SymbolRotunda:
|
||||
return "Rundkirche"
|
||||
case SymbolRoundTower:
|
||||
return "Rundturm"
|
||||
default:
|
||||
return "Kapelle"
|
||||
}
|
||||
}
|
||||
|
||||
type Church struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
ShortName string `json:"shortName"`
|
||||
Symbol ChurchSymbol `json:"symbol"`
|
||||
ColorHex string `json:"colorHex"`
|
||||
Address string `json:"address"`
|
||||
SortIndex int `json:"sortIndex"`
|
||||
Notes string `json:"notes"`
|
||||
}
|
||||
|
||||
type Person struct {
|
||||
ID string `json:"id"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Roles []Role `json:"roles"`
|
||||
Email string `json:"email"`
|
||||
Phone string `json:"phone"`
|
||||
PreferredChurchIDs []string `json:"preferredChurchIDs"`
|
||||
PreferredWeekdays []int `json:"preferredWeekdays"`
|
||||
PreferredServiceTitles []string `json:"preferredServiceTitles"`
|
||||
MaxPerMonth int `json:"maxPerMonth"`
|
||||
Active bool `json:"active"`
|
||||
Notes string `json:"notes"`
|
||||
}
|
||||
|
||||
func (p Person) FullName() string {
|
||||
return strings.TrimSpace(p.FirstName + " " + p.LastName)
|
||||
}
|
||||
|
||||
func (p Person) Initials() string {
|
||||
f := ""
|
||||
l := ""
|
||||
if r := []rune(p.FirstName); len(r) > 0 {
|
||||
f = string(r[0])
|
||||
}
|
||||
if r := []rune(p.LastName); len(r) > 0 {
|
||||
l = string(r[0])
|
||||
}
|
||||
return strings.ToUpper(f + l)
|
||||
}
|
||||
|
||||
func (p Person) AbbreviatedName() string {
|
||||
if r := []rune(p.FirstName); len(r) > 0 {
|
||||
return string(r[0]) + ". " + p.LastName
|
||||
}
|
||||
return p.LastName
|
||||
}
|
||||
|
||||
func (p Person) RoleLabel() string {
|
||||
var parts []string
|
||||
for _, role := range AllRoles {
|
||||
if p.CanFill(role) {
|
||||
parts = append(parts, role.Title())
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, " · ")
|
||||
}
|
||||
|
||||
func (p Person) CanFill(role Role) bool {
|
||||
for _, r := range p.Roles {
|
||||
if r == role {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p Person) HasRole(role Role) bool { return p.CanFill(role) }
|
||||
|
||||
func (p Person) HasPreference() bool {
|
||||
return len(p.PreferredChurchIDs) > 0 || len(p.PreferredWeekdays) > 0 || len(p.PreferredServiceTitles) > 0
|
||||
}
|
||||
|
||||
func IntContains(values []int, needle int) bool {
|
||||
for _, v := range values {
|
||||
if v == needle {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func StringContains(values []string, needle string) bool {
|
||||
for _, v := range values {
|
||||
if v == needle {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func UniqueStrings(values []string) []string {
|
||||
seen := map[string]bool{}
|
||||
var out []string
|
||||
for _, v := range values {
|
||||
if !seen[v] {
|
||||
seen[v] = true
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type Absence struct {
|
||||
ID string `json:"id"`
|
||||
PersonID string `json:"personID"`
|
||||
Start time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
func (a Absence) Range() DayRange { return NewDayRange(a.Start, a.End) }
|
||||
func (a Absence) Overlaps(t time.Time) bool {
|
||||
return Normalize(t).Compare(Normalize(a.Start)) >= 0 && Normalize(t).Compare(Normalize(a.End)) <= 0
|
||||
}
|
||||
|
||||
func (a Absence) Label() string {
|
||||
start := MediumString(a.Start)
|
||||
end := MediumString(a.End)
|
||||
base := start
|
||||
if start != end {
|
||||
base = start + " – " + end
|
||||
}
|
||||
if a.Reason == "" {
|
||||
return base
|
||||
}
|
||||
return base + " · " + a.Reason
|
||||
}
|
||||
|
||||
type ServiceTemplate struct {
|
||||
ID string `json:"id"`
|
||||
ChurchID string `json:"churchID"`
|
||||
Weekday int `json:"weekday"`
|
||||
TimeMinutes int `json:"timeMinutes"`
|
||||
Title string `json:"title"`
|
||||
LectorsNeeded int `json:"lectorsNeeded"`
|
||||
HelpersNeeded int `json:"helpersNeeded"`
|
||||
ValidFrom time.Time `json:"validFrom"`
|
||||
ValidTo *time.Time `json:"validTo"`
|
||||
Active bool `json:"active"`
|
||||
Notes string `json:"notes"`
|
||||
}
|
||||
|
||||
func (t ServiceTemplate) TimeLabel() string { return TimeString(t.TimeMinutes) }
|
||||
|
||||
func (t ServiceTemplate) WeekdayLabel() string {
|
||||
if t.Weekday >= 1 && t.Weekday <= 7 {
|
||||
return weekdayNames[t.Weekday]
|
||||
}
|
||||
return "?"
|
||||
}
|
||||
|
||||
func (t ServiceTemplate) RequirementLabel() string {
|
||||
var parts []string
|
||||
if t.LectorsNeeded > 0 {
|
||||
parts = append(parts, pluralCount(t.LectorsNeeded, "Lektor", "Lektoren"))
|
||||
}
|
||||
if t.HelpersNeeded > 0 {
|
||||
parts = append(parts, pluralCount(t.HelpersNeeded, "Kommunionhelfer", "Kommunionhelfer"))
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return "Keine Dienste"
|
||||
}
|
||||
return strings.Join(parts, " · ")
|
||||
}
|
||||
|
||||
func pluralCount(n int, singular, plural string) string {
|
||||
if n == 1 {
|
||||
return "1× " + singular
|
||||
}
|
||||
return fmt.Sprintf("%d× %s", n, plural)
|
||||
}
|
||||
|
||||
func (t ServiceTemplate) IsValid(on time.Time) bool {
|
||||
if !t.Active {
|
||||
return false
|
||||
}
|
||||
day := Normalize(on)
|
||||
if Weekday(day) != t.Weekday {
|
||||
return false
|
||||
}
|
||||
if day.Before(Normalize(t.ValidFrom)) {
|
||||
return false
|
||||
}
|
||||
if t.ValidTo != nil && day.After(Normalize(*t.ValidTo)) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type ServiceException struct {
|
||||
ID string `json:"id"`
|
||||
TemplateID string `json:"templateID"`
|
||||
Date time.Time `json:"date"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
type ServiceKind string
|
||||
|
||||
const (
|
||||
KindRegular ServiceKind = "regular"
|
||||
KindSpecial ServiceKind = "special"
|
||||
)
|
||||
|
||||
func (k ServiceKind) Title() string {
|
||||
if k == KindSpecial {
|
||||
return "Sondergottesdienst"
|
||||
}
|
||||
return "Regulär"
|
||||
}
|
||||
|
||||
type ServiceOccurrence struct {
|
||||
ID string `json:"id"`
|
||||
ChurchID string `json:"churchID"`
|
||||
Location *string `json:"location"`
|
||||
TemplateID *string `json:"templateID"`
|
||||
Date time.Time `json:"date"`
|
||||
TimeMinutes int `json:"timeMinutes"`
|
||||
Title string `json:"title"`
|
||||
LectorsNeeded int `json:"lectorsNeeded"`
|
||||
HelpersNeeded int `json:"helpersNeeded"`
|
||||
Kind ServiceKind `json:"kind"`
|
||||
Notes string `json:"notes"`
|
||||
Locked bool `json:"locked"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
func (s ServiceOccurrence) PlaceName(church Church) string {
|
||||
if s.Location != nil && strings.TrimSpace(*s.Location) != "" {
|
||||
return *s.Location
|
||||
}
|
||||
return church.Name
|
||||
}
|
||||
|
||||
func (s ServiceOccurrence) TimeLabel() string { return TimeString(s.TimeMinutes) }
|
||||
func (s ServiceOccurrence) DateKey() string { return Key(s.Date) }
|
||||
func (s ServiceOccurrence) RequiredSlots() int {
|
||||
return s.LectorsNeeded + s.HelpersNeeded
|
||||
}
|
||||
func (s ServiceOccurrence) RequiredCount(role Role) int {
|
||||
if role == RoleHelper {
|
||||
return s.HelpersNeeded
|
||||
}
|
||||
return s.LectorsNeeded
|
||||
}
|
||||
func (s ServiceOccurrence) RolesNeeded() []Role {
|
||||
var roles []Role
|
||||
if s.LectorsNeeded > 0 {
|
||||
roles = append(roles, RoleLector)
|
||||
}
|
||||
if s.HelpersNeeded > 0 {
|
||||
roles = append(roles, RoleHelper)
|
||||
}
|
||||
return roles
|
||||
}
|
||||
|
||||
type Assignment struct {
|
||||
ID string `json:"id"`
|
||||
ServiceID string `json:"serviceID"`
|
||||
PersonID string `json:"personID"`
|
||||
Role Role `json:"role"`
|
||||
Locked bool `json:"locked"`
|
||||
Note string `json:"note"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
// Liturgical model ---------------------------------------------------------
|
||||
|
||||
type LiturgicalRank string
|
||||
|
||||
const (
|
||||
RankWeekday LiturgicalRank = ""
|
||||
RankMemorial LiturgicalRank = "g"
|
||||
RankObligatoryMemorial LiturgicalRank = "G"
|
||||
RankFeast LiturgicalRank = "F"
|
||||
RankSolemnity LiturgicalRank = "H"
|
||||
)
|
||||
|
||||
func (r LiturgicalRank) Label() string {
|
||||
switch r {
|
||||
case RankMemorial:
|
||||
return "Gedenktag"
|
||||
case RankObligatoryMemorial:
|
||||
return "Gebotener Gedenktag"
|
||||
case RankFeast:
|
||||
return "Fest"
|
||||
case RankSolemnity:
|
||||
return "Hochfest"
|
||||
default:
|
||||
return "Wochentag"
|
||||
}
|
||||
}
|
||||
|
||||
func (r LiturgicalRank) ShortLabel() string { return string(r) }
|
||||
func (r LiturgicalRank) Priority() int {
|
||||
switch r {
|
||||
case RankMemorial:
|
||||
return 1
|
||||
case RankObligatoryMemorial:
|
||||
return 2
|
||||
case RankFeast:
|
||||
return 3
|
||||
case RankSolemnity:
|
||||
return 4
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
func (r LiturgicalRank) IsFeast() bool { return r == RankFeast || r == RankSolemnity }
|
||||
|
||||
type LiturgicalColor string
|
||||
|
||||
const (
|
||||
ColorWhite LiturgicalColor = "w"
|
||||
ColorRed LiturgicalColor = "r"
|
||||
ColorGreen LiturgicalColor = "g"
|
||||
ColorViolet LiturgicalColor = "v"
|
||||
ColorRose LiturgicalColor = "ros"
|
||||
ColorBlack LiturgicalColor = "s"
|
||||
ColorGold LiturgicalColor = "gold"
|
||||
)
|
||||
|
||||
func (c LiturgicalColor) Label() string {
|
||||
switch c {
|
||||
case ColorRed:
|
||||
return "Rot"
|
||||
case ColorGreen:
|
||||
return "Grün"
|
||||
case ColorViolet:
|
||||
return "Violett"
|
||||
case ColorRose:
|
||||
return "Rosa"
|
||||
case ColorBlack:
|
||||
return "Schwarz"
|
||||
case ColorGold:
|
||||
return "Gold"
|
||||
default:
|
||||
return "Weiß"
|
||||
}
|
||||
}
|
||||
|
||||
func LiturgicalColorFromAPI(value string) LiturgicalColor {
|
||||
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||
case "r":
|
||||
return ColorRed
|
||||
case "g":
|
||||
return ColorGreen
|
||||
case "v":
|
||||
return ColorViolet
|
||||
case "ros", "rose":
|
||||
return ColorRose
|
||||
case "s", "sw":
|
||||
return ColorBlack
|
||||
case "gold":
|
||||
return ColorGold
|
||||
default:
|
||||
return ColorWhite
|
||||
}
|
||||
}
|
||||
|
||||
func LiturgicalColorHex(c LiturgicalColor) string {
|
||||
switch c {
|
||||
case ColorRed:
|
||||
return "#A5453F"
|
||||
case ColorGreen:
|
||||
return "#4F7D5A"
|
||||
case ColorViolet:
|
||||
return "#6E4B8E"
|
||||
case ColorRose:
|
||||
return "#C07A8B"
|
||||
case ColorBlack:
|
||||
return "#4A4440"
|
||||
default:
|
||||
return "#C2A14D"
|
||||
}
|
||||
}
|
||||
|
||||
type LiturgicalSeason string
|
||||
|
||||
const (
|
||||
SeasonAdvent LiturgicalSeason = "advent"
|
||||
SeasonChristmas LiturgicalSeason = "christmas"
|
||||
SeasonOrdinary LiturgicalSeason = "ordinary"
|
||||
SeasonLent LiturgicalSeason = "lent"
|
||||
SeasonEaster LiturgicalSeason = "easter"
|
||||
)
|
||||
|
||||
func (s LiturgicalSeason) Title() string {
|
||||
switch s {
|
||||
case SeasonAdvent:
|
||||
return "Advent"
|
||||
case SeasonChristmas:
|
||||
return "Weihnachtszeit"
|
||||
case SeasonLent:
|
||||
return "Österliche Bußzeit"
|
||||
case SeasonEaster:
|
||||
return "Osterzeit"
|
||||
default:
|
||||
return "Jahreskreis"
|
||||
}
|
||||
}
|
||||
|
||||
func (s LiturgicalSeason) ShortTitle() string {
|
||||
switch s {
|
||||
case SeasonAdvent:
|
||||
return "Advent"
|
||||
case SeasonChristmas:
|
||||
return "Weihnachten"
|
||||
case SeasonLent:
|
||||
return "Fastenzeit"
|
||||
case SeasonEaster:
|
||||
return "Osterzeit"
|
||||
default:
|
||||
return "Jahreskreis"
|
||||
}
|
||||
}
|
||||
|
||||
func (s LiturgicalSeason) ColorHex() string {
|
||||
switch s {
|
||||
case SeasonAdvent:
|
||||
return "#6E4B8E"
|
||||
case SeasonChristmas:
|
||||
return "#B58A3B"
|
||||
case SeasonLent:
|
||||
return "#75516F"
|
||||
case SeasonEaster:
|
||||
return "#C9A227"
|
||||
default:
|
||||
return "#4F7D5A"
|
||||
}
|
||||
}
|
||||
|
||||
type FeastSymbol string
|
||||
|
||||
const (
|
||||
FeastCross FeastSymbol = "cross"
|
||||
FeastStar FeastSymbol = "star"
|
||||
FeastFlame FeastSymbol = "flame"
|
||||
FeastSun FeastSymbol = "sun"
|
||||
FeastLily FeastSymbol = "lily"
|
||||
FeastCrown FeastSymbol = "crown"
|
||||
FeastHeart FeastSymbol = "heart"
|
||||
FeastBook FeastSymbol = "book"
|
||||
FeastCandle FeastSymbol = "candle"
|
||||
FeastDove FeastSymbol = "dove"
|
||||
)
|
||||
|
||||
func (f FeastSymbol) Label() string {
|
||||
switch f {
|
||||
case FeastCross:
|
||||
return "Kreuz"
|
||||
case FeastStar:
|
||||
return "Stern"
|
||||
case FeastFlame:
|
||||
return "Feuer"
|
||||
case FeastSun:
|
||||
return "Sonne"
|
||||
case FeastLily:
|
||||
return "Lilie"
|
||||
case FeastCrown:
|
||||
return "Krone"
|
||||
case FeastHeart:
|
||||
return "Herz"
|
||||
case FeastBook:
|
||||
return "Buch"
|
||||
case FeastCandle:
|
||||
return "Licht"
|
||||
case FeastDove:
|
||||
return "Taube"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
type Readings struct {
|
||||
First string `json:"first"`
|
||||
Psalm string `json:"psalm"`
|
||||
Second string `json:"second"`
|
||||
Gospel string `json:"gospel"`
|
||||
}
|
||||
|
||||
func (r Readings) IsEmpty() bool {
|
||||
return r.First == "" && r.Psalm == "" && r.Second == "" && r.Gospel == ""
|
||||
}
|
||||
|
||||
func (r Readings) ShortLabel() string {
|
||||
var parts []string
|
||||
if r.First != "" {
|
||||
parts = append(parts, r.First)
|
||||
}
|
||||
if r.Second != "" {
|
||||
parts = append(parts, r.Second)
|
||||
}
|
||||
if r.Gospel != "" {
|
||||
parts = append(parts, r.Gospel)
|
||||
}
|
||||
return strings.Join(parts, " · ")
|
||||
}
|
||||
|
||||
func (r Readings) FullLabel() string {
|
||||
var lines []string
|
||||
if r.First != "" {
|
||||
lines = append(lines, "1. Lesung: "+r.First)
|
||||
}
|
||||
if r.Psalm != "" {
|
||||
lines = append(lines, "Psalm: "+r.Psalm)
|
||||
}
|
||||
if r.Second != "" {
|
||||
lines = append(lines, "2. Lesung: "+r.Second)
|
||||
}
|
||||
if r.Gospel != "" {
|
||||
lines = append(lines, "Evangelium: "+r.Gospel)
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
type LiturgicalDay struct {
|
||||
Date time.Time `json:"date"`
|
||||
Title string `json:"title"`
|
||||
Rank LiturgicalRank `json:"rank"`
|
||||
Color LiturgicalColor `json:"color"`
|
||||
Remark string `json:"remark"`
|
||||
Readings Readings `json:"readings"`
|
||||
IsObligation bool `json:"isObligation"`
|
||||
Source string `json:"source"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
func (d LiturgicalDay) DateKey() string { return Key(d.Date) }
|
||||
func (d LiturgicalDay) IsSunday() bool { return IsSunday(d.Date) }
|
||||
func (d LiturgicalDay) IsHighFeast() bool {
|
||||
return d.Rank == RankSolemnity || strings.Contains(strings.ToLower(d.Title), "hochfest")
|
||||
}
|
||||
func (d LiturgicalDay) IsFeast() bool { return d.Rank.IsFeast() || d.IsHighFeast() }
|
||||
func (d LiturgicalDay) Season() LiturgicalSeason {
|
||||
return SeasonFor(d.Date)
|
||||
}
|
||||
func (d LiturgicalDay) Symbol() FeastSymbol {
|
||||
return SymbolFor(d.Title, d.Rank, d.Date)
|
||||
}
|
||||
func (d LiturgicalDay) DisplayTitle() string {
|
||||
if d.Title == "" {
|
||||
if d.IsSunday() {
|
||||
return "Sonntag"
|
||||
}
|
||||
return LongString(d.Date)
|
||||
}
|
||||
return d.Title
|
||||
}
|
||||
func (d LiturgicalDay) BadgeText() string {
|
||||
if d.IsSunday() && d.IsObligation {
|
||||
return "Sonntag"
|
||||
}
|
||||
if d.Rank != RankWeekday {
|
||||
return d.Rank.Label()
|
||||
}
|
||||
if d.IsObligation {
|
||||
return "Gebotener Feiertag"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (d LiturgicalDay) ColorHex() string { return LiturgicalColorHex(d.Color) }
|
||||
|
||||
// View support -------------------------------------------------------------
|
||||
|
||||
type ServiceWithAssignments struct {
|
||||
Service ServiceOccurrence
|
||||
Church Church
|
||||
Assignments []Assignment
|
||||
}
|
||||
|
||||
func (s ServiceWithAssignments) AssignmentsFor(role Role) []Assignment {
|
||||
var out []Assignment
|
||||
for _, a := range s.Assignments {
|
||||
if a.Role == role {
|
||||
out = append(out, a)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s ServiceWithAssignments) OpenSlotsFor(role Role) int {
|
||||
open := s.Service.RequiredCount(role) - len(s.AssignmentsFor(role))
|
||||
if open < 0 {
|
||||
return 0
|
||||
}
|
||||
return open
|
||||
}
|
||||
|
||||
func (s ServiceWithAssignments) FilledSlots() int { return len(s.Assignments) }
|
||||
func (s ServiceWithAssignments) OpenSlots() int {
|
||||
open := s.Service.RequiredSlots() - len(s.Assignments)
|
||||
if open < 0 {
|
||||
return 0
|
||||
}
|
||||
return open
|
||||
}
|
||||
func (s ServiceWithAssignments) IsFullyStaffed() bool { return s.OpenSlots() == 0 }
|
||||
|
||||
type DayPlanRow struct {
|
||||
Date time.Time
|
||||
LiturgicalDay *LiturgicalDay
|
||||
Services []ServiceWithAssignments
|
||||
}
|
||||
|
||||
func (r DayPlanRow) DateKey() string { return Key(r.Date) }
|
||||
func (r DayPlanRow) OpenSlots() int {
|
||||
total := 0
|
||||
for _, s := range r.Services {
|
||||
total += s.OpenSlots()
|
||||
}
|
||||
return total
|
||||
}
|
||||
func (r DayPlanRow) AssignmentCount() int {
|
||||
total := 0
|
||||
for _, s := range r.Services {
|
||||
total += len(s.Assignments)
|
||||
}
|
||||
return total
|
||||
}
|
||||
func (r DayPlanRow) HasServices() bool { return len(r.Services) > 0 }
|
||||
|
||||
func (r DayPlanRow) IsSunday() bool {
|
||||
return (r.LiturgicalDay != nil && r.LiturgicalDay.IsSunday()) || IsSunday(r.Date)
|
||||
}
|
||||
func (r DayPlanRow) IsHighFeast() bool {
|
||||
return r.LiturgicalDay != nil && r.LiturgicalDay.IsHighFeast()
|
||||
}
|
||||
func (r DayPlanRow) IsFeast() bool {
|
||||
return r.LiturgicalDay != nil && r.LiturgicalDay.IsFeast()
|
||||
}
|
||||
func (r DayPlanRow) IsSpecialDay() bool {
|
||||
if r.IsSunday() || r.IsFeast() {
|
||||
return true
|
||||
}
|
||||
return r.LiturgicalDay != nil && r.LiturgicalDay.IsObligation
|
||||
}
|
||||
func (r DayPlanRow) IsObligation() bool {
|
||||
return r.LiturgicalDay != nil && r.LiturgicalDay.IsObligation
|
||||
}
|
||||
|
||||
func (r DayPlanRow) ServicesForChurch(churchID string) []ServiceWithAssignments {
|
||||
var out []ServiceWithAssignments
|
||||
for _, s := range r.Services {
|
||||
if s.Church.ID == churchID {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type UnfilledSlot struct {
|
||||
Service ServiceOccurrence
|
||||
ChurchName string
|
||||
Role Role
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (u UnfilledSlot) ID() string { return u.Service.ID + "-" + string(u.Role) }
|
||||
|
||||
type PersonStat struct {
|
||||
Person Person
|
||||
Total int
|
||||
Lectors int
|
||||
Helpers int
|
||||
ChurchCounts map[string]int
|
||||
PreferredHits int
|
||||
SundayCount int
|
||||
LastAssignment *time.Time
|
||||
}
|
||||
|
||||
func (s PersonStat) PreferenceRate() float64 {
|
||||
if s.Total == 0 {
|
||||
return 0
|
||||
}
|
||||
return float64(s.PreferredHits) / float64(s.Total)
|
||||
}
|
||||
|
||||
type ChurchStat struct {
|
||||
Church Church
|
||||
Assignments int
|
||||
Services int
|
||||
OpenSlots int
|
||||
PersonCount int
|
||||
}
|
||||
|
||||
type RangeStatistics struct {
|
||||
Range DayRange
|
||||
ServiceCount int
|
||||
AssignmentCount int
|
||||
OpenSlots int
|
||||
RequiredSlots int
|
||||
PersonStats []PersonStat
|
||||
ChurchStats []ChurchStat
|
||||
MonthlyCounts map[string]int
|
||||
SundayServiceCount int
|
||||
SundayFilled int
|
||||
PreferenceHits int
|
||||
PreferenceEligible int
|
||||
AbsenceDays int
|
||||
}
|
||||
|
||||
func (s RangeStatistics) CoverageRate() float64 {
|
||||
if s.RequiredSlots == 0 {
|
||||
return 1
|
||||
}
|
||||
return float64(s.AssignmentCount) / float64(s.RequiredSlots)
|
||||
}
|
||||
|
||||
func (s RangeStatistics) PreferenceRate() float64 {
|
||||
if s.PreferenceEligible == 0 {
|
||||
return 0
|
||||
}
|
||||
return float64(s.PreferenceHits) / float64(s.PreferenceEligible)
|
||||
}
|
||||
|
||||
func (s RangeStatistics) ActivePeople() int {
|
||||
n := 0
|
||||
for _, p := range s.PersonStats {
|
||||
if p.Total > 0 {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (s RangeStatistics) AverageAssignments() float64 {
|
||||
count, total := 0, 0
|
||||
for _, p := range s.PersonStats {
|
||||
if p.Total > 0 {
|
||||
count++
|
||||
total += p.Total
|
||||
}
|
||||
}
|
||||
if count == 0 {
|
||||
return 0
|
||||
}
|
||||
return float64(total) / float64(count)
|
||||
}
|
||||
|
||||
type PlannerOptions struct {
|
||||
ReplaceExisting bool
|
||||
RespectPreferredWeekdays bool
|
||||
AllowDoubleRolesOnSameDay bool
|
||||
WeightChurchPreference float64
|
||||
WeightServicePreference float64
|
||||
WeightFairness float64
|
||||
WeightDualRolePreference float64
|
||||
MaxAssignmentsPerDay int
|
||||
}
|
||||
|
||||
func DefaultPlannerOptions() PlannerOptions {
|
||||
return PlannerOptions{
|
||||
RespectPreferredWeekdays: true,
|
||||
WeightChurchPreference: 8,
|
||||
WeightServicePreference: 4,
|
||||
WeightFairness: 2.2,
|
||||
WeightDualRolePreference: 14,
|
||||
MaxAssignmentsPerDay: 1,
|
||||
}
|
||||
}
|
||||
|
||||
type PlanResult struct {
|
||||
Assignments []Assignment
|
||||
Unfilled []UnfilledSlot
|
||||
FilledCount int
|
||||
Message string
|
||||
}
|
||||
|
||||
type CandidateSuggestion struct {
|
||||
Person Person
|
||||
Score float64
|
||||
Warnings []string
|
||||
Blocked bool
|
||||
Preferred bool
|
||||
TotalAssignments int
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ServicePlanner implements the automatic assignment rules of the macOS app.
|
||||
type ServicePlanner struct {
|
||||
People []Person
|
||||
Absences []Absence
|
||||
Services []ServiceOccurrence
|
||||
ExistingAssignments []Assignment
|
||||
Churches []Church
|
||||
Options PlannerOptions
|
||||
}
|
||||
|
||||
type candidateResult struct {
|
||||
person *Person
|
||||
reason string
|
||||
}
|
||||
|
||||
func (p ServicePlanner) Plan() PlanResult {
|
||||
activePeople := make([]Person, 0, len(p.People))
|
||||
for _, person := range p.People {
|
||||
if person.Active {
|
||||
activePeople = append(activePeople, person)
|
||||
}
|
||||
}
|
||||
absencesByPerson := map[string][]Absence{}
|
||||
for _, a := range p.Absences {
|
||||
absencesByPerson[a.PersonID] = append(absencesByPerson[a.PersonID], a)
|
||||
}
|
||||
churchNames := map[string]string{}
|
||||
for _, c := range p.Churches {
|
||||
churchNames[c.ID] = c.Name
|
||||
}
|
||||
serviceByID := map[string]ServiceOccurrence{}
|
||||
for _, s := range p.Services {
|
||||
serviceByID[s.ID] = s
|
||||
}
|
||||
|
||||
working := make([]Assignment, 0, len(p.ExistingAssignments))
|
||||
for _, a := range p.ExistingAssignments {
|
||||
if !p.Options.ReplaceExisting || a.Locked {
|
||||
working = append(working, a)
|
||||
}
|
||||
}
|
||||
|
||||
totalByPerson := map[string]int{}
|
||||
monthByPerson := map[string]int{}
|
||||
dayServicesByPerson := map[string]map[string]bool{}
|
||||
churchByPerson := map[string]map[string]int{}
|
||||
lastDateByPerson := map[string]time.Time{}
|
||||
roleCounts := map[string]map[Role]int{}
|
||||
rolesByServicePerson := map[string]map[string]map[Role]bool{}
|
||||
|
||||
applyToCounts := func(a Assignment, s ServiceOccurrence) {
|
||||
totalByPerson[a.PersonID]++
|
||||
monthByPerson[a.PersonID+"|"+MonthKey(s.Date)]++
|
||||
key := a.PersonID + "|" + s.DateKey()
|
||||
if dayServicesByPerson[key] == nil {
|
||||
dayServicesByPerson[key] = map[string]bool{}
|
||||
}
|
||||
dayServicesByPerson[key][s.ID] = true
|
||||
if churchByPerson[a.PersonID] == nil {
|
||||
churchByPerson[a.PersonID] = map[string]int{}
|
||||
}
|
||||
churchByPerson[a.PersonID][s.ChurchID]++
|
||||
if previous, ok := lastDateByPerson[a.PersonID]; !ok || s.Date.After(previous) {
|
||||
lastDateByPerson[a.PersonID] = s.Date
|
||||
}
|
||||
}
|
||||
|
||||
for _, a := range working {
|
||||
s, ok := serviceByID[a.ServiceID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
applyToCounts(a, s)
|
||||
if roleCounts[s.ID] == nil {
|
||||
roleCounts[s.ID] = map[Role]int{}
|
||||
}
|
||||
roleCounts[s.ID][a.Role]++
|
||||
if rolesByServicePerson[s.ID] == nil {
|
||||
rolesByServicePerson[s.ID] = map[string]map[Role]bool{}
|
||||
}
|
||||
if rolesByServicePerson[s.ID][a.PersonID] == nil {
|
||||
rolesByServicePerson[s.ID][a.PersonID] = map[Role]bool{}
|
||||
}
|
||||
rolesByServicePerson[s.ID][a.PersonID][a.Role] = true
|
||||
}
|
||||
|
||||
sortedServices := make([]ServiceOccurrence, len(p.Services))
|
||||
copy(sortedServices, p.Services)
|
||||
sort.SliceStable(sortedServices, func(i, j int) bool {
|
||||
a, b := sortedServices[i], sortedServices[j]
|
||||
if !a.Date.Equal(b.Date) {
|
||||
return a.Date.Before(b.Date)
|
||||
}
|
||||
if a.TimeMinutes != b.TimeMinutes {
|
||||
return a.TimeMinutes < b.TimeMinutes
|
||||
}
|
||||
return a.ID < b.ID
|
||||
})
|
||||
|
||||
var unfilled []UnfilledSlot
|
||||
var newAssignments []Assignment
|
||||
|
||||
for _, service := range sortedServices {
|
||||
assignedRoles := rolesByServicePerson[service.ID]
|
||||
if assignedRoles == nil {
|
||||
assignedRoles = map[string]map[Role]bool{}
|
||||
rolesByServicePerson[service.ID] = assignedRoles
|
||||
}
|
||||
|
||||
for _, role := range AllRoles {
|
||||
required := service.RequiredCount(role)
|
||||
if required <= 0 {
|
||||
continue
|
||||
}
|
||||
existingForRole := 0
|
||||
if roleCounts[service.ID] != nil {
|
||||
existingForRole = roleCounts[service.ID][role]
|
||||
}
|
||||
if existingForRole >= required {
|
||||
continue
|
||||
}
|
||||
for i := existingForRole; i < required; i++ {
|
||||
result := p.bestCandidate(service, role, activePeople, absencesByPerson,
|
||||
totalByPerson, monthByPerson, dayServicesByPerson, churchByPerson,
|
||||
lastDateByPerson, assignedRoles)
|
||||
if result.person == nil {
|
||||
unfilled = append(unfilled, UnfilledSlot{
|
||||
Service: service,
|
||||
ChurchName: churchNames[service.ChurchID],
|
||||
Role: role,
|
||||
Reason: result.reason,
|
||||
})
|
||||
continue
|
||||
}
|
||||
person := *result.person
|
||||
assignment := Assignment{
|
||||
ID: newID(),
|
||||
ServiceID: service.ID,
|
||||
PersonID: person.ID,
|
||||
Role: role,
|
||||
CreatedAt: now(),
|
||||
}
|
||||
newAssignments = append(newAssignments, assignment)
|
||||
working = append(working, assignment)
|
||||
|
||||
if roleCounts[service.ID] == nil {
|
||||
roleCounts[service.ID] = map[Role]int{}
|
||||
}
|
||||
roleCounts[service.ID][role]++
|
||||
if assignedRoles[person.ID] == nil {
|
||||
assignedRoles[person.ID] = map[Role]bool{}
|
||||
}
|
||||
assignedRoles[person.ID][role] = true
|
||||
applyToCounts(assignment, service)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
filled := len(newAssignments)
|
||||
var message string
|
||||
switch {
|
||||
case filled == 0 && len(unfilled) == 0:
|
||||
message = "Alle Dienste im Zeitraum sind bereits vollständig besetzt."
|
||||
case len(unfilled) == 0:
|
||||
suffix := "e"
|
||||
if filled == 1 {
|
||||
suffix = ""
|
||||
}
|
||||
message = fmt.Sprintf("%d Dienst%s erfolgreich besetzt. Alle Lücken geschlossen.", filled, suffix)
|
||||
default:
|
||||
suffix := "e"
|
||||
if filled == 1 {
|
||||
suffix = ""
|
||||
}
|
||||
gapSuffix := "n"
|
||||
if len(unfilled) == 1 {
|
||||
gapSuffix = ""
|
||||
}
|
||||
message = fmt.Sprintf("%d Dienst%s besetzt, %d Lücke%s bleiben offen.", filled, suffix, len(unfilled), gapSuffix)
|
||||
}
|
||||
|
||||
if p.Options.ReplaceExisting {
|
||||
var locked []Assignment
|
||||
for _, a := range working {
|
||||
if a.Locked {
|
||||
locked = append(locked, a)
|
||||
}
|
||||
}
|
||||
return PlanResult{Assignments: append(locked, newAssignments...), Unfilled: unfilled, FilledCount: filled, Message: message}
|
||||
}
|
||||
return PlanResult{Assignments: working, Unfilled: unfilled, FilledCount: filled, Message: message}
|
||||
}
|
||||
|
||||
func (p ServicePlanner) bestCandidate(
|
||||
service ServiceOccurrence,
|
||||
role Role,
|
||||
people []Person,
|
||||
absencesByPerson map[string][]Absence,
|
||||
totalByPerson map[string]int,
|
||||
monthByPerson map[string]int,
|
||||
dayServicesByPerson map[string]map[string]bool,
|
||||
churchByPerson map[string]map[string]int,
|
||||
lastDateByPerson map[string]time.Time,
|
||||
assignedRolesByPerson map[string]map[Role]bool,
|
||||
) candidateResult {
|
||||
blockedReasons := map[string]int{}
|
||||
var eligible []Person
|
||||
|
||||
for _, person := range people {
|
||||
if !person.CanFill(role) {
|
||||
continue
|
||||
}
|
||||
roles := assignedRolesByPerson[person.ID]
|
||||
if roles != nil && roles[role] {
|
||||
blockedReasons["bereits für diesen Dienst eingeteilt"]++
|
||||
continue
|
||||
}
|
||||
if absences, ok := absencesByPerson[person.ID]; ok {
|
||||
blocked := false
|
||||
for _, a := range absences {
|
||||
if a.Overlaps(service.Date) {
|
||||
blocked = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if blocked {
|
||||
blockedReasons["abwesend"]++
|
||||
continue
|
||||
}
|
||||
}
|
||||
if p.Options.RespectPreferredWeekdays && len(person.PreferredWeekdays) > 0 &&
|
||||
!IntContains(person.PreferredWeekdays, Weekday(service.Date)) {
|
||||
blockedReasons["Einsatztag passt nicht"]++
|
||||
continue
|
||||
}
|
||||
month := MonthKey(service.Date)
|
||||
usedThisMonth := monthByPerson[person.ID+"|"+month]
|
||||
if person.MaxPerMonth > 0 && usedThisMonth >= person.MaxPerMonth {
|
||||
blockedReasons["Monatslimit erreicht"]++
|
||||
continue
|
||||
}
|
||||
usedServices := dayServicesByPerson[person.ID+"|"+service.DateKey()]
|
||||
maxPerDay := p.Options.MaxAssignmentsPerDay
|
||||
if len(usedServices) >= maxPerDay && !subsetOfSingle(usedServices, service.ID) {
|
||||
blockedReasons["bereits an diesem Tag"]++
|
||||
continue
|
||||
}
|
||||
eligible = append(eligible, person)
|
||||
}
|
||||
|
||||
minimumTotal := 0
|
||||
if len(eligible) > 0 {
|
||||
minimumTotal = totalByPerson[eligible[0].ID]
|
||||
for _, person := range eligible[1:] {
|
||||
if totalByPerson[person.ID] < minimumTotal {
|
||||
minimumTotal = totalByPerson[person.ID]
|
||||
}
|
||||
}
|
||||
}
|
||||
const fairnessSlack = 1
|
||||
|
||||
var bestPerson *Person
|
||||
bestScore := 0.0
|
||||
haveBest := false
|
||||
|
||||
for i := range eligible {
|
||||
person := eligible[i]
|
||||
roles := assignedRolesByPerson[person.ID]
|
||||
total := totalByPerson[person.ID]
|
||||
withinFairnessReach := total-minimumTotal <= fairnessSlack
|
||||
|
||||
score := 10.0
|
||||
if withinFairnessReach && roles != nil && roles[role.Complementary()] {
|
||||
score += p.Options.WeightDualRolePreference
|
||||
} else if withinFairnessReach && len(service.RolesNeeded()) > 1 {
|
||||
for _, other := range AllRoles {
|
||||
if other != role && service.RequiredCount(other) > 0 && person.CanFill(other) {
|
||||
score += p.Options.WeightDualRolePreference
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if StringContains(person.PreferredChurchIDs, service.ChurchID) {
|
||||
score += p.Options.WeightChurchPreference
|
||||
}
|
||||
if len(person.PreferredChurchIDs) > 0 && !StringContains(person.PreferredChurchIDs, service.ChurchID) {
|
||||
score -= 1.5
|
||||
}
|
||||
if len(person.PreferredServiceTitles) > 0 {
|
||||
title := strings.ToLower(service.Title)
|
||||
for _, preference := range person.PreferredServiceTitles {
|
||||
if preference != "" && strings.Contains(strings.ToLower(title), strings.ToLower(preference)) {
|
||||
score += p.Options.WeightServicePreference
|
||||
}
|
||||
}
|
||||
}
|
||||
if IntContains(person.PreferredWeekdays, Weekday(service.Date)) {
|
||||
score += 3
|
||||
}
|
||||
score -= float64(total) * p.Options.WeightFairness
|
||||
if counts, ok := churchByPerson[person.ID]; ok {
|
||||
score -= float64(counts[service.ChurchID]) * 0.4
|
||||
}
|
||||
if last, ok := lastDateByPerson[person.ID]; ok {
|
||||
gap := DaysBetween(last, service.Date)
|
||||
if gap >= 14 {
|
||||
score += 1.8
|
||||
} else if gap >= 7 {
|
||||
score += 0.8
|
||||
}
|
||||
} else {
|
||||
score += 2.5
|
||||
}
|
||||
score += stableTieBreak(person.ID + "|" + service.ID + "|" + string(role))
|
||||
|
||||
if !haveBest || score > bestScore {
|
||||
bestScore = score
|
||||
cp := person
|
||||
bestPerson = &cp
|
||||
haveBest = true
|
||||
}
|
||||
}
|
||||
|
||||
if bestPerson != nil {
|
||||
return candidateResult{person: bestPerson}
|
||||
}
|
||||
|
||||
reason := "Keine geeignete Person"
|
||||
if len(blockedReasons) == 0 {
|
||||
reason = "Keine geeignete Person mit Rolle " + role.Title()
|
||||
} else {
|
||||
topKey, topCount := "", -1
|
||||
for key, count := range blockedReasons {
|
||||
if count > topCount {
|
||||
topKey, topCount = key, count
|
||||
}
|
||||
}
|
||||
reason = fmt.Sprintf("%s (%d ausgeschlossen)", topKey, topCount)
|
||||
}
|
||||
return candidateResult{reason: reason}
|
||||
}
|
||||
|
||||
func subsetOfSingle(set map[string]bool, value string) bool {
|
||||
if len(set) == 0 {
|
||||
return true
|
||||
}
|
||||
if len(set) > 1 {
|
||||
return false
|
||||
}
|
||||
return set[value]
|
||||
}
|
||||
|
||||
func stableTieBreak(value string) float64 {
|
||||
var hash uint32 = 5381
|
||||
for _, b := range []byte(value) {
|
||||
hash = (hash << 5) + hash + uint32(b)
|
||||
}
|
||||
return float64(hash%997) / 100000
|
||||
}
|
||||
|
||||
// CandidateSuggestions mirrors the macOS detail sheet's suggestion list.
|
||||
func CandidateSuggestions(
|
||||
service ServiceOccurrence,
|
||||
role Role,
|
||||
people []Person,
|
||||
absences []Absence,
|
||||
rangeAssignments []Assignment,
|
||||
services []ServiceOccurrence,
|
||||
serviceAssignments []Assignment,
|
||||
ignorePreferredWeekdays bool,
|
||||
) []CandidateSuggestion {
|
||||
monthKey := MonthKey(service.Date)
|
||||
serviceDateByID := map[string]ServiceOccurrence{}
|
||||
for _, s := range services {
|
||||
serviceDateByID[s.ID] = s
|
||||
}
|
||||
monthlyCounts := map[string]int{}
|
||||
totalCounts := map[string]int{}
|
||||
dayServices := map[string]map[string]bool{}
|
||||
for _, a := range rangeAssignments {
|
||||
s, ok := serviceDateByID[a.ServiceID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
monthlyCounts[a.PersonID+"|"+MonthKey(s.Date)]++
|
||||
totalCounts[a.PersonID]++
|
||||
key := a.PersonID + "|" + s.DateKey()
|
||||
if dayServices[key] == nil {
|
||||
dayServices[key] = map[string]bool{}
|
||||
}
|
||||
dayServices[key][a.ServiceID] = true
|
||||
}
|
||||
assignedRoles := map[string]map[Role]bool{}
|
||||
for _, a := range serviceAssignments {
|
||||
if assignedRoles[a.PersonID] == nil {
|
||||
assignedRoles[a.PersonID] = map[Role]bool{}
|
||||
}
|
||||
assignedRoles[a.PersonID][a.Role] = true
|
||||
}
|
||||
|
||||
var eligible []Person
|
||||
for _, person := range people {
|
||||
if person.Active && person.CanFill(role) && !(assignedRoles[person.ID] != nil && assignedRoles[person.ID][role]) {
|
||||
eligible = append(eligible, person)
|
||||
}
|
||||
}
|
||||
minimumTotal := 0
|
||||
if len(eligible) > 0 {
|
||||
minimumTotal = totalCounts[eligible[0].ID]
|
||||
for _, person := range eligible[1:] {
|
||||
if totalCounts[person.ID] < minimumTotal {
|
||||
minimumTotal = totalCounts[person.ID]
|
||||
}
|
||||
}
|
||||
}
|
||||
const fairnessSlack = 1
|
||||
weekday := Weekday(service.Date)
|
||||
|
||||
var suggestions []CandidateSuggestion
|
||||
for _, person := range eligible {
|
||||
var warnings []string
|
||||
blocked := false
|
||||
for _, a := range absences {
|
||||
if a.PersonID == person.ID && a.Overlaps(service.Date) {
|
||||
warnings = append(warnings, "abwesend")
|
||||
blocked = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !ignorePreferredWeekdays && len(person.PreferredWeekdays) > 0 && !IntContains(person.PreferredWeekdays, weekday) {
|
||||
warnings = append(warnings, "Einsatztag passt nicht")
|
||||
blocked = true
|
||||
}
|
||||
if person.MaxPerMonth > 0 && monthlyCounts[person.ID+"|"+monthKey] >= person.MaxPerMonth {
|
||||
warnings = append(warnings, "Monatslimit")
|
||||
blocked = true
|
||||
}
|
||||
used := dayServices[person.ID+"|"+service.DateKey()]
|
||||
if len(used) > 0 && !subsetOfSingle(used, service.ID) {
|
||||
warnings = append(warnings, "bereits an diesem Tag")
|
||||
blocked = true
|
||||
}
|
||||
|
||||
total := totalCounts[person.ID]
|
||||
within := total-minimumTotal <= fairnessSlack
|
||||
score := 0.0
|
||||
preferred := false
|
||||
if within && assignedRoles[person.ID] != nil && assignedRoles[person.ID][role.Complementary()] {
|
||||
score += 14
|
||||
preferred = true
|
||||
} else if within && len(service.RolesNeeded()) > 1 {
|
||||
for _, other := range AllRoles {
|
||||
if other != role && service.RequiredCount(other) > 0 && person.CanFill(other) {
|
||||
score += 14
|
||||
preferred = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if StringContains(person.PreferredChurchIDs, service.ChurchID) {
|
||||
score += 8
|
||||
preferred = true
|
||||
}
|
||||
if len(person.PreferredChurchIDs) > 0 && !StringContains(person.PreferredChurchIDs, service.ChurchID) {
|
||||
score -= 2
|
||||
}
|
||||
if IntContains(person.PreferredWeekdays, weekday) {
|
||||
score += 3
|
||||
preferred = true
|
||||
}
|
||||
for _, preference := range person.PreferredServiceTitles {
|
||||
if preference != "" && strings.Contains(strings.ToLower(service.Title), strings.ToLower(preference)) {
|
||||
score += 4
|
||||
preferred = true
|
||||
}
|
||||
}
|
||||
score -= float64(total) * 1.4
|
||||
for _, a := range absences {
|
||||
if a.PersonID == person.ID && a.Overlaps(service.Date) {
|
||||
score -= 100
|
||||
break
|
||||
}
|
||||
}
|
||||
suggestions = append(suggestions, CandidateSuggestion{
|
||||
Person: person, Score: score, Warnings: warnings, Blocked: blocked,
|
||||
Preferred: preferred, TotalAssignments: total,
|
||||
})
|
||||
}
|
||||
|
||||
sort.SliceStable(suggestions, func(i, j int) bool {
|
||||
a, b := suggestions[i], suggestions[j]
|
||||
if a.Blocked != b.Blocked {
|
||||
return !a.Blocked
|
||||
}
|
||||
if a.Score != b.Score {
|
||||
return a.Score > b.Score
|
||||
}
|
||||
return a.Person.LastName < b.Person.LastName
|
||||
})
|
||||
return suggestions
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type StatisticsCalculator struct{}
|
||||
|
||||
func ComputeStatistics(
|
||||
r DayRange,
|
||||
services []ServiceOccurrence,
|
||||
assignments []Assignment,
|
||||
people []Person,
|
||||
churches []Church,
|
||||
absences []Absence,
|
||||
) RangeStatistics {
|
||||
servicesByID := map[string]ServiceOccurrence{}
|
||||
for _, s := range services {
|
||||
servicesByID[s.ID] = s
|
||||
}
|
||||
peopleByID := map[string]Person{}
|
||||
for _, p := range people {
|
||||
peopleByID[p.ID] = p
|
||||
}
|
||||
assignmentsByPerson := map[string][]Assignment{}
|
||||
for _, a := range assignments {
|
||||
assignmentsByPerson[a.PersonID] = append(assignmentsByPerson[a.PersonID], a)
|
||||
}
|
||||
assignmentsByService := map[string][]Assignment{}
|
||||
for _, a := range assignments {
|
||||
assignmentsByService[a.ServiceID] = append(assignmentsByService[a.ServiceID], a)
|
||||
}
|
||||
|
||||
personStats := make([]PersonStat, 0, len(people))
|
||||
for _, person := range people {
|
||||
own := assignmentsByPerson[person.ID]
|
||||
lectors, helpers := 0, 0
|
||||
churchCounts := map[string]int{}
|
||||
preferredHits, sundays := 0, 0
|
||||
var lastDate *time.Time
|
||||
for _, a := range own {
|
||||
service, ok := servicesByID[a.ServiceID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if a.Role == RoleLector {
|
||||
lectors++
|
||||
} else {
|
||||
helpers++
|
||||
}
|
||||
churchCounts[service.ChurchID]++
|
||||
if IsSunday(service.Date) {
|
||||
sundays++
|
||||
}
|
||||
if lastDate == nil || service.Date.After(*lastDate) {
|
||||
d := service.Date
|
||||
lastDate = &d
|
||||
}
|
||||
if PreferenceHit(person, service) {
|
||||
preferredHits++
|
||||
}
|
||||
}
|
||||
stat := PersonStat{
|
||||
Person: person, Total: len(own), Lectors: lectors, Helpers: helpers,
|
||||
ChurchCounts: churchCounts, PreferredHits: preferredHits, SundayCount: sundays,
|
||||
}
|
||||
if lastDate != nil {
|
||||
stat.LastAssignment = lastDate
|
||||
}
|
||||
personStats = append(personStats, stat)
|
||||
}
|
||||
sort.SliceStable(personStats, func(i, j int) bool {
|
||||
if personStats[i].Total != personStats[j].Total {
|
||||
return personStats[i].Total > personStats[j].Total
|
||||
}
|
||||
return personStats[i].Person.LastName < personStats[j].Person.LastName
|
||||
})
|
||||
|
||||
churchStats := make([]ChurchStat, 0, len(churches))
|
||||
for _, church := range churches {
|
||||
var churchServices []ServiceOccurrence
|
||||
serviceIDs := map[string]bool{}
|
||||
for _, s := range services {
|
||||
if s.ChurchID == church.ID {
|
||||
churchServices = append(churchServices, s)
|
||||
serviceIDs[s.ID] = true
|
||||
}
|
||||
}
|
||||
churchAssignments := 0
|
||||
personIDs := map[string]bool{}
|
||||
for _, a := range assignments {
|
||||
if serviceIDs[a.ServiceID] {
|
||||
churchAssignments++
|
||||
personIDs[a.PersonID] = true
|
||||
}
|
||||
}
|
||||
open := 0
|
||||
for _, s := range churchServices {
|
||||
remaining := s.RequiredSlots() - len(assignmentsByService[s.ID])
|
||||
if remaining > 0 {
|
||||
open += remaining
|
||||
}
|
||||
}
|
||||
churchStats = append(churchStats, ChurchStat{
|
||||
Church: church, Assignments: churchAssignments, Services: len(churchServices),
|
||||
OpenSlots: open, PersonCount: len(personIDs),
|
||||
})
|
||||
}
|
||||
sort.SliceStable(churchStats, func(i, j int) bool {
|
||||
return churchStats[i].Church.SortIndex < churchStats[j].Church.SortIndex
|
||||
})
|
||||
|
||||
monthly := map[string]int{}
|
||||
for _, a := range assignments {
|
||||
s, ok := servicesByID[a.ServiceID]
|
||||
if ok {
|
||||
monthly[MonthKey(s.Date)]++
|
||||
}
|
||||
}
|
||||
|
||||
sundayServiceCount := 0
|
||||
sundayIDs := map[string]bool{}
|
||||
for _, s := range services {
|
||||
if IsSunday(s.Date) {
|
||||
sundayServiceCount++
|
||||
sundayIDs[s.ID] = true
|
||||
}
|
||||
}
|
||||
sundayFilled := 0
|
||||
for _, a := range assignments {
|
||||
if sundayIDs[a.ServiceID] {
|
||||
sundayFilled++
|
||||
}
|
||||
}
|
||||
requiredSlots := 0
|
||||
for _, s := range services {
|
||||
requiredSlots += s.RequiredSlots()
|
||||
}
|
||||
openSlots := requiredSlots - len(assignments)
|
||||
if openSlots < 0 {
|
||||
openSlots = 0
|
||||
}
|
||||
|
||||
preferenceHits, preferenceEligible := 0, 0
|
||||
for _, a := range assignments {
|
||||
s, ok := servicesByID[a.ServiceID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
person, ok := peopleByID[a.PersonID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if person.HasPreference() {
|
||||
preferenceEligible++
|
||||
if PreferenceHit(person, s) {
|
||||
preferenceHits++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
active := map[string]bool{}
|
||||
for _, p := range people {
|
||||
if p.Active {
|
||||
active[p.ID] = true
|
||||
}
|
||||
}
|
||||
absenceDays := 0
|
||||
for _, a := range absences {
|
||||
if !active[a.PersonID] {
|
||||
continue
|
||||
}
|
||||
clamped := a.Range().Clamped(r)
|
||||
if !clamped.Start.After(clamped.End) {
|
||||
absenceDays += clamped.DayCount()
|
||||
}
|
||||
}
|
||||
|
||||
return RangeStatistics{
|
||||
Range: r, ServiceCount: len(services), AssignmentCount: len(assignments),
|
||||
OpenSlots: openSlots, RequiredSlots: requiredSlots, PersonStats: personStats,
|
||||
ChurchStats: churchStats, MonthlyCounts: monthly, SundayServiceCount: sundayServiceCount,
|
||||
SundayFilled: sundayFilled, PreferenceHits: preferenceHits,
|
||||
PreferenceEligible: preferenceEligible, AbsenceDays: absenceDays,
|
||||
}
|
||||
}
|
||||
|
||||
func PreferenceHit(person Person, service ServiceOccurrence) bool {
|
||||
if StringContains(person.PreferredChurchIDs, service.ChurchID) {
|
||||
return true
|
||||
}
|
||||
if IntContains(person.PreferredWeekdays, Weekday(service.Date)) {
|
||||
return true
|
||||
}
|
||||
title := strings.ToLower(service.Title)
|
||||
for _, preference := range person.PreferredServiceTitles {
|
||||
if preference != "" && strings.Contains(title, strings.ToLower(preference)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"time"
|
||||
)
|
||||
|
||||
// NewID returns a random RFC-4122 version 4 UUID string.
|
||||
func NewID() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return time.Now().Format("20060102150405.000000000")
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
buf := make([]byte, 36)
|
||||
hex.Encode(buf[0:8], b[0:4])
|
||||
buf[8] = '-'
|
||||
hex.Encode(buf[9:13], b[4:6])
|
||||
buf[13] = '-'
|
||||
hex.Encode(buf[14:18], b[6:8])
|
||||
buf[18] = '-'
|
||||
hex.Encode(buf[19:23], b[8:10])
|
||||
buf[23] = '-'
|
||||
hex.Encode(buf[24:36], b[10:16])
|
||||
return string(buf)
|
||||
}
|
||||
|
||||
func newID() string { return NewID() }
|
||||
|
||||
func now() time.Time { return Normalize(time.Now()) }
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
module lektorenplan
|
||||
|
||||
go 1.27.3
|
||||
|
||||
require (
|
||||
github.com/go-pdf/fpdf v0.9.0
|
||||
golang.org/x/crypto v0.59.0
|
||||
modernc.org/sqlite v1.62.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/dustin/go-humanize v1.1.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||
github.com/ncruces/go-strftime v1.1.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/sys v0.50.0 // indirect
|
||||
modernc.org/libc v1.80.1 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.12.1 // indirect
|
||||
)
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
|
||||
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
|
||||
github.com/go-pdf/fpdf v0.9.0 h1:PPvSaUuo1iMi9KkaAn90NuKi+P4gwMedWPHhj8YlJQw=
|
||||
github.com/go-pdf/fpdf v0.9.0/go.mod h1:oO8N111TkmKb9D7VvWGLvLJlaZUQVPM+6V42pp3iV4Y=
|
||||
github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs=
|
||||
github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
|
||||
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
|
||||
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
|
||||
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
|
||||
modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b h1:WE5SLOURcNd8s6uPR/n4WV4weQxxYKi5OpEZkfNVvdE=
|
||||
modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||
modernc.org/ccgo/v4 v4.38.1 h1:wdxJVBuFT8JufZnnQyS6Bbz3NOWhViD0xJOGR96Bpd4=
|
||||
modernc.org/ccgo/v4 v4.38.1/go.mod h1:kOpEkJRbFwBvjUWwn4j1j9B7iFHbl1+orhgTMCDkDBk=
|
||||
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
|
||||
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/gc/v3 v3.2.0 h1:/Y3LGDMQaoYf55PebP1qsZ5FDGgAZyG1RYKEHeQzh1o=
|
||||
modernc.org/gc/v3 v3.2.0/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.80.1 h1:ejn7HtTV3GknNKbklqWQ1nvUrfX8mTxs1D+xp/JQwy4=
|
||||
modernc.org/libc v1.80.1/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
|
||||
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
|
||||
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g=
|
||||
modernc.org/sqlite v1.62.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
@@ -0,0 +1,279 @@
|
||||
package liturgy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
// APIError describes a failed online calendar request.
|
||||
type APIError struct {
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *APIError) Error() string { return e.Message }
|
||||
|
||||
func apiErrorf(format string, args ...any) error {
|
||||
return &APIError{Message: fmt.Sprintf(format, args...)}
|
||||
}
|
||||
|
||||
// API talks to the eucharistiefeier.de calendar endpoint.
|
||||
type API struct {
|
||||
Diocese string
|
||||
Endpoint string
|
||||
Client *http.Client
|
||||
UserAgent string
|
||||
}
|
||||
|
||||
// NewAPI returns the default live client used by LektorenPlan.
|
||||
func NewAPI() *API {
|
||||
return &API{
|
||||
Diocese: "koeln",
|
||||
Endpoint: "https://www.eucharistiefeier.de/lk/api.php",
|
||||
Client: &http.Client{Timeout: 45 * time.Second},
|
||||
UserAgent: "LektorenPlan/1.0 (Linux; Pfarrei)",
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch downloads and parses one calendar year, filling gaps locally.
|
||||
func (a *API) Fetch(ctx context.Context, year int) ([]domain.LiturgicalDay, error) {
|
||||
endpoint, err := url.Parse(a.Endpoint)
|
||||
if err != nil {
|
||||
return nil, apiErrorf("Die Kalender-URL konnte nicht erstellt werden.")
|
||||
}
|
||||
query := endpoint.Query()
|
||||
query.Set("kal", a.Diocese)
|
||||
query.Set("jahr", strconv.Itoa(year))
|
||||
query.Set("format", "json")
|
||||
query.Set("info", "wdtrflu")
|
||||
query.Set("dup", "e")
|
||||
query.Set("bahn", "j")
|
||||
endpoint.RawQuery = query.Encode()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
|
||||
if err != nil {
|
||||
return nil, apiErrorf("Die Kalenderanfrage konnte nicht erstellt werden (%v).", err)
|
||||
}
|
||||
userAgent := a.UserAgent
|
||||
if userAgent == "" {
|
||||
userAgent = "LektorenPlan/1.0 (Linux; Pfarrei)"
|
||||
}
|
||||
req.Header.Set("User-Agent", userAgent)
|
||||
req.Header.Set("Accept", "application/json, text/plain, */*")
|
||||
|
||||
client := a.Client
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 45 * time.Second}
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, apiErrorf("Der liturgische Kalender war nicht erreichbar (%v).", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
return nil, apiErrorf("Der liturgische Kalender antwortete mit HTTP %d.", resp.StatusCode)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
|
||||
if err != nil {
|
||||
return nil, apiErrorf("Die Kalenderdaten konnten nicht gelesen werden (%v).", err)
|
||||
}
|
||||
return Parse(data, year)
|
||||
}
|
||||
|
||||
var leadingNumber = regexp.MustCompile(`^\d{1,2}\.\s`)
|
||||
|
||||
// Parse converts the JSON payload of the online calendar into days.
|
||||
func Parse(data []byte, year int) ([]domain.LiturgicalDay, error) {
|
||||
var root map[string]any
|
||||
if err := json.Unmarshal(data, &root); err != nil {
|
||||
return nil, apiErrorf("Die Kalenderdaten konnten nicht gelesen werden (%v).", err)
|
||||
}
|
||||
rawCelebrations, ok := root["Zelebrationen"]
|
||||
if !ok {
|
||||
return nil, apiErrorf("Die Kalenderdaten konnten nicht gelesen werden (Zelebrationen fehlen).")
|
||||
}
|
||||
|
||||
entries := decodeEntries(rawCelebrations)
|
||||
grouped := map[string][]map[string]any{}
|
||||
for _, entry := range entries {
|
||||
date, _ := entry["Datum"].(string)
|
||||
grouped[date] = append(grouped[date], entry)
|
||||
}
|
||||
|
||||
keys := make([]string, 0, len(grouped))
|
||||
for key := range grouped {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
prefix := strconv.Itoa(year)
|
||||
var days []domain.LiturgicalDay
|
||||
for _, dateKey := range keys {
|
||||
if !strings.HasPrefix(dateKey, prefix) {
|
||||
continue
|
||||
}
|
||||
date, ok := domain.DateFromKey(dateKey)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
var valid []map[string]any
|
||||
for _, entry := range grouped[dateKey] {
|
||||
title := stringField(entry, "Tl")
|
||||
remark := stringField(entry, "Bem")
|
||||
if strings.Contains(title, "Bahnlesungen") {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(title, "Kommemoration") {
|
||||
continue
|
||||
}
|
||||
if title == "Weihe der eigenen Kirche" && strings.HasPrefix(remark, "Wenn") {
|
||||
continue
|
||||
}
|
||||
valid = append(valid, entry)
|
||||
}
|
||||
if len(valid) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
best := valid[0]
|
||||
bestScore := scoreEntry(best, date)
|
||||
for _, entry := range valid[1:] {
|
||||
if s := scoreEntry(entry, date); s > bestScore {
|
||||
best, bestScore = entry, s
|
||||
}
|
||||
}
|
||||
|
||||
readingEntry := best
|
||||
if stringField(best, "L1") == "" && stringField(best, "EV") == "" {
|
||||
bestLen := readingLength(readingEntry)
|
||||
for _, entry := range valid {
|
||||
if l := readingLength(entry); l > bestLen {
|
||||
readingEntry, bestLen = entry, l
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
title := stringField(best, "Tl")
|
||||
colorValue := stringField(best, "Farbe")
|
||||
if colorValue == "" {
|
||||
colorValue = stringField(readingEntry, "Farbe")
|
||||
}
|
||||
days = append(days, domain.LiturgicalDay{
|
||||
Date: date,
|
||||
Title: title,
|
||||
Rank: domain.LiturgicalRank(stringField(best, "Rang")),
|
||||
Color: domain.LiturgicalColorFromAPI(colorValue),
|
||||
Remark: stringField(best, "Bem"),
|
||||
Readings: domain.Readings{
|
||||
First: stringField(readingEntry, "L1"),
|
||||
Psalm: stringField(readingEntry, "AP"),
|
||||
Second: stringField(readingEntry, "L2"),
|
||||
Gospel: stringField(readingEntry, "EV"),
|
||||
},
|
||||
IsObligation: IsObligation(date, title),
|
||||
Source: SourceLabel,
|
||||
UpdatedAt: domain.Normalize(time.Now()),
|
||||
})
|
||||
}
|
||||
|
||||
if len(days) == 0 {
|
||||
return nil, apiErrorf("Für %d wurden keine liturgischen Daten geliefert.", year)
|
||||
}
|
||||
return FillLocalGaps(year, days), nil
|
||||
}
|
||||
|
||||
func decodeEntries(raw any) []map[string]any {
|
||||
var entries []map[string]any
|
||||
switch value := raw.(type) {
|
||||
case []any:
|
||||
for _, item := range value {
|
||||
if entry, ok := item.(map[string]any); ok {
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
}
|
||||
case map[string]any:
|
||||
for _, item := range value {
|
||||
if entry, ok := item.(map[string]any); ok {
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
func stringField(entry map[string]any, key string) string {
|
||||
if value, ok := entry[key].(string); ok {
|
||||
return value
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func readingLength(entry map[string]any) int {
|
||||
total := 0
|
||||
for _, key := range []string{"L1", "AP", "L2", "EV"} {
|
||||
total += utf8.RuneCountInString(stringField(entry, key))
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
func scoreEntry(entry map[string]any, date time.Time) int {
|
||||
value := 0
|
||||
switch stringField(entry, "Rang") {
|
||||
case "H":
|
||||
value += 120
|
||||
case "F":
|
||||
value += 110
|
||||
case "G":
|
||||
value += 80
|
||||
case "g":
|
||||
value += 60
|
||||
default:
|
||||
value += 50
|
||||
}
|
||||
title := stringField(entry, "Tl")
|
||||
remark := stringField(entry, "Bem")
|
||||
lowerTitle := strings.ToLower(title)
|
||||
|
||||
if domain.IsSunday(date) {
|
||||
if strings.Contains(lowerTitle, "sonntag") || strings.Contains(lowerTitle, "taufe des herrn") {
|
||||
value += 100
|
||||
}
|
||||
if stringField(entry, "Rang") == "" {
|
||||
value += 30
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case strings.Contains(remark, "Am Tag"):
|
||||
value += 18
|
||||
case strings.Contains(remark, "Am Morgen"):
|
||||
value += 12
|
||||
case strings.Contains(remark, "Am Vorabend"):
|
||||
value -= 4
|
||||
case strings.Contains(remark, "In der Heiligen Nacht"):
|
||||
value += 5
|
||||
}
|
||||
if strings.Contains(remark, "Hochfest") {
|
||||
value += 10
|
||||
}
|
||||
if leadingNumber.MatchString(title) {
|
||||
value -= 25
|
||||
}
|
||||
if stringField(entry, "L1") != "" || stringField(entry, "EV") != "" {
|
||||
value += 20
|
||||
}
|
||||
if strings.Contains(lowerTitle, "im jahreskreis") || strings.Contains(lowerTitle, "osterzeit") {
|
||||
value += 5
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":1,"source":"www.eucharistiefeier.de","diocese":"Erzbistum Köln","years":[2025,2026,2027,2028],"days":[{"date":"2025-01-01","title":"1. Januar - Neujahr","rank":"H","color":"w","bem":"Hochfest der Gottesmutter Maria","l1":"Num 6, 22-27","ap":"Ps 67 (66), 2-3.5.6 u. 8 (R: 2a)","l2":"Gal 4, 4-7","ev":"Lk 2, 16-21","obligation":true},{"date":"2025-01-02","title":"Hl. Basilius der Große (379) und hl. Gregor von Nazianz (um 390), Bischöfe, Kirchenlehrer","rank":"G","color":"w","bem":"","l1":"Eph 4, 1-7.11-13","ap":"Ps 23 (22), 1-3.4.5.6 (R: 1)","l2":"","ev":"Mt 23, 8-12","obligation":false},{"date":"2025-01-03","title":"Heiligster Name Jesu","rank":"g","color":"w","bem":"","l1":"Phil 2, 1-11","ap":"Ps 8, 4-5.6-7.8-9 (R: 2a)","l2":"","ev":"Lk 2, 21-24","obligation":false},{"date":"2025-01-04","title":"4. Januar","rank":"","color":"w","bem":"","l1":"1 Joh 3, 7-10","ap":"Ps 98 (97), 1.7-8.9 (R: vgl. 3cd)","l2":"","ev":"Joh 1, 35-42","obligation":false},{"date":"2025-01-05","title":"2. Sonntag nach Weihnachten","rank":"","color":"w","bem":"","l1":"Sir 24, 1-2.8-12 (1-4.12-16)","ap":"Ps 147, 12-13.14-15.19-20 (R: Joh 1, 14)","l2":"Eph 1, 3-6.15-18","ev":"Joh 1, 1-18","obligation":true},{"date":"2025-01-06","title":"Erscheinung des Herrn","rank":"H","color":"w","bem":"","l1":"Jes 60, 1-6","ap":"Ps 72 (71), 1-2.7-8.10-11.12-13 (R: 11)","l2":"Eph 3, 2-3a.5-6","ev":"Mt 2, 1-12","obligation":true},{"date":"2025-01-07","title":"Hl. Raimund von Peñafort, Ordensgründer (1275)","rank":"g","color":"w","bem":"","l1":"2 Kor 5, 14-20","ap":"Ps 103 (102), 1-2.3-4.8-9.13-14.17-18a (R: 11)","l2":"","ev":"Lk 12, 35-40","obligation":false},{"date":"2025-01-08","title":"Hl. Severin, Mönch in Norikum (482)","rank":"g","color":"w","bem":"","l1":"Jak 2, 14-17","ap":"Ps 107 (106), 1-2a u. 3.4-5.6-7.8-9 (R: vgl. Spr 31, 20)","l2":"","ev":"Mt 25, 31-46","obligation":false},{"date":"2025-01-09","title":"9. Januar","rank":"","color":"w","bem":"","l1":"1 Joh 4, 11-18","ap":"Ps 72 (71), 1-2.10-11.12-13 (R: 11)","l2":"","ev":"Mk 6, 45-52","obligation":false},{"date":"2025-01-10","title":"10. Januar","rank":"","color":"w","bem":"","l1":"1 Joh 4, 19 - 5, 4","ap":"Ps 72 (71), 1-2.14 u. 15bc.17 (R: 11)","l2":"","ev":"Lk 4, 14-22a","obligation":false},{"date":"2025-01-11","title":"11. Januar","rank":"","color":"w","bem":"","l1":"1 Joh 5, 5-13","ap":"Ps 147, 12-13.14-15.19-20 (R: 12a)","l2":"","ev":"Lk 5, 12-16","obligation":false},{"date":"2025-01-12","title":"Taufe des Herrn","rank":"F","color":"w","bem":"Sonntag nach dem 6. Januar","l1":"Jes 42, 5a.1-4.6-7 oder Jes 40, 1-5.9-11","ap":"Ps 29 (28), 1-2.3ac-4.3b u. 9b-10 (R: vgl. 11b) oder Ps 104 (103), 1-2.3-4.24-25.27-28.29-30 (R: 1ab)","l2":"Apg 10, 34-38 oder Tit 2, 11-14; 3, 4-7","ev":"Lk 3, 15-16.21-22","obligation":true},{"date":"2025-01-13","title":"Hl. Hilarius, Bischof von Poitiers, Kirchenlehrer (um 367)","rank":"g","color":"w","bem":"","l1":"1 Joh 2, 18-25","ap":"Ps 110 (109), 1-2.3.4-5 (R: 4b)","l2":"","ev":"Mt 5, 13-19","obligation":false},{"date":"2025-01-14","title":"Dienstag der 1. Woche im Jahreskreis","rank":"","color":"g","bem":"","l1":"Hebr 2, 5-12","ap":"Ps 8, 2 u. 5.6-7.8-9 (R: vgl. 7)","l2":"","ev":"Mk 1, 21-28","obligation":false},{"date":"2025-01-15","title":"Mittwoch der 1. Woche im Jahreskreis","rank":"","color":"g","bem":"","l1":"Hebr 2, 11-12.13c-18","ap":"Ps 105 (104), 1-2.3-4.6-7.8-9 (R: 7a.8a)","l2":"","ev":"Mk 1, 29-39","obligation":false},{"date":"2025-01-16","title":"Donnerstag der 1. Woche im Jahreskreis","rank":"","color":"g","bem":"","l1":"Hebr 3, 7-14","ap":"Ps 95 (94), 6-7b.7c-9.10-11 (R: vgl. 7c.8a)","l2":"","ev":"Mk 1, 40-45","obligation":false},{"date":"2025-01-17","title":"Hl. Antonius, Mönchsvater in Ägypten (356)","rank":"G","color":"w","bem":"","l1":"Eph 6, 10-13.18","ap":"Ps 16 (15), 1-2 u. 5.7-8.9 u. 11 (R: vgl. 5a)","l2":"","ev":"Mt 19, 16-26","obligation":false},{"date":"2025-01-18","title":"Samstag der 1. Woche im Jahreskreis","rank":"","color":"g","bem":"","l1":"Hebr 4, 12-16","ap":"Ps 19 (18B), 8.9.10.11 u. 15 (R: vgl. Joh 6, 63b)","l2":"","ev":"Mk 2, 13-17","obligation":false},{"date":"2025-01-19","title":"2. Sonntag im Jahreskreis","rank":"","color":"g","bem":"","l1":"Jes 62, 1-5","ap":"Ps 96 (95), 1-2.3-4.6-7.10 (R: vgl. 3a)","l2":"1 Kor 12, 4-11","ev":"Joh 2, 1-11","obligation":true},{"date":"2025-01-20","title":"Hl. Fabian, Papst, Märtyrer (250)","rank":"g","color":"r","bem":"","l1":"1 Petr 5, 1-4","ap":"Ps 40 (39), 2 u. 4ab.7-8.9-10 (R: vgl. 8a.9a)","l2":"","ev":"Joh 21, 1.15-17","obligation":false},{"date":"2025-01-21","title":"Hl. Agnes, Jungfrau, Märtyrin in Rom (304)","rank":"g","color":"r","bem":"","l1":"1 Kor 1, 26-31","ap":"Ps 23 (22), 1-3.4.5.6 (R: 1)","l2":"","ev":"Mt 13, 44-46","obligation":false},{"date":"2025-01-22","title":"Hl. Vinzenz, Diakon, Märtyrer in Spanien (304)","rank":"g","color":"r","bem":"","l1":"2 Kor 4, 7-15","ap":"Ps 34 (33), 2-3.4-5.6-7.8-9 (R: vgl. 5b)","l2":"","ev":"Mt 10, 17-22","obligatioLine truncated
|
||||
@@ -0,0 +1,287 @@
|
||||
// Package liturgy implements the local liturgical calendar and the optional
|
||||
// online source www.eucharistiefeier.de used by LektorenPlan.
|
||||
package liturgy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
// Moveable feasts -----------------------------------------------------------
|
||||
|
||||
func EasterSunday(year int) time.Time { return domain.EasterSunday(year) }
|
||||
func AshWednesday(y int) time.Time { return domain.AshWednesday(y) }
|
||||
func PalmSunday(y int) time.Time { return domain.PalmSunday(y) }
|
||||
func HolyThursday(y int) time.Time { return domain.HolyThursday(y) }
|
||||
func GoodFriday(y int) time.Time { return domain.GoodFriday(y) }
|
||||
func HolySaturday(y int) time.Time { return domain.HolySaturday(y) }
|
||||
func Ascension(y int) time.Time { return domain.Ascension(y) }
|
||||
func Pentecost(y int) time.Time { return domain.Pentecost(y) }
|
||||
func CorpusChristi(y int) time.Time { return domain.CorpusChristi(y) }
|
||||
func SacredHeart(y int) time.Time { return domain.SacredHeart(y) }
|
||||
func TrinitySunday(y int) time.Time { return domain.TrinitySunday(y) }
|
||||
func AdventStart(year int) time.Time { return domain.AdventStart(year) }
|
||||
func ChristKing(year int) time.Time { return domain.ChristKing(year) }
|
||||
func BaptismOfTheLord(year int) time.Time { return domain.BaptismOfTheLord(year) }
|
||||
|
||||
// Seasons -------------------------------------------------------------------
|
||||
|
||||
func SeasonFor(date time.Time) domain.LiturgicalSeason { return domain.SeasonFor(date) }
|
||||
func SeasonName(date time.Time) string { return SeasonFor(date).Title() }
|
||||
|
||||
// Obligation ----------------------------------------------------------------
|
||||
|
||||
func IsObligation(date time.Time, title string) bool {
|
||||
if domain.IsSunday(date) {
|
||||
return true
|
||||
}
|
||||
m, d := domain.Month(date), domain.DayNumber(date)
|
||||
switch {
|
||||
case m == 1 && d == 1, m == 1 && d == 6, m == 8 && d == 15, m == 11 && d == 1, m == 12 && d == 25:
|
||||
return true
|
||||
}
|
||||
lower := strings.ToLower(title)
|
||||
if strings.Contains(lower, "fronleichnam") ||
|
||||
strings.Contains(lower, "christi himmelfahrt") ||
|
||||
(strings.Contains(lower, "pfingsten") && !strings.Contains(lower, "vorabend")) ||
|
||||
strings.Contains(lower, "ostersonntag") || strings.Contains(lower, "osternacht") {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Symbols -------------------------------------------------------------------
|
||||
|
||||
func SymbolFor(title string, rank domain.LiturgicalRank, date time.Time) domain.FeastSymbol {
|
||||
return domain.SymbolFor(title, rank, date)
|
||||
}
|
||||
|
||||
// Local fallback ------------------------------------------------------------
|
||||
|
||||
var fixedReadings = map[string]domain.Readings{
|
||||
"01-01": {First: "Num 6, 22-27", Psalm: "Ps 67 (66), 2-3.5.6 u. 8 (R: 2a)", Second: "Gal 4, 4-7", Gospel: "Lk 2, 16-21"},
|
||||
"01-06": {First: "Jes 60, 1-6", Psalm: "Ps 72 (71), 1-2.7-8.10-11.12-13 (R: 11)", Second: "Eph 3, 2-3a.5-6", Gospel: "Mt 2, 1-12"},
|
||||
"02-02": {First: "Mal 3, 1-4", Psalm: "Ps 24 (23), 7-8.9-10 (R: 8a)", Second: "Hebr 2, 14-18", Gospel: "Lk 2, 22-40"},
|
||||
"03-19": {First: "2 Sam 7, 4-5a.12-14a.16", Psalm: "Ps 89 (88), 2-3.4-5.27.29 (R: 37)", Second: "Röm 4, 13.16-18.22", Gospel: "Mt 1, 16.18-21.24a"},
|
||||
"03-25": {First: "Jes 7, 10-14", Psalm: "Ps 40 (39), 5-6.7-8a.8b-10 (R: 8a.9a)", Second: "Hebr 10, 4-10", Gospel: "Lk 1, 26-38"},
|
||||
"06-24": {First: "Jes 49, 1-6", Psalm: "Ps 139 (138), 1-3.13-14ab.14c-15 (R: 14a)", Second: "Apg 13, 22-26", Gospel: "Lk 1, 57-66.80"},
|
||||
"06-29": {First: "Apg 12, 1-11", Psalm: "Ps 34 (33), 2-3.4-5.6-7.8-9 (R: 5b)", Second: "2 Tim 4, 6-8.17-18", Gospel: "Mt 16, 13-19"},
|
||||
"08-15": {First: "Offb 11, 19a; 12, 1-6a.10ab", Psalm: "Ps 45 (44), 11-12.16-17 (R: 10b)", Second: "1 Kor 15, 20-27", Gospel: "Lk 1, 39-56"},
|
||||
"09-14": {First: "Num 21, 4b-9", Psalm: "Ps 78 (77), 1-2.34-35.36-37.38 (R: 7b)", Second: "Phil 2, 6-11", Gospel: "Joh 3, 13-17"},
|
||||
"11-01": {First: "Offb 7, 2-4.9-14", Psalm: "Ps 24 (23), 1-2.3-4.5-6 (R: vgl. 6)", Second: "1 Joh 3, 1-3", Gospel: "Mt 5, 1-12a"},
|
||||
"11-02": {First: "Jes 25, 6a.7-9", Psalm: "Ps 23 (22), 1-3a.3b-4.5.6 (R: 1)", Second: "Röm 8, 14-23", Gospel: "Mt 25, 31-46"},
|
||||
"12-08": {First: "Gen 3, 9-15.20", Psalm: "Ps 98 (97), 1.2-3ab.3cd-4 (R: 1a)", Second: "Eph 1, 3-6.11-12", Gospel: "Lk 1, 26-38"},
|
||||
"12-24": {First: "2 Sam 7, 1-5.8b-12.14a.16", Psalm: "Ps 89 (88), 2-3.20a u. 4-5.27 u. 29 (R: 2a)", Gospel: "Lk 1, 67-79"},
|
||||
"12-25": {First: "Jes 52, 7-10", Psalm: "Ps 98 (97), 1.2-3b.3c-4.5-6 (R: vgl. 3cd)", Second: "Hebr 1, 1-6", Gospel: "Joh 1, 1-18"},
|
||||
"12-26": {First: "Apg 6, 8-10; 7, 54-59", Psalm: "Ps 31 (30), 3-4.6.8.17 (R: 6a)", Gospel: "Mt 10, 17-22"},
|
||||
}
|
||||
|
||||
var easterReadings = map[int]domain.Readings{
|
||||
-46: {First: "Joel 2, 12-18", Psalm: "Ps 51 (50), 3-4.5-6a.12-13.14 u. 17 (R: vgl. 3a)", Second: "2 Kor 5, 20 - 6, 2", Gospel: "Mt 6, 1-6.16-18"},
|
||||
-7: {First: "Jes 50, 4-7", Psalm: "Ps 22 (21), 8-9.17-18a.19-20.23-24 (R: 2a)", Second: "Phil 2, 6-11", Gospel: "Mt 21, 1-11"},
|
||||
-3: {First: "Ex 12, 1-8.11-14", Psalm: "Ps 116 (115), 12-13.15-16bc.17-18 (R: vgl. 1 Kor 10, 16)", Second: "1 Kor 11, 23-26", Gospel: "Joh 13, 1-15"},
|
||||
-2: {First: "Jes 52, 13 - 53, 12", Psalm: "Ps 31 (30), 2 u. 6.12-13.15-16.17 u. 25 (R: Lk 23, 46)", Second: "Hebr 4, 14-16; 5, 7-9", Gospel: "Joh 18, 1 - 19, 42"},
|
||||
0: {First: "Apg 10, 34a.37-43", Psalm: "Ps 118 (117), 1-2.16-17.22-23 (R: vgl. 24)", Second: "Kol 3, 1-4 oder 1 Kor 5, 6b-8", Gospel: "Joh 20, 1-9"},
|
||||
39: {First: "Apg 1, 1-11", Psalm: "Ps 47 (46), 2-3.6-7.8-9 (R: 6)", Second: "Eph 1, 17-23", Gospel: "Mk 16, 15-20"},
|
||||
49: {First: "Apg 2, 1-11", Psalm: "Ps 104 (103), 1-2.24-25.29-30.31 u. 34 (R: vgl. 30)", Second: "1 Kor 12, 3b-7.12-13", Gospel: "Joh 20, 19-23"},
|
||||
56: {First: "Spr 8, 22-31", Psalm: "Ps 8, 4-5.6-7.8-9 (R: 2a)", Second: "Röm 5, 1-5", Gospel: "Joh 16, 12-15"},
|
||||
60: {First: "Dtn 8, 2-3.14-16a", Psalm: "Ps 147, 12-13.14-15.19-20 (R: 12a)", Second: "1 Kor 10, 16-17", Gospel: "Joh 6, 51-58"},
|
||||
68: {First: "Hos 11, 1.3-4.8c-9", Psalm: "Jes 12, 2-3.4bcd.5-6 (R: 3)", Second: "Eph 3, 8-12.14-19", Gospel: "Joh 19, 31-37"},
|
||||
}
|
||||
|
||||
// LocalDay builds the offline fallback for one date.
|
||||
func LocalDay(date time.Time) domain.LiturgicalDay {
|
||||
day := domain.Normalize(date)
|
||||
y := domain.Year(day)
|
||||
m := domain.Month(day)
|
||||
d := domain.DayNumber(day)
|
||||
key := fmt.Sprintf("%02d-%02d", m, d)
|
||||
weekday := domain.Weekday(day)
|
||||
easter := EasterSunday(y)
|
||||
offset := domain.DaysBetween(easter, day)
|
||||
|
||||
title := ""
|
||||
rank := domain.RankWeekday
|
||||
color := domain.ColorGreen
|
||||
readings := domain.Readings{}
|
||||
remark := ""
|
||||
|
||||
switch offset {
|
||||
case -46:
|
||||
title, rank, color, readings = "Aschermittwoch", domain.RankWeekday, domain.ColorViolet, easterReadings[-46]
|
||||
case -7:
|
||||
title, rank, color, readings = "Palmsonntag", domain.RankFeast, domain.ColorRed, easterReadings[-7]
|
||||
case -3:
|
||||
title, rank, color, readings = "Gründonnerstag", domain.RankSolemnity, domain.ColorWhite, easterReadings[-3]
|
||||
case -2:
|
||||
title, rank, color, readings = "Karfreitag", domain.RankSolemnity, domain.ColorRed, easterReadings[-2]
|
||||
case -1:
|
||||
title, rank, color = "Karsamstag", domain.RankWeekday, domain.ColorViolet
|
||||
case 0:
|
||||
title, rank, color, readings = "Ostersonntag", domain.RankSolemnity, domain.ColorWhite, easterReadings[0]
|
||||
remark = "Hochfest der Auferstehung des Herrn"
|
||||
case 1:
|
||||
title, rank, color = "Ostermontag", domain.RankSolemnity, domain.ColorWhite
|
||||
readings = domain.Readings{First: "Apg 2, 14.22-33", Psalm: "Ps 16 (15), 1-2a u. 5.7-8.9-10.11 (R: 11a)", Gospel: "Mt 28, 8-15"}
|
||||
case 39:
|
||||
title, rank, color, readings = "Christi Himmelfahrt", domain.RankSolemnity, domain.ColorWhite, easterReadings[39]
|
||||
case 49:
|
||||
title, rank, color, readings = "Pfingsten", domain.RankSolemnity, domain.ColorRed, easterReadings[49]
|
||||
remark = "Hochfest des Heiligen Geistes"
|
||||
case 50:
|
||||
title, rank, color = "Pfingstmontag", domain.RankSolemnity, domain.ColorRed
|
||||
readings = domain.Readings{First: "Apg 10, 34a.37-43", Psalm: "Ps 118 (117), 1-2.16-17.22-23 (R: vgl. 24)", Second: "Kol 3, 1-4", Gospel: "Joh 20, 1-9"}
|
||||
case 56:
|
||||
title, rank, color, readings = "Dreifaltigkeitssonntag", domain.RankSolemnity, domain.ColorWhite, easterReadings[56]
|
||||
case 60:
|
||||
title, rank, color, readings = "Fronleichnam", domain.RankSolemnity, domain.ColorWhite, easterReadings[60]
|
||||
remark = "Hochfest des Leibes und Blutes Christi"
|
||||
case 68:
|
||||
title, rank, color, readings = "Heiligstes Herz Jesu", domain.RankSolemnity, domain.ColorWhite, easterReadings[68]
|
||||
}
|
||||
|
||||
if title == "" {
|
||||
switch key {
|
||||
case "01-01":
|
||||
title, rank, color = "Neujahr – Hochfest der Gottesmutter Maria", domain.RankSolemnity, domain.ColorWhite
|
||||
case "01-06":
|
||||
title, rank, color = "Erscheinung des Herrn", domain.RankSolemnity, domain.ColorWhite
|
||||
case "02-02":
|
||||
title, rank, color = "Darstellung des Herrn", domain.RankFeast, domain.ColorWhite
|
||||
case "03-19":
|
||||
title, rank, color = "Hl. Josef, Bräutigam der Gottesmutter", domain.RankSolemnity, domain.ColorWhite
|
||||
case "03-25":
|
||||
title, rank, color = "Verkündigung des Herrn", domain.RankSolemnity, domain.ColorWhite
|
||||
case "06-24":
|
||||
title, rank, color = "Geburt Johannes' des Täufers", domain.RankSolemnity, domain.ColorWhite
|
||||
case "06-29":
|
||||
title, rank, color = "Petrus und Paulus", domain.RankSolemnity, domain.ColorRed
|
||||
case "08-15":
|
||||
title, rank, color = "Mariä Aufnahme in den Himmel", domain.RankSolemnity, domain.ColorWhite
|
||||
case "09-14":
|
||||
title, rank, color = "Kreuzerhöhung", domain.RankFeast, domain.ColorRed
|
||||
case "11-01":
|
||||
title, rank, color = "Allerheiligen", domain.RankSolemnity, domain.ColorWhite
|
||||
case "11-02":
|
||||
title, rank, color = "Allerseelen", domain.RankWeekday, domain.ColorViolet
|
||||
case "12-08":
|
||||
title, rank, color = "Mariä Empfängnis", domain.RankSolemnity, domain.ColorWhite
|
||||
case "12-24":
|
||||
title, rank, color = "Heiliger Abend", domain.RankWeekday, domain.ColorWhite
|
||||
case "12-25":
|
||||
title, rank, color = "Weihnachten – Hochfest der Geburt des Herrn", domain.RankSolemnity, domain.ColorWhite
|
||||
case "12-26":
|
||||
title, rank, color = "Hl. Stephanus", domain.RankFeast, domain.ColorRed
|
||||
}
|
||||
if r, ok := fixedReadings[key]; ok {
|
||||
readings = r
|
||||
}
|
||||
}
|
||||
|
||||
if title == "" {
|
||||
if weekday == 1 {
|
||||
title = sundayTitle(day)
|
||||
color = domain.ColorGreen
|
||||
if seasonal := seasonalSundayRank(day); seasonal != domain.RankWeekday {
|
||||
rank = seasonal
|
||||
}
|
||||
} else {
|
||||
title = weekdayTitle(day)
|
||||
season := SeasonFor(day)
|
||||
if season == domain.SeasonAdvent || season == domain.SeasonLent {
|
||||
color = domain.ColorViolet
|
||||
} else if season == domain.SeasonChristmas || season == domain.SeasonEaster {
|
||||
color = domain.ColorWhite
|
||||
} else {
|
||||
color = domain.ColorGreen
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if rank == domain.RankSolemnity {
|
||||
color = domain.ColorWhite
|
||||
}
|
||||
if rank == domain.RankFeast && color == domain.ColorGreen {
|
||||
color = domain.ColorRed
|
||||
}
|
||||
|
||||
return domain.LiturgicalDay{
|
||||
Date: day, Title: title, Rank: rank, Color: color, Remark: remark,
|
||||
Readings: readings, IsObligation: IsObligation(day, title),
|
||||
Source: "lokale Berechnung", UpdatedAt: domain.Normalize(time.Now()),
|
||||
}
|
||||
}
|
||||
|
||||
func LocalDays(r domain.DayRange) []domain.LiturgicalDay {
|
||||
days := r.Days()
|
||||
out := make([]domain.LiturgicalDay, 0, len(days))
|
||||
for _, day := range days {
|
||||
out = append(out, LocalDay(day))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func seasonalSundayRank(day time.Time) domain.LiturgicalRank {
|
||||
season := SeasonFor(day)
|
||||
if season == domain.SeasonAdvent || season == domain.SeasonChristmas || season == domain.SeasonLent || season == domain.SeasonEaster {
|
||||
if season == domain.SeasonLent && domain.DaysBetween(PalmSunday(domain.Year(day)), day) == 0 {
|
||||
return domain.RankFeast
|
||||
}
|
||||
return domain.RankWeekday
|
||||
}
|
||||
return domain.RankWeekday
|
||||
}
|
||||
|
||||
func sundayTitle(day time.Time) string {
|
||||
y := domain.Year(day)
|
||||
switch SeasonFor(day) {
|
||||
case domain.SeasonAdvent:
|
||||
index := domain.DaysBetween(AdventStart(y), day)/7 + 1
|
||||
names := []string{"1. Adventssonntag", "2. Adventssonntag", "3. Adventssonntag", "4. Adventssonntag"}
|
||||
if index >= 1 && index <= len(names) {
|
||||
return names[index-1]
|
||||
}
|
||||
return "Adventssonntag"
|
||||
case domain.SeasonChristmas:
|
||||
if domain.DaysBetween(BaptismOfTheLord(y), day) == 0 {
|
||||
return "Taufe des Herrn"
|
||||
}
|
||||
return "Sonntag in der Weihnachtszeit"
|
||||
case domain.SeasonLent:
|
||||
index := domain.DaysBetween(AshWednesday(y), day)/7 + 1
|
||||
if index >= 6 {
|
||||
return "Palmsonntag"
|
||||
}
|
||||
return fmt.Sprintf("%d. Fastensonntag", index)
|
||||
case domain.SeasonEaster:
|
||||
index := domain.DaysBetween(EasterSunday(y), day)/7 + 1
|
||||
if index == 1 {
|
||||
return "Ostersonntag"
|
||||
}
|
||||
if index == 8 {
|
||||
return "Pfingsten"
|
||||
}
|
||||
return fmt.Sprintf("%d. Sonntag der Osterzeit", index)
|
||||
default:
|
||||
return "Sonntag im Jahreskreis"
|
||||
}
|
||||
}
|
||||
|
||||
func weekdayTitle(day time.Time) string {
|
||||
name := domain.WeekdayName(day)
|
||||
switch SeasonFor(day) {
|
||||
case domain.SeasonAdvent:
|
||||
return name + " im Advent"
|
||||
case domain.SeasonChristmas:
|
||||
return name + " in der Weihnachtszeit"
|
||||
case domain.SeasonLent:
|
||||
return name + " in der Fastenzeit"
|
||||
case domain.SeasonEaster:
|
||||
return name + " in der Osterzeit"
|
||||
default:
|
||||
return name + " im Jahreskreis"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package liturgy
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
// SourceLabel is the attribution required by the data source.
|
||||
const SourceLabel = "Daten von www.eucharistiefeier.de"
|
||||
|
||||
//go:embed liturgical-snapshot.json
|
||||
var snapshotJSON []byte
|
||||
|
||||
type snapshotFile struct {
|
||||
Version int `json:"version"`
|
||||
Source string `json:"source"`
|
||||
Diocese string `json:"diocese"`
|
||||
Years []int `json:"years"`
|
||||
Days []snapshotDay `json:"days"`
|
||||
}
|
||||
|
||||
type snapshotDay struct {
|
||||
Date string `json:"date"`
|
||||
Title string `json:"title"`
|
||||
Rank string `json:"rank"`
|
||||
Color string `json:"color"`
|
||||
Remark string `json:"bem"`
|
||||
First string `json:"l1"`
|
||||
Psalm string `json:"ap"`
|
||||
Second string `json:"l2"`
|
||||
Gospel string `json:"ev"`
|
||||
Obligation bool `json:"obligation"`
|
||||
}
|
||||
|
||||
var (
|
||||
cachedSnapshot []domain.LiturgicalDay
|
||||
cachedSnapshotOnce bool
|
||||
)
|
||||
|
||||
func loadSnapshot() (snapshotFile, error) {
|
||||
var file snapshotFile
|
||||
if err := json.Unmarshal(snapshotJSON, &file); err != nil {
|
||||
return file, fmt.Errorf("liturgical snapshot: %w", err)
|
||||
}
|
||||
return file, nil
|
||||
}
|
||||
|
||||
// SnapshotLoaded reports whether the embedded JSON could be decoded.
|
||||
func SnapshotLoaded() bool {
|
||||
_, err := loadSnapshot()
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// SnapshotYears returns the years covered by the embedded snapshot.
|
||||
func SnapshotYears() []int {
|
||||
file, err := loadSnapshot()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return file.Years
|
||||
}
|
||||
|
||||
// SnapshotDays returns the bundled offline calendar.
|
||||
func SnapshotDays() []domain.LiturgicalDay {
|
||||
if cachedSnapshotOnce {
|
||||
return cachedSnapshot
|
||||
}
|
||||
cachedSnapshotOnce = true
|
||||
file, err := loadSnapshot()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
days := make([]domain.LiturgicalDay, 0, len(file.Days))
|
||||
for _, entry := range file.Days {
|
||||
date, ok := domain.DateFromKey(entry.Date)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
days = append(days, domain.LiturgicalDay{
|
||||
Date: date,
|
||||
Title: entry.Title,
|
||||
Rank: domain.LiturgicalRank(entry.Rank),
|
||||
Color: domain.LiturgicalColorFromAPI(entry.Color),
|
||||
Remark: entry.Remark,
|
||||
Readings: domain.Readings{
|
||||
First: entry.First,
|
||||
Psalm: entry.Psalm,
|
||||
Second: entry.Second,
|
||||
Gospel: entry.Gospel,
|
||||
},
|
||||
IsObligation: entry.Obligation,
|
||||
Source: SourceLabel,
|
||||
UpdatedAt: domain.Normalize(time.Now()),
|
||||
})
|
||||
}
|
||||
cachedSnapshot = days
|
||||
return days
|
||||
}
|
||||
|
||||
// SnapshotDaysForYear returns the bundled days of one calendar year.
|
||||
func SnapshotDaysForYear(year int) []domain.LiturgicalDay {
|
||||
var out []domain.LiturgicalDay
|
||||
for _, day := range SnapshotDays() {
|
||||
if domain.Year(day.Date) == year {
|
||||
out = append(out, day)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// SnapshotMissing returns bundled days whose date keys are not yet present.
|
||||
func SnapshotMissing(existing map[string]bool) []domain.LiturgicalDay {
|
||||
var out []domain.LiturgicalDay
|
||||
for _, day := range SnapshotDays() {
|
||||
if !existing[day.DateKey()] {
|
||||
out = append(out, day)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// FillLocalGaps completes a year with the local calendar so a plan never has
|
||||
// empty rows when the online source omits days.
|
||||
func FillLocalGaps(year int, days []domain.LiturgicalDay) []domain.LiturgicalDay {
|
||||
seen := make(map[string]bool, len(days))
|
||||
for _, day := range days {
|
||||
seen[day.DateKey()] = true
|
||||
}
|
||||
for _, day := range domain.YearRange(year).Days() {
|
||||
if !seen[domain.Key(day)] {
|
||||
days = append(days, LocalDay(day))
|
||||
}
|
||||
}
|
||||
sortDays(days)
|
||||
return days
|
||||
}
|
||||
|
||||
func sortDays(days []domain.LiturgicalDay) {
|
||||
sort.Slice(days, func(i, j int) bool { return days[i].Date.Before(days[j].Date) })
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
// Command lektorenplan serves the browser version of LektorenPlan.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
"lektorenplan/store"
|
||||
"lektorenplan/web"
|
||||
)
|
||||
|
||||
// version can be overridden at build time with
|
||||
// -ldflags "-X main.version=1.2.3".
|
||||
var version = "1.0.0"
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
log.Fatalf("lektorenplan: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
var (
|
||||
addr string
|
||||
dbPath string
|
||||
seedDemo bool
|
||||
adminUser string
|
||||
adminPassword string
|
||||
secureCookies bool
|
||||
demoMode bool
|
||||
syncLiturgy bool
|
||||
)
|
||||
flag.StringVar(&addr, "addr", env("LP_ADDR", ":8080"), "HTTP listen address")
|
||||
flag.StringVar(&dbPath, "db", env("LP_DB", "lektorenplan.db"), "path to the SQLite database")
|
||||
flag.BoolVar(&seedDemo, "seed-demo", envBool("LP_SEED_DEMO", false), "create demo tenants and accounts on an empty database")
|
||||
flag.StringVar(&adminUser, "admin-user", env("LP_ADMIN_USER", "admin"), "initial administrator username")
|
||||
flag.StringVar(&adminPassword, "admin-password", env("LP_ADMIN_PASSWORD", ""), "initial administrator password (generated when empty)")
|
||||
flag.BoolVar(&secureCookies, "secure-cookies", envBool("LP_SECURE_COOKIES", false), "mark session cookies Secure (enable behind HTTPS)")
|
||||
flag.BoolVar(&demoMode, "demo", envBool("LP_DEMO_MODE", false), "show the demo badge in the interface")
|
||||
flag.BoolVar(&syncLiturgy, "sync-liturgy", envBool("LP_SYNC_LITURGY", true), "refresh the liturgical calendar daily in the background")
|
||||
flag.Parse()
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(dbPath), 0o755); err != nil && filepath.Dir(dbPath) != "." {
|
||||
return fmt.Errorf("create database directory: %w", err)
|
||||
}
|
||||
|
||||
st, err := store.Open(dbPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer st.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
if err := bootstrap(ctx, st, seedDemo, adminUser, adminPassword); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
server, err := web.New(st, web.Options{
|
||||
SecureCookies: secureCookies,
|
||||
Version: version,
|
||||
DemoMode: demoMode,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if syncLiturgy {
|
||||
go liturgyLoop(st)
|
||||
}
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: server.Handler(),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 120 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
|
||||
errc := make(chan error, 1)
|
||||
go func() {
|
||||
log.Printf("LektorenPlan %s lauscht auf %s (Datenbank: %s)", version, addr, dbPath)
|
||||
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
errc <- err
|
||||
}
|
||||
}()
|
||||
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
|
||||
|
||||
select {
|
||||
case err := <-errc:
|
||||
return err
|
||||
case sig := <-stop:
|
||||
log.Printf("%s empfangen, beende Server …", sig)
|
||||
}
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
return httpServer.Shutdown(shutdownCtx)
|
||||
}
|
||||
|
||||
func bootstrap(ctx context.Context, st *store.Store, seedDemo bool, adminUser, adminPassword string) error {
|
||||
if seedDemo {
|
||||
if err := st.SeedDemo(ctx); err != nil {
|
||||
return fmt.Errorf("seed demo data: %w", err)
|
||||
}
|
||||
log.Printf("Demo-Daten und Demo-Konten sind vorhanden.")
|
||||
}
|
||||
|
||||
count, err := st.CountUsers(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("count users: %w", err)
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
password := adminPassword
|
||||
generated := false
|
||||
if password == "" {
|
||||
password, err = randomPassword()
|
||||
if err != nil {
|
||||
return fmt.Errorf("generate administrator password: %w", err)
|
||||
}
|
||||
generated = true
|
||||
}
|
||||
created, err := st.EnsureAdmin(ctx, adminUser, password)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create administrator: %w", err)
|
||||
}
|
||||
if created && generated {
|
||||
log.Printf("Administrator %q angelegt. Einmaliges Passwort: %s", adminUser, password)
|
||||
log.Printf("Bitte nach der ersten Anmeldung ändern.")
|
||||
} else if created {
|
||||
log.Printf("Administrator %q angelegt.", adminUser)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// liturgyLoop refreshes the liturgical calendar once a day. Failures are
|
||||
// non-fatal: the bundled snapshot and local computation keep the app usable.
|
||||
func liturgyLoop(st *store.Store) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
|
||||
defer cancel()
|
||||
syncYears(ctx, st)
|
||||
|
||||
ticker := time.NewTicker(24 * time.Hour)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
|
||||
syncYears(ctx, st)
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
func syncYears(ctx context.Context, st *store.Store) {
|
||||
if st.Setting(ctx, "autoSyncLiturgy") == "0" {
|
||||
return
|
||||
}
|
||||
year := domain.Year(domain.Today())
|
||||
for _, target := range []int{year, year + 1} {
|
||||
if err := web.SyncLiturgyYear(ctx, st, target); err != nil {
|
||||
log.Printf("Liturgie-Synchronisierung %d: %v", target, err)
|
||||
continue
|
||||
}
|
||||
log.Printf("Liturgischer Kalender %d aktualisiert.", target)
|
||||
}
|
||||
}
|
||||
|
||||
func randomPassword() (string, error) {
|
||||
const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789"
|
||||
buf := make([]byte, 20)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for i := range buf {
|
||||
buf[i] = alphabet[int(buf[i])%len(alphabet)]
|
||||
}
|
||||
return string(buf), nil
|
||||
}
|
||||
|
||||
func env(key, fallback string) string {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envBool(key string, fallback bool) bool {
|
||||
value := os.Getenv(key)
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
parsed, err := strconv.ParseBool(value)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
+823
@@ -0,0 +1,823 @@
|
||||
// Package pdf renders printable service plans using only core PDF fonts.
|
||||
package pdf
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-pdf/fpdf"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
// Options configures the printable document.
|
||||
type Options struct {
|
||||
TenantName string
|
||||
Diocese string
|
||||
GeneratedAt time.Time
|
||||
}
|
||||
|
||||
func (o Options) tenant() string {
|
||||
if strings.TrimSpace(o.TenantName) == "" {
|
||||
return "LektorenPlan"
|
||||
}
|
||||
return o.TenantName
|
||||
}
|
||||
|
||||
func (o Options) diocese() string {
|
||||
if strings.TrimSpace(o.Diocese) == "" {
|
||||
return "Erzbistum Köln"
|
||||
}
|
||||
return o.Diocese
|
||||
}
|
||||
|
||||
func (o Options) generated() time.Time {
|
||||
if o.GeneratedAt.IsZero() {
|
||||
return time.Now()
|
||||
}
|
||||
return o.GeneratedAt
|
||||
}
|
||||
|
||||
// Palette is shared by both layouts.
|
||||
type palette struct {
|
||||
ink [3]int
|
||||
secondary [3]int
|
||||
tertiary [3]int
|
||||
line [3]int
|
||||
accent [3]int
|
||||
gold [3]int
|
||||
burgundy [3]int
|
||||
sundayWash [3]int
|
||||
feastWash [3]int
|
||||
open [3]int
|
||||
headerWash [3]int
|
||||
}
|
||||
|
||||
var colors = palette{
|
||||
ink: [3]int{31, 34, 40},
|
||||
secondary: [3]int{97, 98, 99},
|
||||
tertiary: [3]int{133, 130, 125},
|
||||
line: [3]int{215, 210, 201},
|
||||
accent: [3]int{46, 92, 87},
|
||||
gold: [3]int{184, 135, 59},
|
||||
burgundy: [3]int{125, 61, 74},
|
||||
sundayWash: [3]int{251, 244, 226},
|
||||
feastWash: [3]int{255, 244, 201},
|
||||
open: [3]int{179, 107, 33},
|
||||
headerWash: [3]int{245, 243, 238},
|
||||
}
|
||||
|
||||
func newPDF(orientation string) *fpdf.Fpdf {
|
||||
pdf := fpdf.New(orientation, "mm", "A4", "")
|
||||
pdf.SetAutoPageBreak(false, 0)
|
||||
pdf.SetCreator("LektorenPlan Web", true)
|
||||
pdf.SetTitle("LektorenPlan – Gottesdienstplan", true)
|
||||
pdf.SetMargins(8.5, 8.5, 8.5)
|
||||
return pdf
|
||||
}
|
||||
|
||||
func translator(pdf *fpdf.Fpdf) func(string) string {
|
||||
return pdf.UnicodeTranslatorFromDescriptor("cp1252")
|
||||
}
|
||||
|
||||
func setColor(pdf *fpdf.Fpdf, c [3]int) {
|
||||
pdf.SetTextColor(c[0], c[1], c[2])
|
||||
}
|
||||
|
||||
func setFill(pdf *fpdf.Fpdf, c [3]int) {
|
||||
pdf.SetFillColor(c[0], c[1], c[2])
|
||||
}
|
||||
|
||||
func setDraw(pdf *fpdf.Fpdf, c [3]int) {
|
||||
pdf.SetDrawColor(c[0], c[1], c[2])
|
||||
}
|
||||
|
||||
func hexColor(value string, fallback [3]int) [3]int {
|
||||
cleaned := strings.TrimPrefix(strings.TrimSpace(value), "#")
|
||||
if len(cleaned) != 6 {
|
||||
return fallback
|
||||
}
|
||||
parsed, err := strconv.ParseUint(cleaned, 16, 32)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
return [3]int{int(parsed >> 16 & 0xFF), int(parsed >> 8 & 0xFF), int(parsed & 0xFF)}
|
||||
}
|
||||
|
||||
func fit(pdf *fpdf.Fpdf, text string, width float64) string {
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
return ""
|
||||
}
|
||||
if pdf.GetStringWidth(text) <= width {
|
||||
return text
|
||||
}
|
||||
runes := []rune(text)
|
||||
for len(runes) > 0 {
|
||||
runes = runes[:len(runes)-1]
|
||||
candidate := strings.TrimSpace(string(runes)) + "…"
|
||||
if pdf.GetStringWidth(candidate) <= width {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// wrap splits text into at most maxLines lines fitting width.
|
||||
func wrap(pdf *fpdf.Fpdf, text string, width float64, maxLines int) []string {
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" || maxLines < 1 {
|
||||
return nil
|
||||
}
|
||||
words := strings.Fields(text)
|
||||
var lines []string
|
||||
current := ""
|
||||
for _, word := range words {
|
||||
candidate := word
|
||||
if current != "" {
|
||||
candidate = current + " " + word
|
||||
}
|
||||
if pdf.GetStringWidth(candidate) <= width {
|
||||
current = candidate
|
||||
continue
|
||||
}
|
||||
if current != "" {
|
||||
lines = append(lines, current)
|
||||
if len(lines) == maxLines {
|
||||
break
|
||||
}
|
||||
current = word
|
||||
} else {
|
||||
current = fit(pdf, word, width)
|
||||
}
|
||||
}
|
||||
if len(lines) < maxLines && current != "" {
|
||||
lines = append(lines, current)
|
||||
} else if len(lines) == maxLines && current != "" {
|
||||
lines[len(lines)-1] = fit(pdf, lines[len(lines)-1]+" "+current, width)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
func writeLines(pdf *fpdf.Fpdf, lines []string, x, y, width, lineHeight float64) float64 {
|
||||
for _, line := range lines {
|
||||
pdf.SetXY(x, y)
|
||||
pdf.CellFormat(width, lineHeight, line, "", 0, "L", false, 0, "")
|
||||
y += lineHeight
|
||||
}
|
||||
return y
|
||||
}
|
||||
|
||||
func drawBadge(pdf *fpdf.Fpdf, tr func(string) string, text string, x, y float64, color [3]int) {
|
||||
pdf.SetFont("Helvetica", "B", 5.4)
|
||||
width := pdf.GetStringWidth(tr(text)) + 3.2
|
||||
setFill(pdf, color)
|
||||
pdf.SetTextColor(255, 255, 255)
|
||||
pdf.RoundedRect(x, y, width, 3.4, 1, "1234", "F")
|
||||
pdf.SetXY(x, y+0.55)
|
||||
pdf.CellFormat(width, 2.4, tr(text), "", 0, "C", false, 0, "")
|
||||
}
|
||||
|
||||
func feastBadge(day *domain.LiturgicalDay) (string, [3]int) {
|
||||
if day == nil {
|
||||
return "", colors.accent
|
||||
}
|
||||
switch {
|
||||
case day.IsHighFeast():
|
||||
return "HOCHFEST", colors.gold
|
||||
case day.Rank == domain.RankFeast:
|
||||
return "FEST", colors.burgundy
|
||||
case day.Rank == domain.RankObligatoryMemorial:
|
||||
return "GEDENKTAG", colors.accent
|
||||
case day.IsObligation && !day.IsSunday():
|
||||
return "GEBOTEN", colors.accent
|
||||
default:
|
||||
return "", colors.accent
|
||||
}
|
||||
}
|
||||
|
||||
func shortWeekday(date time.Time) string {
|
||||
return strings.ToUpper(domain.ShortWeekdayName(date))
|
||||
}
|
||||
|
||||
func feastHint(day *domain.LiturgicalDay) string {
|
||||
if day == nil || day.Title == "" {
|
||||
return "Hochfest"
|
||||
}
|
||||
title := day.Title
|
||||
if index := strings.Index(title, " – "); index >= 0 {
|
||||
return title[index+len(" – "):]
|
||||
}
|
||||
if len([]rune(title)) <= 30 {
|
||||
return title
|
||||
}
|
||||
if strings.Contains(strings.ToLower(title), "hochfest") {
|
||||
return "Hochfest"
|
||||
}
|
||||
runes := []rune(title)
|
||||
return string(runes[:28]) + "…"
|
||||
}
|
||||
|
||||
func namesFor(service domain.ServiceWithAssignments, role domain.Role, people map[string]domain.Person) (string, int) {
|
||||
needed := service.Service.RequiredCount(role)
|
||||
assigned := service.AssignmentsFor(role)
|
||||
lastNames := make([]string, 0, len(assigned))
|
||||
for _, assignment := range assigned {
|
||||
if person, ok := people[assignment.PersonID]; ok {
|
||||
lastNames = append(lastNames, person.LastName)
|
||||
}
|
||||
}
|
||||
open := needed - len(lastNames)
|
||||
if open < 0 {
|
||||
open = 0
|
||||
}
|
||||
parts := append([]string{}, lastNames...)
|
||||
if open > 0 {
|
||||
parts = append(parts, "offen")
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return "offen", 0
|
||||
}
|
||||
return strings.Join(parts, ", "), open
|
||||
}
|
||||
|
||||
// FullPlan writes the A4 landscape calendar.
|
||||
func FullPlan(w io.Writer, r domain.DayRange, rows []domain.DayPlanRow, churches []domain.Church, people []domain.Person, opts Options) error {
|
||||
pdf := newPDF("L")
|
||||
tr := translator(pdf)
|
||||
peopleByID := map[string]domain.Person{}
|
||||
for _, person := range people {
|
||||
peopleByID[person.ID] = person
|
||||
}
|
||||
|
||||
const (
|
||||
pageWidth = 297.0
|
||||
pageHeight = 210.0
|
||||
margin = 8.5
|
||||
headerH = 26.0
|
||||
colH = 8.5
|
||||
footerH = 7.0
|
||||
dateW = 17.0
|
||||
liturgyW = 57.0
|
||||
gap = 1.35
|
||||
)
|
||||
churchWidth := (pageWidth - margin*2 - dateW - liturgyW - gap*5) / 4
|
||||
contentTop := margin + headerH + colH + 1.5
|
||||
contentBottom := pageHeight - margin - footerH
|
||||
|
||||
columns := churches
|
||||
if len(columns) > 4 {
|
||||
columns = columns[:4]
|
||||
}
|
||||
|
||||
drawHeader := func(continuation bool) {
|
||||
setColor(pdf, colors.accent)
|
||||
pdf.SetFont("Helvetica", "B", 6.4)
|
||||
pdf.SetXY(margin, margin)
|
||||
pdf.CellFormat(150, 3.4, tr("LEKTORENPLAN · "+strings.ToUpper(opts.tenant())), "", 0, "L", false, 0, "")
|
||||
|
||||
setColor(pdf, colors.ink)
|
||||
pdf.SetFont("Times", "B", 18)
|
||||
title := "Gottesdienstplan"
|
||||
if continuation {
|
||||
title = "Gottesdienstplan · Fortsetzung"
|
||||
}
|
||||
pdf.SetXY(margin, margin+4.6)
|
||||
pdf.CellFormat(150, 7, tr(title), "", 0, "L", false, 0, "")
|
||||
|
||||
setColor(pdf, colors.secondary)
|
||||
pdf.SetFont("Helvetica", "", 8.2)
|
||||
pdf.SetXY(margin, margin+13.2)
|
||||
pdf.CellFormat(160, 4, tr(r.LongTitle()), "", 0, "L", false, 0, "")
|
||||
|
||||
rightX := pageWidth - margin - 82
|
||||
setColor(pdf, colors.tertiary)
|
||||
pdf.SetFont("Helvetica", "", 6.8)
|
||||
pdf.SetXY(rightX, margin)
|
||||
pdf.CellFormat(82, 3.2, tr("Erstellt am "+domain.MediumString(opts.generated())), "", 0, "R", false, 0, "")
|
||||
pdf.SetXY(rightX, margin+4.4)
|
||||
pdf.CellFormat(82, 3.2, tr("Liturgischer Kalender: "+opts.diocese()), "", 0, "R", false, 0, "")
|
||||
pdf.SetXY(rightX, margin+8.8)
|
||||
pdf.CellFormat(82, 3.2, tr("Daten von www.eucharistiefeier.de"), "", 0, "R", false, 0, "")
|
||||
|
||||
setDraw(pdf, colors.line)
|
||||
pdf.SetLineWidth(0.25)
|
||||
pdf.Line(margin, margin+headerH-2.2, pageWidth-margin, margin+headerH-2.2)
|
||||
}
|
||||
|
||||
drawColumnHeader := func() {
|
||||
y := margin + headerH
|
||||
setFill(pdf, colors.headerWash)
|
||||
pdf.Rect(margin, y, pageWidth-margin*2, colH, "F")
|
||||
x := margin + 2
|
||||
setColor(pdf, colors.tertiary)
|
||||
pdf.SetFont("Helvetica", "B", 5.8)
|
||||
pdf.SetXY(x, y+2.8)
|
||||
pdf.CellFormat(dateW-2, 3, tr("TAG"), "", 0, "L", false, 0, "")
|
||||
x += dateW
|
||||
pdf.SetXY(x, y+2.8)
|
||||
pdf.CellFormat(liturgyW, 3, tr("LITURGIE & LESUNGEN"), "", 0, "L", false, 0, "")
|
||||
x += liturgyW + gap
|
||||
for _, church := range columns {
|
||||
color := hexColor(church.ColorHex, colors.accent)
|
||||
setColor(pdf, color)
|
||||
pdf.SetFont("Times", "B", 8.2)
|
||||
pdf.SetXY(x+1.3, y+1.2)
|
||||
pdf.CellFormat(churchWidth-2.6, 4, tr(fit(pdf, church.Name, churchWidth-2.6)), "", 0, "L", false, 0, "")
|
||||
setColor(pdf, colors.tertiary)
|
||||
pdf.SetFont("Helvetica", "", 5.2)
|
||||
pdf.SetXY(x+1.3, y+5.1)
|
||||
pdf.CellFormat(churchWidth-2.6, 2.6, tr(fit(pdf, church.Address, churchWidth-2.6)), "", 0, "L", false, 0, "")
|
||||
x += churchWidth + gap
|
||||
}
|
||||
setDraw(pdf, colors.line)
|
||||
pdf.SetLineWidth(0.3)
|
||||
pdf.Line(margin, y+colH, pageWidth-margin, y+colH)
|
||||
}
|
||||
|
||||
drawFooter := func(page int) {
|
||||
y := pageHeight - margin - footerH
|
||||
setDraw(pdf, colors.line)
|
||||
pdf.SetLineWidth(0.25)
|
||||
pdf.Line(margin, y+1.5, pageWidth-margin, y+1.5)
|
||||
setColor(pdf, colors.tertiary)
|
||||
pdf.SetFont("Helvetica", "", 5.8)
|
||||
pdf.SetXY(margin, y+2.6)
|
||||
pdf.CellFormat(150, 3, tr("LektorenPlan · "+r.ShortTitle()), "", 0, "L", false, 0, "")
|
||||
pdf.SetXY(pageWidth-margin-30, y+2.6)
|
||||
pdf.CellFormat(30, 3, tr(fmt.Sprintf("Seite %d", page)), "", 0, "R", false, 0, "")
|
||||
}
|
||||
|
||||
rowHeight := func(row domain.DayPlanRow) float64 {
|
||||
height := 15.0
|
||||
if row.LiturgicalDay != nil {
|
||||
titles := wrap(pdf, row.LiturgicalDay.DisplayTitle(), liturgyW-4, 3)
|
||||
readings := []string{}
|
||||
if !row.LiturgicalDay.Readings.IsEmpty() {
|
||||
readings = wrap(pdf, row.LiturgicalDay.Readings.ShortLabel(), liturgyW-4, 3)
|
||||
}
|
||||
lit := 4.5 + float64(len(titles))*3.4 + float64(len(readings))*2.5
|
||||
if badge, _ := feastBadge(row.LiturgicalDay); badge != "" {
|
||||
lit += 4.2
|
||||
}
|
||||
if lit+2 > height {
|
||||
height = lit + 2
|
||||
}
|
||||
}
|
||||
for _, service := range row.Services {
|
||||
h := 5.0
|
||||
if service.Service.Location != nil && strings.TrimSpace(*service.Service.Location) != "" {
|
||||
h += 3.2
|
||||
}
|
||||
for _, role := range domain.AllRoles {
|
||||
if service.Service.RequiredCount(role) > 0 {
|
||||
h += 3.4
|
||||
}
|
||||
}
|
||||
h += 2.2
|
||||
if h > height {
|
||||
height = h
|
||||
}
|
||||
}
|
||||
if height > 53 {
|
||||
height = 53
|
||||
}
|
||||
return height
|
||||
}
|
||||
|
||||
pdf.AddPage()
|
||||
drawHeader(false)
|
||||
drawColumnHeader()
|
||||
page := 1
|
||||
y := contentTop
|
||||
|
||||
if len(rows) == 0 {
|
||||
setColor(pdf, colors.secondary)
|
||||
pdf.SetFont("Times", "", 12)
|
||||
pdf.SetXY(margin, y+4)
|
||||
pdf.CellFormat(pageWidth-margin*2, 6, tr("Für den gewählten Zeitraum sind keine Gottesdienste hinterlegt."), "", 0, "L", false, 0, "")
|
||||
}
|
||||
|
||||
for index, row := range rows {
|
||||
height := rowHeight(row)
|
||||
if y+height > contentBottom {
|
||||
drawFooter(page)
|
||||
page++
|
||||
pdf.AddPage()
|
||||
drawHeader(true)
|
||||
drawColumnHeader()
|
||||
y = contentTop
|
||||
}
|
||||
|
||||
isSunday := row.IsSunday()
|
||||
isFeast := row.IsHighFeast()
|
||||
isHoliday := row.IsObligation() && !isSunday
|
||||
if isFeast {
|
||||
setFill(pdf, colors.feastWash)
|
||||
pdf.Rect(margin, y, pageWidth-margin*2, height, "F")
|
||||
} else if isSunday || isHoliday {
|
||||
setFill(pdf, colors.sundayWash)
|
||||
pdf.Rect(margin, y, pageWidth-margin*2, height, "F")
|
||||
}
|
||||
|
||||
x := margin
|
||||
// Date cell.
|
||||
setColor(pdf, colors.tertiary)
|
||||
if isSunday {
|
||||
setColor(pdf, colors.burgundy)
|
||||
}
|
||||
pdf.SetFont("Helvetica", "B", 5.9)
|
||||
pdf.SetXY(x+1.5, y+1.5)
|
||||
pdf.CellFormat(dateW-1.5, 3, tr(shortWeekday(row.Date)), "", 0, "L", false, 0, "")
|
||||
if isFeast {
|
||||
setColor(pdf, colors.gold)
|
||||
} else if isSunday {
|
||||
setColor(pdf, colors.burgundy)
|
||||
} else {
|
||||
setColor(pdf, colors.ink)
|
||||
}
|
||||
pdf.SetFont("Times", "B", 13.5)
|
||||
pdf.SetXY(x+1.5, y+4)
|
||||
pdf.CellFormat(dateW-1.5, 6, tr(fmt.Sprintf("%d.", domain.DayNumber(row.Date))), "", 0, "L", false, 0, "")
|
||||
setColor(pdf, colors.tertiary)
|
||||
pdf.SetFont("Helvetica", "", 5.9)
|
||||
pdf.SetXY(x+1.5, y+11)
|
||||
pdf.CellFormat(dateW-1.5, 3, tr(domain.ShortMonthName(row.Date)), "", 0, "L", false, 0, "")
|
||||
if isSunday {
|
||||
setColor(pdf, colors.burgundy)
|
||||
pdf.SetFont("Helvetica", "B", 4.9)
|
||||
pdf.SetXY(x+1.5, y+14.5)
|
||||
pdf.CellFormat(dateW, 2.5, tr("SONNTAG"), "", 0, "L", false, 0, "")
|
||||
}
|
||||
x += dateW
|
||||
|
||||
// Liturgy.
|
||||
textY := y + 1.6
|
||||
if day := row.LiturgicalDay; day != nil {
|
||||
if badge, color := feastBadge(day); badge != "" {
|
||||
drawBadge(pdf, tr, badge, x+1.2, textY, color)
|
||||
textY += 4.2
|
||||
}
|
||||
titleColor := colors.ink
|
||||
if isSunday {
|
||||
titleColor = colors.burgundy
|
||||
}
|
||||
setColor(pdf, titleColor)
|
||||
fontStyle := "B"
|
||||
if !day.IsFeast() {
|
||||
fontStyle = ""
|
||||
}
|
||||
pdf.SetFont("Times", fontStyle, 8.2)
|
||||
titleLines := wrap(pdf, day.DisplayTitle(), liturgyW-4, 3)
|
||||
textY = writeLines(pdf, titleLines, x+1.2, textY, liturgyW-4, 3.3)
|
||||
if !day.Readings.IsEmpty() {
|
||||
setColor(pdf, colors.secondary)
|
||||
pdf.SetFont("Helvetica", "", 5.6)
|
||||
readingLines := wrap(pdf, day.Readings.ShortLabel(), liturgyW-4, 3)
|
||||
writeLines(pdf, readingLines, x+1.2, textY+0.4, liturgyW-4, 2.5)
|
||||
}
|
||||
}
|
||||
x += liturgyW + gap
|
||||
|
||||
// Church columns.
|
||||
for _, church := range columns {
|
||||
services := row.ServicesForChurch(church.ID)
|
||||
serviceY := y + 1.4
|
||||
color := hexColor(church.ColorHex, colors.accent)
|
||||
for _, service := range services {
|
||||
setColor(pdf, color)
|
||||
pdf.SetFont("Helvetica", "B", 6.2)
|
||||
label := fit(pdf, service.Service.TimeLabel()+" "+service.Service.Title, churchWidth-4)
|
||||
pdf.SetXY(x+1.2, serviceY)
|
||||
pdf.CellFormat(churchWidth-2.4, 3.6, tr(label), "", 0, "L", false, 0, "")
|
||||
serviceY += 3.4
|
||||
if service.Service.Location != nil && strings.TrimSpace(*service.Service.Location) != "" {
|
||||
setColor(pdf, colors.burgundy)
|
||||
pdf.SetFont("Helvetica", "B", 5.4)
|
||||
pdf.SetXY(x+1.6, serviceY)
|
||||
pdf.CellFormat(churchWidth-3, 2.8, tr(fit(pdf, *service.Service.Location, churchWidth-3)), "", 0, "L", false, 0, "")
|
||||
serviceY += 3.0
|
||||
}
|
||||
for _, role := range domain.AllRoles {
|
||||
if service.Service.RequiredCount(role) <= 0 {
|
||||
continue
|
||||
}
|
||||
names, open := namesFor(service, role, peopleByID)
|
||||
prefix := "L: "
|
||||
if role == domain.RoleHelper {
|
||||
prefix = "K: "
|
||||
}
|
||||
text := prefix + names
|
||||
if open > 0 {
|
||||
setColor(pdf, colors.open)
|
||||
pdf.SetFont("Helvetica", "B", 5.4)
|
||||
} else {
|
||||
setColor(pdf, colors.secondary)
|
||||
pdf.SetFont("Helvetica", "", 5.4)
|
||||
}
|
||||
lines := wrap(pdf, text, churchWidth-3, 2)
|
||||
serviceY = writeLines(pdf, lines, x+1.6, serviceY, churchWidth-3, 3.0)
|
||||
}
|
||||
serviceY += 1.5
|
||||
if serviceY > y+height-2 {
|
||||
break
|
||||
}
|
||||
}
|
||||
setDraw(pdf, colors.line)
|
||||
pdf.SetLineWidth(0.15)
|
||||
pdf.Line(x, y+1.5, x, y+height-1.5)
|
||||
x += churchWidth + gap
|
||||
}
|
||||
|
||||
if index < len(rows)-1 {
|
||||
setDraw(pdf, colors.line)
|
||||
pdf.SetLineWidth(0.2)
|
||||
pdf.Line(margin, y+height, pageWidth-margin, y+height)
|
||||
}
|
||||
y += height
|
||||
}
|
||||
|
||||
drawFooter(page)
|
||||
if err := pdf.Output(w); err != nil {
|
||||
return err
|
||||
}
|
||||
return pdf.Error()
|
||||
}
|
||||
|
||||
// CompactPlan writes the A4 portrait service list.
|
||||
func CompactPlan(w io.Writer, r domain.DayRange, rows []domain.DayPlanRow, people []domain.Person, opts Options) error {
|
||||
pdf := newPDF("P")
|
||||
tr := translator(pdf)
|
||||
peopleByID := map[string]domain.Person{}
|
||||
for _, person := range people {
|
||||
peopleByID[person.ID] = person
|
||||
}
|
||||
|
||||
const (
|
||||
pageWidth = 210.0
|
||||
pageHeight = 297.0
|
||||
margin = 12.7
|
||||
headerH = 24.7
|
||||
colH = 8.1
|
||||
footerH = 8.5
|
||||
dateW = 25.0
|
||||
serviceW = 69.0
|
||||
lectorW = 41.0
|
||||
gap = 2.8
|
||||
)
|
||||
helperW := pageWidth - margin*2 - dateW - serviceW - lectorW - gap*3
|
||||
contentTop := margin + headerH + colH + 2
|
||||
contentBottom := pageHeight - margin - footerH
|
||||
|
||||
drawHeader := func(continuation bool) {
|
||||
setColor(pdf, colors.accent)
|
||||
pdf.SetFont("Helvetica", "B", 6.2)
|
||||
pdf.SetXY(margin, margin)
|
||||
pdf.CellFormat(120, 3.2, tr("LEKTORENPLAN · "+strings.ToUpper(opts.tenant())), "", 0, "L", false, 0, "")
|
||||
|
||||
setColor(pdf, colors.ink)
|
||||
pdf.SetFont("Times", "B", 17)
|
||||
title := "Gottesdienstliste"
|
||||
if continuation {
|
||||
title = "Gottesdienstliste · Fortsetzung"
|
||||
}
|
||||
pdf.SetXY(margin, margin+4.4)
|
||||
pdf.CellFormat(130, 6.5, tr(title), "", 0, "L", false, 0, "")
|
||||
|
||||
setColor(pdf, colors.secondary)
|
||||
pdf.SetFont("Helvetica", "", 7.8)
|
||||
pdf.SetXY(margin, margin+13)
|
||||
pdf.CellFormat(120, 4, tr(r.LongTitle()), "", 0, "L", false, 0, "")
|
||||
|
||||
rightX := pageWidth - margin - 62
|
||||
setColor(pdf, colors.tertiary)
|
||||
pdf.SetFont("Helvetica", "B", 6.4)
|
||||
pdf.SetXY(rightX, margin)
|
||||
pdf.CellFormat(62, 3.2, tr("A4 hoch · kompakte Liste"), "", 0, "R", false, 0, "")
|
||||
pdf.SetFont("Helvetica", "", 6.4)
|
||||
pdf.SetXY(rightX, margin+4.5)
|
||||
pdf.CellFormat(62, 3.2, tr("Erstellt am "+domain.MediumString(opts.generated())), "", 0, "R", false, 0, "")
|
||||
pdf.SetXY(rightX, margin+9)
|
||||
pdf.CellFormat(62, 3.2, tr("Daten von www.eucharistiefeier.de"), "", 0, "R", false, 0, "")
|
||||
|
||||
setDraw(pdf, colors.line)
|
||||
pdf.SetLineWidth(0.25)
|
||||
pdf.Line(margin, margin+headerH-2.2, pageWidth-margin, margin+headerH-2.2)
|
||||
}
|
||||
|
||||
drawColumnHeader := func() {
|
||||
y := margin + headerH
|
||||
setFill(pdf, colors.headerWash)
|
||||
pdf.Rect(margin, y, pageWidth-margin*2, colH, "F")
|
||||
x := margin + 2
|
||||
setColor(pdf, colors.tertiary)
|
||||
pdf.SetFont("Helvetica", "B", 5.8)
|
||||
headers := []struct {
|
||||
Text string
|
||||
Width float64
|
||||
}{
|
||||
{"TAG", dateW - 2}, {"GOTTESDIENST", serviceW}, {"LEKTOREN", lectorW}, {"KOMMUNIONHELFER", helperW},
|
||||
}
|
||||
for _, header := range headers {
|
||||
pdf.SetXY(x, y+2.7)
|
||||
pdf.CellFormat(header.Width, 3, tr(header.Text), "", 0, "L", false, 0, "")
|
||||
x += header.Width + gap
|
||||
}
|
||||
setDraw(pdf, colors.line)
|
||||
pdf.SetLineWidth(0.3)
|
||||
pdf.Line(margin, y+colH, pageWidth-margin, y+colH)
|
||||
}
|
||||
|
||||
drawFooter := func(page int) {
|
||||
y := pageHeight - margin - footerH
|
||||
setDraw(pdf, colors.line)
|
||||
pdf.SetLineWidth(0.25)
|
||||
pdf.Line(margin, y+1.5, pageWidth-margin, y+1.5)
|
||||
setColor(pdf, colors.tertiary)
|
||||
pdf.SetFont("Helvetica", "", 5.8)
|
||||
pdf.SetXY(margin, y+2.6)
|
||||
pdf.CellFormat(150, 3, tr("LektorenPlan · kompakte Liste · "+r.ShortTitle()), "", 0, "L", false, 0, "")
|
||||
pdf.SetXY(pageWidth-margin-25, y+2.6)
|
||||
pdf.CellFormat(25, 3, tr(fmt.Sprintf("Seite %d", page)), "", 0, "R", false, 0, "")
|
||||
}
|
||||
|
||||
rowHeight := func(service domain.ServiceWithAssignments) float64 {
|
||||
height := 7.0
|
||||
if service.Service.Title != "" {
|
||||
height += 1.8
|
||||
}
|
||||
lectorNames, _ := namesFor(service, domain.RoleLector, peopleByID)
|
||||
helperNames, _ := namesFor(service, domain.RoleHelper, peopleByID)
|
||||
lectorLines := len(wrap(pdf, lectorNames, lectorW-2, 2))
|
||||
helperLines := len(wrap(pdf, helperNames, helperW-2, 2))
|
||||
if lines := maxInt(lectorLines, helperLines); float64(lines)*3 > height {
|
||||
height = float64(lines) * 3
|
||||
}
|
||||
if len(service.AssignmentsFor(domain.RoleLector)) == 0 && service.Service.RequiredCount(domain.RoleLector) > 0 {
|
||||
height += 1.2
|
||||
}
|
||||
return maxFloat(height, 8.2) + 1.6
|
||||
}
|
||||
|
||||
pdf.AddPage()
|
||||
drawHeader(false)
|
||||
drawColumnHeader()
|
||||
page := 1
|
||||
y := contentTop
|
||||
|
||||
visibleDays := 0
|
||||
for _, row := range rows {
|
||||
if len(row.Services) > 0 {
|
||||
visibleDays++
|
||||
}
|
||||
}
|
||||
if visibleDays == 0 {
|
||||
setColor(pdf, colors.secondary)
|
||||
pdf.SetFont("Times", "", 12)
|
||||
pdf.SetXY(margin, y+5)
|
||||
pdf.CellFormat(pageWidth-margin*2, 6, tr("Für den gewählten Zeitraum sind keine Gottesdienste hinterlegt."), "", 0, "L", false, 0, "")
|
||||
}
|
||||
|
||||
for dayIndex, row := range rows {
|
||||
if len(row.Services) == 0 {
|
||||
continue
|
||||
}
|
||||
services := append([]domain.ServiceWithAssignments(nil), row.Services...)
|
||||
sortServices(services)
|
||||
for serviceIndex, service := range services {
|
||||
height := rowHeight(service)
|
||||
if y+height > contentBottom {
|
||||
drawFooter(page)
|
||||
page++
|
||||
pdf.AddPage()
|
||||
drawHeader(true)
|
||||
drawColumnHeader()
|
||||
y = contentTop
|
||||
}
|
||||
if row.IsHighFeast() {
|
||||
setFill(pdf, colors.feastWash)
|
||||
pdf.Rect(margin, y, pageWidth-margin*2, height, "F")
|
||||
} else if row.IsSunday() {
|
||||
setFill(pdf, colors.sundayWash)
|
||||
pdf.Rect(margin, y, pageWidth-margin*2, height, "F")
|
||||
}
|
||||
|
||||
if serviceIndex == 0 {
|
||||
setColor(pdf, colors.tertiary)
|
||||
if row.IsSunday() || row.IsHighFeast() {
|
||||
setColor(pdf, colors.burgundy)
|
||||
}
|
||||
pdf.SetFont("Helvetica", "B", 5.8)
|
||||
pdf.SetXY(margin+1.5, y+1.8)
|
||||
pdf.CellFormat(dateW-2, 3, tr(shortWeekday(row.Date)), "", 0, "L", false, 0, "")
|
||||
if row.IsHighFeast() {
|
||||
setColor(pdf, colors.gold)
|
||||
} else if row.IsSunday() {
|
||||
setColor(pdf, colors.burgundy)
|
||||
} else {
|
||||
setColor(pdf, colors.ink)
|
||||
}
|
||||
pdf.SetFont("Times", "B", 12.5)
|
||||
pdf.SetXY(margin+1.5, y+4.3)
|
||||
pdf.CellFormat(dateW-2, 5, tr(fmt.Sprintf("%d.%d.", domain.DayNumber(row.Date), domain.Month(row.Date))), "", 0, "L", false, 0, "")
|
||||
if row.IsHighFeast() {
|
||||
setColor(pdf, colors.gold)
|
||||
pdf.SetFont("Helvetica", "B", 5.2)
|
||||
hint := wrap(pdf, feastHint(row.LiturgicalDay), dateW-4, 3)
|
||||
writeLines(pdf, hint, margin+1.5, y+10, dateW-4, 2.4)
|
||||
}
|
||||
}
|
||||
|
||||
x := margin + dateW + gap
|
||||
churchColor := hexColor(service.Church.ColorHex, colors.accent)
|
||||
setColor(pdf, churchColor)
|
||||
pdf.SetFont("Helvetica", "B", 7.2)
|
||||
place := service.Service.PlaceName(service.Church)
|
||||
line := fit(pdf, service.Service.TimeLabel()+" · "+place, serviceW-2)
|
||||
pdf.SetXY(x, y+1.6)
|
||||
pdf.CellFormat(serviceW-2, 3.4, tr(line), "", 0, "L", false, 0, "")
|
||||
if service.Service.Title != "" {
|
||||
setColor(pdf, colors.secondary)
|
||||
if service.Service.Kind == domain.KindSpecial {
|
||||
setColor(pdf, colors.burgundy)
|
||||
}
|
||||
pdf.SetFont("Helvetica", "", 6.1)
|
||||
title := service.Service.Title
|
||||
if service.Service.Kind == domain.KindSpecial {
|
||||
title += " · Sondergottesdienst"
|
||||
}
|
||||
pdf.SetXY(x, y+4.8)
|
||||
pdf.CellFormat(serviceW-2, 3, tr(fit(pdf, title, serviceW-2)), "", 0, "L", false, 0, "")
|
||||
}
|
||||
x += serviceW + gap
|
||||
|
||||
drawRole := func(role domain.Role, width float64) {
|
||||
needed := service.Service.RequiredCount(role)
|
||||
if needed <= 0 {
|
||||
setColor(pdf, colors.tertiary)
|
||||
pdf.SetFont("Helvetica", "", 6.6)
|
||||
pdf.SetXY(x, y+1.8)
|
||||
pdf.CellFormat(width, 3, tr("—"), "", 0, "L", false, 0, "")
|
||||
return
|
||||
}
|
||||
names, open := namesFor(service, role, peopleByID)
|
||||
if open > 0 {
|
||||
setColor(pdf, colors.open)
|
||||
pdf.SetFont("Helvetica", "B", 6.6)
|
||||
} else {
|
||||
setColor(pdf, colors.ink)
|
||||
pdf.SetFont("Helvetica", "", 6.6)
|
||||
}
|
||||
lines := wrap(pdf, names, width, 2)
|
||||
writeLines(pdf, lines, x, y+1.8, width, 3)
|
||||
}
|
||||
drawRole(domain.RoleLector, lectorW)
|
||||
x += lectorW + gap
|
||||
drawRole(domain.RoleHelper, helperW)
|
||||
|
||||
setDraw(pdf, colors.line)
|
||||
pdf.SetLineWidth(0.15)
|
||||
pdf.Line(margin, y+height, pageWidth-margin, y+height)
|
||||
y += height
|
||||
}
|
||||
if dayIndex < len(rows)-1 {
|
||||
setDraw(pdf, colors.line)
|
||||
pdf.SetLineWidth(0.3)
|
||||
pdf.Line(margin+1, y, pageWidth-margin-1, y)
|
||||
}
|
||||
}
|
||||
|
||||
drawFooter(page)
|
||||
if err := pdf.Output(w); err != nil {
|
||||
return err
|
||||
}
|
||||
return pdf.Error()
|
||||
}
|
||||
|
||||
func sortServices(services []domain.ServiceWithAssignments) {
|
||||
sort.SliceStable(services, func(i, j int) bool {
|
||||
a, b := services[i].Service, services[j].Service
|
||||
if a.TimeMinutes != b.TimeMinutes {
|
||||
return a.TimeMinutes < b.TimeMinutes
|
||||
}
|
||||
return services[i].Church.SortIndex < services[j].Church.SortIndex
|
||||
})
|
||||
}
|
||||
|
||||
func maxInt(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func maxFloat(a, b float64) float64 {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package pdf
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
func sampleRows() (domain.DayRange, []domain.DayPlanRow, []domain.Church, []domain.Person) {
|
||||
church := domain.Church{ID: "c1", Name: "St. Andreas", ShortName: "Andreas",
|
||||
Symbol: domain.SymbolBasilica, ColorHex: "#9B5B44", Address: "Andreasstraße 1", SortIndex: 0}
|
||||
person := domain.Person{ID: "p1", FirstName: "Anna", LastName: "Berg",
|
||||
Roles: []domain.Role{domain.RoleLector}, Active: true}
|
||||
service := domain.ServiceOccurrence{
|
||||
ID: "s1", ChurchID: "c1", Date: domain.MustDate("2026-11-15"),
|
||||
TimeMinutes: 9*60 + 30, Title: "Hochamt", LectorsNeeded: 1, HelpersNeeded: 2,
|
||||
Kind: domain.KindRegular, CreatedAt: time.Now(),
|
||||
}
|
||||
assignment := domain.Assignment{ID: "a1", ServiceID: "s1", PersonID: "p1", Role: domain.RoleLector}
|
||||
liturgy := domain.LiturgicalDay{
|
||||
Date: domain.MustDate("2026-11-15"), Title: "33. Sonntag im Jahreskreis",
|
||||
Rank: domain.RankSolemnity, Color: domain.ColorGreen,
|
||||
Readings: domain.Readings{First: "Mal 3, 19-20a", Gospel: "Lk 21, 5-19"},
|
||||
IsObligation: true, Source: "test",
|
||||
}
|
||||
row := domain.DayPlanRow{
|
||||
Date: domain.MustDate("2026-11-15"), LiturgicalDay: &liturgy,
|
||||
Services: []domain.ServiceWithAssignments{{Service: service, Church: church, Assignments: []domain.Assignment{assignment}}},
|
||||
}
|
||||
r := domain.NewDayRange(domain.MustDate("2026-11-15"), domain.MustDate("2026-11-15"))
|
||||
return r, []domain.DayPlanRow{row}, []domain.Church{church}, []domain.Person{person}
|
||||
}
|
||||
|
||||
func TestFullPlan(t *testing.T) {
|
||||
r, rows, churches, people := sampleRows()
|
||||
var buf bytes.Buffer
|
||||
if err := FullPlan(&buf, r, rows, churches, people, Options{TenantName: "Bad Godesberg"}); err != nil {
|
||||
t.Fatalf("render: %v", err)
|
||||
}
|
||||
if buf.Len() < 1000 || !bytes.HasPrefix(buf.Bytes(), []byte("%PDF")) {
|
||||
t.Fatalf("unexpected PDF output (%d bytes)", buf.Len())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompactPlan(t *testing.T) {
|
||||
r, rows, _, people := sampleRows()
|
||||
var buf bytes.Buffer
|
||||
if err := CompactPlan(&buf, r, rows, people, Options{TenantName: "Bad Godesberg"}); err != nil {
|
||||
t.Fatalf("render: %v", err)
|
||||
}
|
||||
if buf.Len() < 1000 || !bytes.HasPrefix(buf.Bytes(), []byte("%PDF")) {
|
||||
t.Fatalf("unexpected PDF output (%d bytes)", buf.Len())
|
||||
}
|
||||
}
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build a static Linux/arm64 binary for LektorenPlan.
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/build-linux-arm64.sh [output]
|
||||
#
|
||||
# The build is CGO-free, so the result runs on any Linux arm64 distribution
|
||||
# with a reasonably recent kernel (no SQLite or libc runtime needed).
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
output="${1:-dist/lektorenplan-linux-arm64}"
|
||||
version="${LP_VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo 1.0.0)}"
|
||||
|
||||
mkdir -p "$(dirname "$output")"
|
||||
|
||||
echo "Baue $output (Version $version) …"
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 \
|
||||
go build -trimpath -buildvcs=false \
|
||||
-ldflags "-s -w -X main.version=$version" \
|
||||
-o "$output" .
|
||||
|
||||
echo "Fertig: $output"
|
||||
file "$output" 2>/dev/null || true
|
||||
@@ -0,0 +1,24 @@
|
||||
[Unit]
|
||||
Description=LektorenPlan – Gottesdienst- und Dienstplanung
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=lektorenplan
|
||||
Group=lektorenplan
|
||||
WorkingDirectory=/opt/lektorenplan
|
||||
ExecStart=/opt/lektorenplan/lektorenplan -addr 127.0.0.1:8080 -db /var/lib/lektorenplan/lektorenplan.db
|
||||
Environment=LP_SEED_DEMO=false
|
||||
Environment=LP_SECURE_COOKIES=true
|
||||
Restart=on-failure
|
||||
RestartSec=3
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ReadWritePaths=/var/lib/lektorenplan
|
||||
UMask=0077
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,424 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
// UserRole is the application-wide permission level of an account.
|
||||
type UserRole string
|
||||
|
||||
const (
|
||||
RoleAdmin UserRole = "admin"
|
||||
RoleEditor UserRole = "editor"
|
||||
RoleReader UserRole = "reader"
|
||||
)
|
||||
|
||||
// UserRoleTitle returns the German label of a role.
|
||||
func UserRoleTitle(role UserRole) string {
|
||||
switch role {
|
||||
case RoleAdmin:
|
||||
return "Administrator"
|
||||
case RoleEditor:
|
||||
return "Redakteur"
|
||||
default:
|
||||
return "Leser"
|
||||
}
|
||||
}
|
||||
|
||||
// IsValid reports whether the role is known.
|
||||
func (r UserRole) IsValid() bool {
|
||||
return r == RoleAdmin || r == RoleEditor || r == RoleReader
|
||||
}
|
||||
|
||||
// CanEdit reports whether the role may modify planning data.
|
||||
func (r UserRole) CanEdit() bool { return r == RoleAdmin || r == RoleEditor }
|
||||
|
||||
// IsAdmin reports whether the role may manage tenants and accounts.
|
||||
func (r UserRole) IsAdmin() bool { return r == RoleAdmin }
|
||||
|
||||
// User is a login account. Memberships are loaded on demand.
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"displayName"`
|
||||
PasswordHash string `json:"-"`
|
||||
Role UserRole `json:"role"`
|
||||
Active bool `json:"active"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
TenantIDs []string `json:"tenantIDs,omitempty"`
|
||||
}
|
||||
|
||||
// RoleTitle is a template helper.
|
||||
func (u *User) RoleTitle() string { return UserRoleTitle(u.Role) }
|
||||
|
||||
// Users lists all accounts with their memberships.
|
||||
func (s *Store) Users(ctx context.Context) ([]User, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
"SELECT id, username, display_name, password_hash, role, active, created_at FROM users ORDER BY username COLLATE NOCASE")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []User
|
||||
for rows.Next() {
|
||||
user, err := scanUser(rows)
|
||||
if err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, *user)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
// Close the result set before loading memberships: the pool deliberately
|
||||
// uses a single connection, so nested queries would otherwise block.
|
||||
rows.Close()
|
||||
|
||||
for i := range out {
|
||||
tenantIDs, err := s.Memberships(ctx, out[i].ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[i].TenantIDs = tenantIDs
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// User loads an account by id.
|
||||
func (s *Store) User(ctx context.Context, id string) (*User, error) {
|
||||
row := s.db.QueryRowContext(ctx,
|
||||
"SELECT id, username, display_name, password_hash, role, active, created_at FROM users WHERE id=?", id)
|
||||
user, err := scanUser(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenantIDs, err := s.Memberships(ctx, user.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user.TenantIDs = tenantIDs
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// UserByUsername loads an account by login name.
|
||||
func (s *Store) UserByUsername(ctx context.Context, username string) (*User, error) {
|
||||
row := s.db.QueryRowContext(ctx,
|
||||
"SELECT id, username, display_name, password_hash, role, active, created_at FROM users WHERE username=? COLLATE NOCASE",
|
||||
strings.TrimSpace(username))
|
||||
user, err := scanUser(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenantIDs, err := s.Memberships(ctx, user.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user.TenantIDs = tenantIDs
|
||||
return user, nil
|
||||
}
|
||||
|
||||
type rowScanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
|
||||
func scanUser(row rowScanner) (*User, error) {
|
||||
var user User
|
||||
var role, created string
|
||||
var active int
|
||||
if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &user.PasswordHash, &role, &active, &created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user.Role = UserRole(role)
|
||||
user.Active = active != 0
|
||||
user.CreatedAt = parseTime(created)
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// HashPassword returns a bcrypt hash suitable for storage.
|
||||
func HashPassword(password string) (string, error) {
|
||||
if len(password) < 6 {
|
||||
return "", errors.New("Das Passwort muss mindestens 6 Zeichen lang sein.")
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(hash), nil
|
||||
}
|
||||
|
||||
// Authenticate validates credentials and returns the active account.
|
||||
func (s *Store) Authenticate(ctx context.Context, username, password string) (*User, error) {
|
||||
user, err := s.UserByUsername(ctx, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, errors.New("Benutzername oder Passwort ist falsch.")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !user.Active {
|
||||
return nil, errors.New("Dieses Konto ist deaktiviert.")
|
||||
}
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil {
|
||||
return nil, errors.New("Benutzername oder Passwort ist falsch.")
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// CreateUser adds an account and its tenant memberships.
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, password string, role UserRole, active bool, tenantIDs []string) (*User, error) {
|
||||
username = strings.TrimSpace(username)
|
||||
displayName = strings.TrimSpace(displayName)
|
||||
if username == "" || displayName == "" {
|
||||
return nil, errors.New("Benutzername und Anzeigename sind erforderlich")
|
||||
}
|
||||
if !role.IsValid() {
|
||||
return nil, errors.New("Unbekannte Rolle")
|
||||
}
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user := &User{
|
||||
ID: domain.NewID(), Username: username, DisplayName: displayName,
|
||||
PasswordHash: hash, Role: role, Active: active, CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
err = s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO users(id, username, display_name, password_hash, role, active, created_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?)`,
|
||||
user.ID, user.Username, user.DisplayName, user.PasswordHash, string(user.Role),
|
||||
boolInt(user.Active), user.CreatedAt.Format(time.RFC3339)); err != nil {
|
||||
return err
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, tenantID := range tenantIDs {
|
||||
if tenantID == "" || seen[tenantID] {
|
||||
continue
|
||||
}
|
||||
seen[tenantID] = true
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"INSERT INTO memberships(user_id, tenant_id) VALUES(?, ?)", user.ID, tenantID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return nil, errors.New("Dieser Benutzername ist bereits vergeben.")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
user.TenantIDs = tenantIDs
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// UpdateUser saves account fields. An empty password keeps the old hash.
|
||||
func (s *Store) UpdateUser(ctx context.Context, id, username, displayName, password string, role UserRole, active bool, tenantIDs []string) error {
|
||||
username = strings.TrimSpace(username)
|
||||
displayName = strings.TrimSpace(displayName)
|
||||
if username == "" || displayName == "" {
|
||||
return errors.New("Benutzername und Anzeigename sind erforderlich")
|
||||
}
|
||||
if !role.IsValid() {
|
||||
return errors.New("Unbekannte Rolle")
|
||||
}
|
||||
return s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
if password != "" {
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"UPDATE users SET username=?, display_name=?, role=?, active=?, password_hash=? WHERE id=?",
|
||||
username, displayName, string(role), boolInt(active), hash, id); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"UPDATE users SET username=?, display_name=?, role=?, active=? WHERE id=?",
|
||||
username, displayName, string(role), boolInt(active), id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM memberships WHERE user_id=?", id); err != nil {
|
||||
return err
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, tenantID := range tenantIDs {
|
||||
if tenantID == "" || seen[tenantID] {
|
||||
continue
|
||||
}
|
||||
seen[tenantID] = true
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"INSERT INTO memberships(user_id, tenant_id) VALUES(?, ?)", id, tenantID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// SetUserPassword updates only the password hash.
|
||||
func (s *Store) SetUserPassword(ctx context.Context, id, password string) error {
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, "UPDATE users SET password_hash=? WHERE id=?", hash, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteUser removes an account and its sessions.
|
||||
func (s *Store) DeleteUser(ctx context.Context, id string) error {
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM users WHERE id=?", id)
|
||||
return err
|
||||
}
|
||||
|
||||
// CountUsers returns the number of accounts.
|
||||
func (s *Store) CountUsers(ctx context.Context) (int, error) {
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM users").Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
// EnsureAdmin creates the first administrator when no account exists.
|
||||
// It returns true when a new account was created.
|
||||
func (s *Store) EnsureAdmin(ctx context.Context, username, password string) (bool, error) {
|
||||
count, err := s.CountUsers(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if count > 0 {
|
||||
return false, nil
|
||||
}
|
||||
if strings.TrimSpace(username) == "" {
|
||||
username = "admin"
|
||||
}
|
||||
if strings.TrimSpace(password) == "" {
|
||||
password = "admin123"
|
||||
}
|
||||
_, err = s.CreateUser(ctx, username, "Administrator", password, RoleAdmin, true, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Session is a server-side login session. The cookie holds the raw token;
|
||||
// only its SHA-256 digest is stored here.
|
||||
type Session struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"userID"`
|
||||
CSRFToken string `json:"-"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
}
|
||||
|
||||
func randomToken(bytes int) (string, error) {
|
||||
buf := make([]byte, bytes)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
func tokenDigest(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// CreateSession starts a login session and returns the raw cookie token.
|
||||
func (s *Store) CreateSession(ctx context.Context, userID string, ttl time.Duration) (*Session, string, error) {
|
||||
token, err := randomToken(32)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
csrf, err := randomToken(32)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
session := &Session{
|
||||
ID: tokenDigest(token), UserID: userID, CSRFToken: csrf,
|
||||
CreatedAt: now, ExpiresAt: now.Add(ttl),
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, `
|
||||
INSERT INTO sessions(id, user_id, csrf_token, created_at, expires_at)
|
||||
VALUES(?, ?, ?, ?, ?)`,
|
||||
session.ID, session.UserID, session.CSRFToken,
|
||||
session.CreatedAt.Format(time.RFC3339), session.ExpiresAt.Format(time.RFC3339))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return session, token, nil
|
||||
}
|
||||
|
||||
// SessionUser resolves a cookie token to its session and account.
|
||||
func (s *Store) SessionUser(ctx context.Context, token string) (*Session, *User, error) {
|
||||
if token == "" {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
var session Session
|
||||
var created, expires string
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
"SELECT id, user_id, csrf_token, created_at, expires_at FROM sessions WHERE id=?",
|
||||
tokenDigest(token)).Scan(&session.ID, &session.UserID, &session.CSRFToken, &created, &expires)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
session.CreatedAt = parseTime(created)
|
||||
session.ExpiresAt = parseTime(expires)
|
||||
if time.Now().UTC().After(session.ExpiresAt) {
|
||||
_ = s.DeleteSession(ctx, session.ID)
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
user, err := s.User(ctx, session.UserID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !user.Active {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
return &session, user, nil
|
||||
}
|
||||
|
||||
// DeleteSession invalidates one session by its stored digest.
|
||||
func (s *Store) DeleteSession(ctx context.Context, id string) error {
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM sessions WHERE id=?", id)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteSessionByToken invalidates a session using the raw cookie token.
|
||||
func (s *Store) DeleteSessionByToken(ctx context.Context, token string) error {
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM sessions WHERE id=?", tokenDigest(token))
|
||||
return err
|
||||
}
|
||||
|
||||
// PurgeExpiredSessions removes stale rows.
|
||||
func (s *Store) PurgeExpiredSessions(ctx context.Context) error {
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM sessions WHERE expires_at < ?", time.Now().UTC().Format(time.RFC3339))
|
||||
return err
|
||||
}
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
// Package store persists tenants, accounts and planning data in SQLite.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
// Common store errors.
|
||||
var (
|
||||
ErrNotFound = errors.New("nicht gefunden")
|
||||
ErrConflict = errors.New("bereits vorhanden")
|
||||
)
|
||||
|
||||
// Store owns the SQLite connection and the application schema.
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
path string
|
||||
}
|
||||
|
||||
// Open creates the database file if needed and applies the schema.
|
||||
func Open(path string) (*Store, error) {
|
||||
dsn := path
|
||||
if path != ":memory:" && !strings.HasPrefix(path, "file:") {
|
||||
dsn = "file:" + path
|
||||
}
|
||||
db, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open database: %w", err)
|
||||
}
|
||||
// A single connection keeps :memory: databases coherent and avoids
|
||||
// writer contention on small installations.
|
||||
db.SetMaxOpenConns(1)
|
||||
db.SetMaxIdleConns(1)
|
||||
db.SetConnMaxLifetime(0)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
pragmas := []string{
|
||||
"PRAGMA foreign_keys = ON",
|
||||
"PRAGMA busy_timeout = 5000",
|
||||
}
|
||||
for _, pragma := range pragmas {
|
||||
if _, err := db.ExecContext(ctx, pragma); err != nil {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("configure database: %w", err)
|
||||
}
|
||||
}
|
||||
if path != ":memory:" && !strings.HasPrefix(path, "file::memory:") {
|
||||
if _, err := db.ExecContext(ctx, "PRAGMA journal_mode = WAL"); err != nil {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("enable WAL: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
store := &Store{db: db, path: path}
|
||||
if err := store.migrate(ctx); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
return store, nil
|
||||
}
|
||||
|
||||
// Close releases the database handle.
|
||||
func (s *Store) Close() error { return s.db.Close() }
|
||||
|
||||
// Path returns the configured database path.
|
||||
func (s *Store) Path() string { return s.path }
|
||||
|
||||
// DB exposes the raw handle for maintenance tasks such as backups.
|
||||
func (s *Store) DB() *sql.DB { return s.db }
|
||||
|
||||
const schema = `
|
||||
CREATE TABLE IF NOT EXISTS schema_meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tenants (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
slug TEXT NOT NULL UNIQUE,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
display_name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS memberships (
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (user_id, tenant_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_memberships_tenant ON memberships(tenant_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
csrf_token TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS churches (
|
||||
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
short_name TEXT NOT NULL,
|
||||
symbol TEXT NOT NULL,
|
||||
color_hex TEXT NOT NULL,
|
||||
address TEXT NOT NULL DEFAULT '',
|
||||
sort_index INTEGER NOT NULL DEFAULT 0,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (tenant_id, id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS people (
|
||||
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
id TEXT NOT NULL,
|
||||
first_name TEXT NOT NULL,
|
||||
last_name TEXT NOT NULL,
|
||||
roles TEXT NOT NULL,
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
phone TEXT NOT NULL DEFAULT '',
|
||||
preferred_church_ids TEXT NOT NULL DEFAULT '[]',
|
||||
preferred_weekdays TEXT NOT NULL DEFAULT '[]',
|
||||
preferred_service_titles TEXT NOT NULL DEFAULT '[]',
|
||||
max_per_month INTEGER NOT NULL DEFAULT 6,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (tenant_id, id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS absences (
|
||||
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
id TEXT NOT NULL,
|
||||
person_id TEXT NOT NULL,
|
||||
start_date TEXT NOT NULL,
|
||||
end_date TEXT NOT NULL,
|
||||
reason TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (tenant_id, id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_absences_person ON absences(tenant_id, person_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS service_templates (
|
||||
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
id TEXT NOT NULL,
|
||||
church_id TEXT NOT NULL,
|
||||
weekday INTEGER NOT NULL,
|
||||
time_minutes INTEGER NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
lectors_needed INTEGER NOT NULL DEFAULT 1,
|
||||
helpers_needed INTEGER NOT NULL DEFAULT 1,
|
||||
valid_from TEXT NOT NULL,
|
||||
valid_to TEXT,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (tenant_id, id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_templates_church ON service_templates(tenant_id, church_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS service_exceptions (
|
||||
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
id TEXT NOT NULL,
|
||||
template_id TEXT NOT NULL,
|
||||
date TEXT NOT NULL,
|
||||
reason TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (tenant_id, id),
|
||||
UNIQUE (tenant_id, template_id, date)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS services (
|
||||
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
id TEXT NOT NULL,
|
||||
church_id TEXT NOT NULL,
|
||||
location TEXT NOT NULL DEFAULT '',
|
||||
template_id TEXT,
|
||||
date TEXT NOT NULL,
|
||||
time_minutes INTEGER NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
lectors_needed INTEGER NOT NULL DEFAULT 1,
|
||||
helpers_needed INTEGER NOT NULL DEFAULT 1,
|
||||
kind TEXT NOT NULL DEFAULT 'regular',
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
locked INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL,
|
||||
PRIMARY KEY (tenant_id, id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_services_date ON services(tenant_id, date);
|
||||
CREATE INDEX IF NOT EXISTS idx_services_church ON services(tenant_id, church_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_services_template_date
|
||||
ON services(tenant_id, template_id, date) WHERE template_id IS NOT NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS assignments (
|
||||
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
id TEXT NOT NULL,
|
||||
service_id TEXT NOT NULL,
|
||||
person_id TEXT NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
locked INTEGER NOT NULL DEFAULT 0,
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
PRIMARY KEY (tenant_id, id),
|
||||
UNIQUE (tenant_id, service_id, person_id, role)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_assignments_service ON assignments(tenant_id, service_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_assignments_person ON assignments(tenant_id, person_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS liturgical_days (
|
||||
date TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
rank TEXT NOT NULL DEFAULT '',
|
||||
color TEXT NOT NULL DEFAULT 'g',
|
||||
remark TEXT NOT NULL DEFAULT '',
|
||||
first_reading TEXT NOT NULL DEFAULT '',
|
||||
psalm TEXT NOT NULL DEFAULT '',
|
||||
second_reading TEXT NOT NULL DEFAULT '',
|
||||
gospel TEXT NOT NULL DEFAULT '',
|
||||
is_obligation INTEGER NOT NULL DEFAULT 0,
|
||||
source TEXT NOT NULL DEFAULT '',
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tenant_settings (
|
||||
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
PRIMARY KEY (tenant_id, key)
|
||||
);
|
||||
`
|
||||
|
||||
func (s *Store) migrate(ctx context.Context) error {
|
||||
if _, err := s.db.ExecContext(ctx, schema); err != nil {
|
||||
return fmt.Errorf("apply schema: %w", err)
|
||||
}
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
"INSERT INTO schema_meta(key, value) VALUES('schemaVersion', '1') "+
|
||||
"ON CONFLICT(key) DO UPDATE SET value=excluded.value"); err != nil {
|
||||
return fmt.Errorf("record schema version: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) transaction(ctx context.Context, fn func(*sql.Tx) error) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := fn(tx); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func nowText() string { return time.Now().UTC().Format(time.RFC3339) }
|
||||
|
||||
func parseTime(value string) time.Time {
|
||||
t, err := time.Parse(time.RFC3339, value)
|
||||
if err != nil {
|
||||
return time.Time{}
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func boolInt(value bool) int {
|
||||
if value {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func nullString(value *string) any {
|
||||
if value == nil || strings.TrimSpace(*value) == "" {
|
||||
return nil
|
||||
}
|
||||
return *value
|
||||
}
|
||||
|
||||
func stringValue(value sql.NullString) string {
|
||||
if value.Valid {
|
||||
return value.String
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func intValue(value sql.NullInt64) int {
|
||||
if value.Valid {
|
||||
return int(value.Int64)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
text := strings.ToLower(err.Error())
|
||||
return strings.Contains(text, "unique constraint") || strings.Contains(text, "constraint failed")
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
"lektorenplan/liturgy"
|
||||
)
|
||||
|
||||
type demoTenantSpec struct {
|
||||
Name string
|
||||
Slug string
|
||||
Notes string
|
||||
Churches []domain.Church
|
||||
People []domain.Person
|
||||
Absences []demoAbsence
|
||||
Templates []demoTemplate
|
||||
Specials []demoSpecial
|
||||
LockEvery int
|
||||
}
|
||||
|
||||
type demoAbsence struct {
|
||||
PersonID string
|
||||
Start string
|
||||
End string
|
||||
Reason string
|
||||
}
|
||||
|
||||
type demoTemplate struct {
|
||||
ID string
|
||||
ChurchID string
|
||||
Weekday int
|
||||
Hour int
|
||||
Minute int
|
||||
Title string
|
||||
Lectors int
|
||||
Helpers int
|
||||
Notes string
|
||||
}
|
||||
|
||||
type demoSpecial struct {
|
||||
ChurchID string
|
||||
Location string
|
||||
Date string
|
||||
Hour int
|
||||
Minute int
|
||||
Title string
|
||||
Lectors int
|
||||
Helpers int
|
||||
Notes string
|
||||
}
|
||||
|
||||
func demoMinute(hour, minute int) int { return hour*60 + minute }
|
||||
|
||||
func badGodesbergSpec() demoTenantSpec {
|
||||
churches := []domain.Church{
|
||||
{ID: "c-andreas", Name: "St. Andreas", ShortName: "Andreas", Symbol: domain.SymbolBasilica,
|
||||
ColorHex: "#9B5B44", Address: "Andreasstraße 1, 53179 Bonn", SortIndex: 0,
|
||||
Notes: "Romanischer Kirchturm, Pfarrkirche im Rheinviertel"},
|
||||
{ID: "c-evergislus", Name: "St. Evergislus", ShortName: "Evergislus", Symbol: domain.SymbolGothic,
|
||||
ColorHex: "#4E6E5D", Address: "Hardtstraße 13, 53175 Bonn", SortIndex: 1,
|
||||
Notes: "Neugotische Kirche in Plittersdorf"},
|
||||
{ID: "c-herzjesu", Name: "Herz Jesu", ShortName: "Herz Jesu", Symbol: domain.SymbolModern,
|
||||
ColorHex: "#7A5A78", Address: "Beethovenallee, 53173 Bonn", SortIndex: 2,
|
||||
Notes: "Kirche im Villenviertel"},
|
||||
{ID: "c-hildegard", Name: "St. Hildegard", ShortName: "Hildegard", Symbol: domain.SymbolRotunda,
|
||||
ColorHex: "#B0833C", Address: "Im Meisengarten, 53179 Bonn", SortIndex: 3,
|
||||
Notes: "Rundkirche der 1960er Jahre in Rüngsdorf"},
|
||||
}
|
||||
|
||||
people := []domain.Person{
|
||||
{ID: "p-anna", FirstName: "Anna", LastName: "Berg", Roles: []domain.Role{domain.RoleLector},
|
||||
Email: "anna.berg@example.org", Phone: "0228 555 0101",
|
||||
PreferredChurchIDs: []string{"c-andreas"}, PreferredWeekdays: []int{1},
|
||||
PreferredServiceTitles: []string{"Hochamt"}, MaxPerMonth: 7, Active: true,
|
||||
Notes: "Liest besonders gerne die Sonntagslesungen."},
|
||||
{ID: "p-markus", FirstName: "Markus", LastName: "Weber", Roles: []domain.Role{domain.RoleLector},
|
||||
Email: "markus.weber@example.org", Phone: "0228 555 0102",
|
||||
PreferredChurchIDs: []string{"c-herzjesu"}, PreferredWeekdays: []int{1, 7},
|
||||
PreferredServiceTitles: []string{"Vorabendmesse"}, MaxPerMonth: 8, Active: true},
|
||||
{ID: "p-elisabeth", FirstName: "Elisabeth", LastName: "Klein",
|
||||
Roles: []domain.Role{domain.RoleLector, domain.RoleHelper},
|
||||
Email: "elisabeth.klein@example.org", Phone: "0228 555 0103",
|
||||
MaxPerMonth: 9, Active: true, Notes: "Flexibel einsetzbar, auch kurzfristig."},
|
||||
{ID: "p-johannes", FirstName: "Johannes", LastName: "Schmitz", Roles: []domain.Role{domain.RoleLector},
|
||||
Email: "johannes.schmitz@example.org", PreferredChurchIDs: []string{"c-evergislus"},
|
||||
PreferredWeekdays: []int{1}, PreferredServiceTitles: []string{"Hochamt"}, MaxPerMonth: 6, Active: true},
|
||||
{ID: "p-maria", FirstName: "Maria", LastName: "Hoffmann", Roles: []domain.Role{domain.RoleHelper},
|
||||
PreferredChurchIDs: []string{"c-herzjesu"}, PreferredWeekdays: []int{1}, MaxPerMonth: 8, Active: true},
|
||||
{ID: "p-peter", FirstName: "Peter", LastName: "Lang", Roles: []domain.Role{domain.RoleHelper},
|
||||
PreferredChurchIDs: []string{"c-hildegard"}, PreferredWeekdays: []int{1}, MaxPerMonth: 6, Active: true},
|
||||
{ID: "p-susanne", FirstName: "Susanne", LastName: "Vogel",
|
||||
Roles: []domain.Role{domain.RoleLector, domain.RoleHelper},
|
||||
PreferredChurchIDs: []string{"c-andreas"}, PreferredWeekdays: []int{1}, MaxPerMonth: 8, Active: true},
|
||||
{ID: "p-thomas", FirstName: "Thomas", LastName: "Neumann", Roles: []domain.Role{domain.RoleLector},
|
||||
MaxPerMonth: 10, Active: true, Notes: "Springerfunktion."},
|
||||
{ID: "p-claudia", FirstName: "Claudia", LastName: "Roth", Roles: []domain.Role{domain.RoleHelper},
|
||||
PreferredChurchIDs: []string{"c-evergislus"}, PreferredWeekdays: []int{1, 4}, MaxPerMonth: 7, Active: true},
|
||||
{ID: "p-michael", FirstName: "Michael", LastName: "Braun", Roles: []domain.Role{domain.RoleHelper},
|
||||
PreferredChurchIDs: []string{"c-andreas"}, PreferredWeekdays: []int{1}, MaxPerMonth: 8, Active: true},
|
||||
{ID: "p-julia", FirstName: "Julia", LastName: "Schröder",
|
||||
Roles: []domain.Role{domain.RoleLector, domain.RoleHelper},
|
||||
PreferredChurchIDs: []string{"c-herzjesu", "c-hildegard"}, PreferredWeekdays: []int{1, 7}, MaxPerMonth: 8, Active: true},
|
||||
{ID: "p-andreas", FirstName: "Andreas", LastName: "Wolff", Roles: []domain.Role{domain.RoleLector},
|
||||
PreferredChurchIDs: []string{"c-hildegard"}, PreferredWeekdays: []int{1},
|
||||
PreferredServiceTitles: []string{"Wort-Gottes-Feier"}, MaxPerMonth: 6, Active: true},
|
||||
{ID: "p-birgit", FirstName: "Birgit", LastName: "Sauer", Roles: []domain.Role{domain.RoleHelper},
|
||||
MaxPerMonth: 9, Active: true},
|
||||
{ID: "p-daniel", FirstName: "Daniel", LastName: "Krüger", Roles: []domain.Role{domain.RoleLector},
|
||||
PreferredChurchIDs: []string{"c-herzjesu", "c-andreas"}, PreferredWeekdays: []int{1, 2, 5}, MaxPerMonth: 7, Active: true},
|
||||
{ID: "p-petra", FirstName: "Petra", LastName: "Sommer", Roles: []domain.Role{domain.RoleHelper},
|
||||
PreferredChurchIDs: []string{"c-evergislus", "c-hildegard"}, PreferredWeekdays: []int{1, 7}, MaxPerMonth: 7, Active: true},
|
||||
{ID: "p-stefan", FirstName: "Stefan", LastName: "Haas",
|
||||
Roles: []domain.Role{domain.RoleLector, domain.RoleHelper}, MaxPerMonth: 9, Active: true},
|
||||
{ID: "p-monika", FirstName: "Monika", LastName: "Albrecht", Roles: []domain.Role{domain.RoleHelper},
|
||||
PreferredChurchIDs: []string{"c-andreas"}, PreferredWeekdays: []int{1, 3}, MaxPerMonth: 6, Active: true},
|
||||
{ID: "p-christoph", FirstName: "Christoph", LastName: "Mertens", Roles: []domain.Role{domain.RoleLector},
|
||||
PreferredChurchIDs: []string{"c-evergislus"}, PreferredWeekdays: []int{1, 7},
|
||||
PreferredServiceTitles: []string{"Vorabendmesse"}, MaxPerMonth: 7, Active: true},
|
||||
{ID: "p-simone", FirstName: "Simone", LastName: "Becker", Roles: []domain.Role{domain.RoleHelper},
|
||||
MaxPerMonth: 8, Active: true},
|
||||
{ID: "p-martin", FirstName: "Martin", LastName: "Fuchs", Roles: []domain.Role{domain.RoleLector},
|
||||
PreferredWeekdays: []int{1, 3}, MaxPerMonth: 7, Active: true},
|
||||
{ID: "p-ursula", FirstName: "Ursula", LastName: "Peters", Roles: []domain.Role{domain.RoleHelper},
|
||||
PreferredWeekdays: []int{3, 4, 5}, MaxPerMonth: 8, Active: true, Notes: "Werktagsmessen."},
|
||||
{ID: "p-frank", FirstName: "Frank", LastName: "Lorenz", Roles: []domain.Role{domain.RoleLector},
|
||||
PreferredWeekdays: []int{2, 3, 5}, MaxPerMonth: 8, Active: true, Notes: "Werktagsmessen."},
|
||||
}
|
||||
|
||||
absences := []demoAbsence{
|
||||
{"p-anna", "2026-12-20", "2027-01-06", "Weihnachtsreise"},
|
||||
{"p-markus", "2026-11-10", "2026-11-24", "Kur"},
|
||||
{"p-maria", "2027-03-01", "2027-03-15", "Fortbildung"},
|
||||
{"p-peter", "2026-12-24", "2026-12-26", "Familie"},
|
||||
{"p-susanne", "2026-08-01", "2026-08-21", "Urlaub"},
|
||||
{"p-michael", "2026-11-01", "2026-11-08", "Urlaub"},
|
||||
{"p-julia", "2027-05-01", "2027-05-14", "Urlaub"},
|
||||
{"p-birgit", "2026-11-15", "2026-11-22", "Dienstreise"},
|
||||
{"p-daniel", "2026-12-01", "2026-12-12", "Umzug"},
|
||||
{"p-petra", "2027-02-01", "2027-02-14", "Winterurlaub"},
|
||||
{"p-thomas", "2027-04-01", "2027-04-20", "Reha"},
|
||||
{"p-simone", "2026-12-24", "2027-01-02", "Familienbesuch"},
|
||||
{"p-ursula", "2026-09-07", "2026-09-20", "Urlaub"},
|
||||
{"p-frank", "2026-11-23", "2026-12-04", "Kur"},
|
||||
}
|
||||
|
||||
templates := []demoTemplate{
|
||||
{"t-andreas-so-hl", "c-andreas", 1, 9, 30, "Hochamt", 1, 2, "Sonntägliches Hochamt"},
|
||||
{"t-andreas-so-ab", "c-andreas", 1, 18, 0, "Abendmesse", 1, 1, ""},
|
||||
{"t-andreas-mi", "c-andreas", 4, 8, 30, "Werktagsmesse", 1, 1, ""},
|
||||
{"t-evergislus-sa", "c-evergislus", 7, 18, 0, "Vorabendmesse", 1, 1, "Samstagabend"},
|
||||
{"t-evergislus-so", "c-evergislus", 1, 11, 0, "Hochamt", 1, 2, ""},
|
||||
{"t-evergislus-do", "c-evergislus", 5, 8, 30, "Werktagsmesse", 1, 1, ""},
|
||||
{"t-herzjesu-sa", "c-herzjesu", 7, 17, 0, "Vorabendmesse", 1, 1, ""},
|
||||
{"t-herzjesu-so", "c-herzjesu", 1, 10, 0, "Hochamt", 1, 2, ""},
|
||||
{"t-herzjesu-di", "c-herzjesu", 3, 18, 0, "Werktagsmesse", 1, 1, ""},
|
||||
{"t-herzjesu-fr", "c-herzjesu", 6, 8, 30, "Werktagsmesse", 1, 1, ""},
|
||||
{"t-hildegard-so", "c-hildegard", 1, 9, 0, "Messe", 1, 1, ""},
|
||||
{"t-hildegard-wgf", "c-hildegard", 1, 11, 30, "Wort-Gottes-Feier", 1, 0, "Lektorat, keine Kommunionspendung"},
|
||||
{"t-hildegard-mi", "c-hildegard", 4, 18, 30, "Werktagsmesse", 1, 1, ""},
|
||||
}
|
||||
|
||||
specials := []demoSpecial{
|
||||
{"c-andreas", "", "2025-12-24", 16, 0, "Familienchristmette", 1, 1, "Kinder- und Familienchristmette mit Krippenspiel"},
|
||||
{"c-herzjesu", "", "2025-12-24", 22, 0, "Christmette", 1, 2, ""},
|
||||
{"c-evergislus", "", "2025-04-19", 21, 0, "Osternacht", 1, 1, "Hochfest der Auferstehung, Lichterfeier"},
|
||||
{"c-andreas", "", "2026-04-04", 21, 0, "Osternacht", 1, 1, "Lichterfeier mit Taufgedächtnis"},
|
||||
{"c-andreas", "", "2026-11-30", 18, 0, "Patronatsfest St. Andreas", 1, 1, "Hochfest des heiligen Andreas"},
|
||||
{"c-herzjesu", "Open-Air auf dem Theaterplatz", "2026-06-04", 10, 0, "Fronleichnamsmesse", 1, 2, "Gemeinsame Messfeier der Pfarreiengemeinschaft im Freien"},
|
||||
{"c-andreas", "", "2026-12-24", 16, 0, "Familienchristmette", 1, 1, "Kinder- und Familienchristmette"},
|
||||
{"c-herzjesu", "", "2026-12-24", 22, 0, "Christmette", 1, 2, ""},
|
||||
{"c-evergislus", "", "2027-03-27", 21, 0, "Osternacht", 1, 1, ""},
|
||||
{"c-herzjesu", "", "2027-06-04", 10, 0, "Fronleichnamsprozession", 1, 2, "Gemeinsame Prozession der Pfarrgemeinschaft"},
|
||||
{"c-andreas", "", "2027-12-24", 16, 0, "Familienchristmette", 1, 1, ""},
|
||||
{"c-herzjesu", "", "2027-12-24", 22, 0, "Christmette", 1, 2, ""},
|
||||
}
|
||||
|
||||
return demoTenantSpec{
|
||||
Name: "Bad Godesberg", Slug: "bad-godesberg",
|
||||
Notes: "Pfarreiengemeinschaft im Rheinviertel – Demo-Datensatz.",
|
||||
Churches: churches, People: people, Absences: absences,
|
||||
Templates: templates, Specials: specials, LockEvery: 41,
|
||||
}
|
||||
}
|
||||
|
||||
func rheinaueSpec() demoTenantSpec {
|
||||
churches := []domain.Church{
|
||||
{ID: "c-marien", Name: "St. Marien", ShortName: "Marien", Symbol: domain.SymbolGothic,
|
||||
ColorHex: "#7A5A78", Address: "Rheinallee 4, 53424 Remagen", SortIndex: 0,
|
||||
Notes: "Neugotische Pfarrkirche am Rhein"},
|
||||
{ID: "c-kreuz", Name: "Heilig Kreuz", ShortName: "Kreuz", Symbol: domain.SymbolModern,
|
||||
ColorHex: "#4F7D5A", Address: "Kreuzweg 12, 53424 Remagen", SortIndex: 1,
|
||||
Notes: "Moderner Gemeindesaal mit Kapelle"},
|
||||
{ID: "c-elisabeth", Name: "St. Elisabeth", ShortName: "Elisabeth", Symbol: domain.SymbolChapel,
|
||||
ColorHex: "#B0833C", Address: "Lindenstraße 8, 53424 Remagen", SortIndex: 2,
|
||||
Notes: "Kleine Kapelle im Ortsteil"},
|
||||
}
|
||||
|
||||
people := []domain.Person{
|
||||
{ID: "r-clara", FirstName: "Clara", LastName: "Winter", Roles: []domain.Role{domain.RoleLector},
|
||||
Email: "clara.winter@example.org", PreferredChurchIDs: []string{"c-marien"},
|
||||
PreferredWeekdays: []int{1}, PreferredServiceTitles: []string{"Hochamt"}, MaxPerMonth: 7, Active: true},
|
||||
{ID: "r-bernd", FirstName: "Bernd", LastName: "Kaiser", Roles: []domain.Role{domain.RoleHelper},
|
||||
Email: "bernd.kaiser@example.org", PreferredChurchIDs: []string{"c-kreuz"},
|
||||
PreferredWeekdays: []int{1}, MaxPerMonth: 8, Active: true},
|
||||
{ID: "r-nina", FirstName: "Nina", LastName: "Sommer", Roles: []domain.Role{domain.RoleLector, domain.RoleHelper},
|
||||
PreferredWeekdays: []int{1, 7}, MaxPerMonth: 8, Active: true},
|
||||
{ID: "r-heinz", FirstName: "Heinz", LastName: "Vogt", Roles: []domain.Role{domain.RoleLector},
|
||||
PreferredChurchIDs: []string{"c-elisabeth"}, PreferredWeekdays: []int{1, 4},
|
||||
PreferredServiceTitles: []string{"Wort-Gottes-Feier"}, MaxPerMonth: 6, Active: true},
|
||||
{ID: "r-ines", FirstName: "Ines", LastName: "Kraus", Roles: []domain.Role{domain.RoleHelper},
|
||||
PreferredChurchIDs: []string{"c-marien"}, PreferredWeekdays: []int{1, 6}, MaxPerMonth: 8, Active: true},
|
||||
{ID: "r-oliver", FirstName: "Oliver", LastName: "Brandt", Roles: []domain.Role{domain.RoleLector},
|
||||
PreferredWeekdays: []int{1, 3, 5}, MaxPerMonth: 8, Active: true},
|
||||
{ID: "r-gabi", FirstName: "Gabriele", LastName: "Meyer", Roles: []domain.Role{domain.RoleHelper},
|
||||
PreferredWeekdays: []int{3, 4}, MaxPerMonth: 7, Active: true, Notes: "Werktagsmessen."},
|
||||
{ID: "r-tobias", FirstName: "Tobias", LastName: "Ritter", Roles: []domain.Role{domain.RoleLector, domain.RoleHelper},
|
||||
PreferredChurchIDs: []string{"c-kreuz"}, PreferredWeekdays: []int{1, 7}, MaxPerMonth: 9, Active: true},
|
||||
{ID: "r-sabine", FirstName: "Sabine", LastName: "Lenz", Roles: []domain.Role{domain.RoleHelper},
|
||||
PreferredChurchIDs: []string{"c-elisabeth"}, PreferredWeekdays: []int{1}, MaxPerMonth: 6, Active: true},
|
||||
{ID: "r-klaus", FirstName: "Klaus", LastName: "Hofmann", Roles: []domain.Role{domain.RoleLector},
|
||||
MaxPerMonth: 10, Active: true, Notes: "Springerfunktion."},
|
||||
{ID: "r-ute", FirstName: "Ute", LastName: "Schwarz", Roles: []domain.Role{domain.RoleHelper},
|
||||
MaxPerMonth: 8, Active: true},
|
||||
{ID: "r-ralf", FirstName: "Ralf", LastName: "Dietrich", Roles: []domain.Role{domain.RoleLector},
|
||||
PreferredWeekdays: []int{2, 6}, MaxPerMonth: 7, Active: true},
|
||||
}
|
||||
|
||||
absences := []demoAbsence{
|
||||
{"r-clara", "2026-12-22", "2027-01-03", "Weihnachtsurlaub"},
|
||||
{"r-bernd", "2026-11-15", "2026-11-28", "Kur"},
|
||||
{"r-nina", "2027-02-01", "2027-02-14", "Winterurlaub"},
|
||||
{"r-heinz", "2026-10-05", "2026-10-18", "Reise"},
|
||||
{"r-ines", "2026-12-24", "2026-12-26", "Familie"},
|
||||
{"r-oliver", "2027-04-01", "2027-04-12", "Fortbildung"},
|
||||
{"r-tobias", "2026-08-03", "2026-08-21", "Urlaub"},
|
||||
{"r-sabine", "2027-05-01", "2027-05-10", "Urlaub"},
|
||||
}
|
||||
|
||||
templates := []demoTemplate{
|
||||
{"t-marien-sa", "c-marien", 7, 18, 0, "Vorabendmesse", 1, 1, "Samstagabend"},
|
||||
{"t-marien-so", "c-marien", 1, 10, 0, "Hochamt", 1, 2, "Sonntägliches Hochamt"},
|
||||
{"t-kreuz-so", "c-kreuz", 1, 9, 0, "Messe", 1, 1, ""},
|
||||
{"t-kreuz-mi", "c-kreuz", 4, 18, 30, "Werktagsmesse", 1, 0, "Lektorat, keine Kommunionspendung"},
|
||||
{"t-elisabeth-so", "c-elisabeth", 1, 11, 30, "Wort-Gottes-Feier", 1, 0, ""},
|
||||
{"t-elisabeth-do", "c-elisabeth", 5, 8, 30, "Werktagsmesse", 1, 1, ""},
|
||||
}
|
||||
|
||||
specials := []demoSpecial{
|
||||
{"c-marien", "", "2026-06-04", 10, 0, "Fronleichnamsmesse", 1, 2, "Gemeinsame Messfeier im Freien"},
|
||||
{"c-marien", "", "2026-12-24", 17, 0, "Familienchristmette", 1, 1, ""},
|
||||
{"c-kreuz", "", "2026-12-24", 22, 0, "Christmette", 1, 2, ""},
|
||||
{"c-marien", "", "2027-03-27", 21, 0, "Osternacht", 1, 1, "Lichterfeier"},
|
||||
}
|
||||
|
||||
return demoTenantSpec{
|
||||
Name: "Rheinaue (Demo)", Slug: "rheinaue",
|
||||
Notes: "Zweiter Mandant zur Demonstration der Mandantentrennung.",
|
||||
Churches: churches, People: people, Absences: absences,
|
||||
Templates: templates, Specials: specials, LockEvery: 29,
|
||||
}
|
||||
}
|
||||
|
||||
// SeedDemo creates two demonstration tenants on a fresh database and ensures
|
||||
// the documented demo accounts exist.
|
||||
func (s *Store) SeedDemo(ctx context.Context) error {
|
||||
if err := s.seedLiturgicalSnapshot(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
specs := []demoTenantSpec{badGodesbergSpec(), rheinaueSpec()}
|
||||
tenantIDs := map[string]string{}
|
||||
for _, spec := range specs {
|
||||
tenant, err := s.TenantBySlug(ctx, spec.Slug)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
tenant, err = s.CreateTenant(ctx, spec.Name, spec.Slug, spec.Notes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Mandant %s: %w", spec.Name, err)
|
||||
}
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
tenantIDs[spec.Slug] = tenant.ID
|
||||
|
||||
count, err := s.CountChurches(ctx, tenant.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
continue
|
||||
}
|
||||
if err := s.seedTenant(ctx, tenant.ID, spec); err != nil {
|
||||
return fmt.Errorf("Demo-Daten für %s: %w", spec.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.ensureDemoUsers(ctx, tenantIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_ = s.SetSetting(ctx, "diocese", "koeln")
|
||||
if s.Setting(ctx, "autoSyncLiturgy") == "" {
|
||||
_ = s.SetSetting(ctx, "autoSyncLiturgy", "1")
|
||||
}
|
||||
_ = s.SetSetting(ctx, "demoSeededAt", time.Now().UTC().Format(time.RFC3339))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) seedLiturgicalSnapshot(ctx context.Context) error {
|
||||
count, err := s.LiturgicalDayCount(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
return nil
|
||||
}
|
||||
days := liturgy.SnapshotDays()
|
||||
if len(days) == 0 {
|
||||
return errors.New("liturgischer Schnappschuss konnte nicht gelesen werden")
|
||||
}
|
||||
return s.UpsertLiturgicalDays(ctx, days)
|
||||
}
|
||||
|
||||
func (s *Store) ensureDemoUsers(ctx context.Context, tenantIDs map[string]string) error {
|
||||
if _, err := s.EnsureAdmin(ctx, "admin", "admin123"); err != nil {
|
||||
return err
|
||||
}
|
||||
accounts := []struct {
|
||||
Username string
|
||||
DisplayName string
|
||||
Password string
|
||||
Role UserRole
|
||||
Tenants []string
|
||||
}{
|
||||
{"editor", "Elisabeth Redaktion", "editor123", RoleEditor,
|
||||
[]string{tenantIDs["bad-godesberg"], tenantIDs["rheinaue"]}},
|
||||
{"reader", "Rainer Lesezugriff", "reader123", RoleReader,
|
||||
[]string{tenantIDs["bad-godesberg"]}},
|
||||
}
|
||||
for _, account := range accounts {
|
||||
_, err := s.UserByUsername(ctx, account.Username)
|
||||
if err == nil {
|
||||
continue
|
||||
}
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
if _, err := s.CreateUser(ctx, account.Username, account.DisplayName, account.Password,
|
||||
account.Role, true, account.Tenants); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) seedTenant(ctx context.Context, tenantID string, spec demoTenantSpec) error {
|
||||
for _, church := range spec.Churches {
|
||||
if err := s.UpsertChurch(ctx, tenantID, church); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, person := range spec.People {
|
||||
if err := s.UpsertPerson(ctx, tenantID, person); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, absence := range spec.Absences {
|
||||
if err := s.UpsertAbsence(ctx, tenantID, domain.Absence{
|
||||
ID: domain.NewID(),
|
||||
PersonID: absence.PersonID,
|
||||
Start: domain.MustDate(absence.Start),
|
||||
End: domain.MustDate(absence.End),
|
||||
Reason: absence.Reason,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
validFrom := domain.MustDate("2024-01-01")
|
||||
for _, template := range spec.Templates {
|
||||
if err := s.UpsertTemplate(ctx, tenantID, domain.ServiceTemplate{
|
||||
ID: template.ID, ChurchID: template.ChurchID, Weekday: template.Weekday,
|
||||
TimeMinutes: demoMinute(template.Hour, template.Minute), Title: template.Title,
|
||||
LectorsNeeded: template.Lectors, HelpersNeeded: template.Helpers,
|
||||
ValidFrom: validFrom, Active: true, Notes: template.Notes,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.seedExceptions(ctx, tenantID, spec); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for year := 2025; year <= 2028; year++ {
|
||||
if _, err := s.GenerateServices(ctx, tenantID, domain.YearRange(year), true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, special := range spec.Specials {
|
||||
location := special.Location
|
||||
var locationPtr *string
|
||||
if location != "" {
|
||||
locationPtr = &location
|
||||
}
|
||||
if _, err := s.UpsertService(ctx, tenantID, domain.ServiceOccurrence{
|
||||
ChurchID: special.ChurchID, Location: locationPtr,
|
||||
Date: domain.MustDate(special.Date),
|
||||
TimeMinutes: demoMinute(special.Hour, special.Minute),
|
||||
Title: special.Title, LectorsNeeded: special.Lectors,
|
||||
HelpersNeeded: special.Helpers, Kind: domain.KindSpecial,
|
||||
Notes: special.Notes, CreatedAt: time.Now().UTC(),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return s.seedHistory(ctx, tenantID, spec)
|
||||
}
|
||||
|
||||
func (s *Store) seedExceptions(ctx context.Context, tenantID string, spec demoTenantSpec) error {
|
||||
goodFridays := []string{"2025-04-18", "2026-04-03", "2027-03-26"}
|
||||
christmasEves := []string{"2025-12-24", "2027-12-24"}
|
||||
holySaturdays := []string{"2025-04-19", "2026-04-04", "2027-03-27"}
|
||||
byID := map[string]demoTemplate{}
|
||||
for _, template := range spec.Templates {
|
||||
byID[template.ID] = template
|
||||
}
|
||||
for _, template := range spec.Templates {
|
||||
if template.Weekday == 6 && template.ChurchID == "c-herzjesu" {
|
||||
for _, key := range goodFridays {
|
||||
if err := s.UpsertException(ctx, tenantID, domain.ServiceException{
|
||||
ID: domain.NewID(), TemplateID: template.ID,
|
||||
Date: domain.MustDate(key), Reason: "Karfreitag – keine Werktagsmesse",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if template.Weekday == 4 {
|
||||
for _, key := range christmasEves {
|
||||
if err := s.UpsertException(ctx, tenantID, domain.ServiceException{
|
||||
ID: domain.NewID(), TemplateID: template.ID,
|
||||
Date: domain.MustDate(key), Reason: "Heiliger Abend",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, ok := byID["t-evergislus-sa"]; ok {
|
||||
for _, key := range holySaturdays {
|
||||
if err := s.UpsertException(ctx, tenantID, domain.ServiceException{
|
||||
ID: domain.NewID(), TemplateID: "t-evergislus-sa",
|
||||
Date: domain.MustDate(key), Reason: "Osternacht",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) seedHistory(ctx context.Context, tenantID string, spec demoTenantSpec) error {
|
||||
today := domain.Today()
|
||||
start := domain.MustDate("2025-01-01")
|
||||
end := domain.AddingDays(-1, today)
|
||||
if end.Before(start) {
|
||||
return nil
|
||||
}
|
||||
past := domain.NewDayRange(start, end)
|
||||
services, err := s.Services(ctx, tenantID, past)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(services) == 0 {
|
||||
return nil
|
||||
}
|
||||
people, err := s.People(ctx, tenantID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
absences, err := s.Absences(ctx, tenantID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
churches, err := s.Churches(ctx, tenantID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
planner := domain.ServicePlanner{
|
||||
People: people, Absences: absences, Services: services,
|
||||
Churches: churches, Options: domain.PlannerOptions{
|
||||
ReplaceExisting: true, RespectPreferredWeekdays: true,
|
||||
WeightChurchPreference: 8, WeightServicePreference: 4,
|
||||
WeightFairness: 2.4, WeightDualRolePreference: 14,
|
||||
MaxAssignmentsPerDay: 1,
|
||||
},
|
||||
}
|
||||
result := planner.Plan()
|
||||
if err := s.SavePlan(ctx, tenantID, result.Assignments, past, true); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
assignments, err := s.Assignments(ctx, tenantID, past)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range assignments {
|
||||
if spec.LockEvery > 0 && i%spec.LockEvery == 0 {
|
||||
assignments[i].Locked = true
|
||||
if err := s.UpsertAssignment(ctx, tenantID, assignments[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
// ExchangeScope selects what an exchange file contains.
|
||||
type ExchangeScope string
|
||||
|
||||
const (
|
||||
ScopeResources ExchangeScope = "resources"
|
||||
ScopePlan ExchangeScope = "plan"
|
||||
)
|
||||
|
||||
func (s ExchangeScope) Title() string {
|
||||
if s == ScopeResources {
|
||||
return "Ressourcen"
|
||||
}
|
||||
return "Planungsabschnitt"
|
||||
}
|
||||
|
||||
// ExchangeRange is a serialisable inclusive day range.
|
||||
type ExchangeRange struct {
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
}
|
||||
|
||||
// ResourceBundle carries configuration and volunteer data.
|
||||
type ResourceBundle struct {
|
||||
Churches []domain.Church `json:"churches"`
|
||||
People []domain.Person `json:"people"`
|
||||
Absences []domain.Absence `json:"absences"`
|
||||
Templates []domain.ServiceTemplate `json:"templates"`
|
||||
Exceptions []domain.ServiceException `json:"exceptions"`
|
||||
}
|
||||
|
||||
// PlanExchange is the JSON document exchanged with other installations.
|
||||
type PlanExchange struct {
|
||||
FormatVersion int `json:"formatVersion"`
|
||||
ExportedAt time.Time `json:"exportedAt"`
|
||||
AppName string `json:"appName"`
|
||||
Scope ExchangeScope `json:"scope"`
|
||||
Range ExchangeRange `json:"range"`
|
||||
Resources ResourceBundle `json:"resources"`
|
||||
Services []domain.ServiceOccurrence `json:"services"`
|
||||
Assignments []domain.Assignment `json:"assignments"`
|
||||
LiturgicalDays []domain.LiturgicalDay `json:"liturgicalDays"`
|
||||
Note string `json:"note"`
|
||||
}
|
||||
|
||||
// ExchangeSummary reports the imported record counts.
|
||||
type ExchangeSummary struct {
|
||||
Scope ExchangeScope `json:"scope"`
|
||||
Range ExchangeRange `json:"range"`
|
||||
Churches int `json:"churches"`
|
||||
People int `json:"people"`
|
||||
Templates int `json:"templates"`
|
||||
Services int `json:"services"`
|
||||
Assignments int `json:"assignments"`
|
||||
LiturgicalDays int `json:"liturgicalDays"`
|
||||
}
|
||||
|
||||
// Summary returns counts for display after import or before export.
|
||||
func (e PlanExchange) Summary() ExchangeSummary {
|
||||
return ExchangeSummary{
|
||||
Scope: e.Scope, Range: e.Range,
|
||||
Churches: len(e.Resources.Churches), People: len(e.Resources.People),
|
||||
Templates: len(e.Resources.Templates), Services: len(e.Services),
|
||||
Assignments: len(e.Assignments), LiturgicalDays: len(e.LiturgicalDays),
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalJSON indents the exchange document for readability.
|
||||
func (e PlanExchange) MarshalJSON() ([]byte, error) {
|
||||
type alias PlanExchange
|
||||
return json.MarshalIndent(alias(e), "", " ")
|
||||
}
|
||||
|
||||
// ExportResources builds a resources-only exchange document.
|
||||
func (s *Store) ExportResources(ctx context.Context, tenantID string) (PlanExchange, error) {
|
||||
churches, err := s.Churches(ctx, tenantID)
|
||||
if err != nil {
|
||||
return PlanExchange{}, err
|
||||
}
|
||||
people, err := s.People(ctx, tenantID)
|
||||
if err != nil {
|
||||
return PlanExchange{}, err
|
||||
}
|
||||
absences, err := s.Absences(ctx, tenantID)
|
||||
if err != nil {
|
||||
return PlanExchange{}, err
|
||||
}
|
||||
templates, err := s.Templates(ctx, tenantID)
|
||||
if err != nil {
|
||||
return PlanExchange{}, err
|
||||
}
|
||||
exceptions, err := s.Exceptions(ctx, tenantID)
|
||||
if err != nil {
|
||||
return PlanExchange{}, err
|
||||
}
|
||||
return PlanExchange{
|
||||
FormatVersion: 1, ExportedAt: time.Now().UTC(), AppName: "LektorenPlan Web",
|
||||
Scope: ScopeResources,
|
||||
Resources: ResourceBundle{
|
||||
Churches: churches, People: people, Absences: absences,
|
||||
Templates: templates, Exceptions: exceptions,
|
||||
},
|
||||
Note: "Export aus LektorenPlan Web",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ExportPlan builds a plan exchange document for a range.
|
||||
func (s *Store) ExportPlan(ctx context.Context, tenantID string, r domain.DayRange) (PlanExchange, error) {
|
||||
resources, err := s.ExportResources(ctx, tenantID)
|
||||
if err != nil {
|
||||
return PlanExchange{}, err
|
||||
}
|
||||
services, err := s.Services(ctx, tenantID, r)
|
||||
if err != nil {
|
||||
return PlanExchange{}, err
|
||||
}
|
||||
serviceIDs := make([]string, len(services))
|
||||
for i, service := range services {
|
||||
serviceIDs[i] = service.ID
|
||||
}
|
||||
assignments, err := s.AssignmentsForServices(ctx, tenantID, serviceIDs)
|
||||
if err != nil {
|
||||
return PlanExchange{}, err
|
||||
}
|
||||
liturgicalDays, err := s.LiturgicalDays(ctx, r)
|
||||
if err != nil {
|
||||
return PlanExchange{}, err
|
||||
}
|
||||
personIDs := map[string]bool{}
|
||||
for _, assignment := range assignments {
|
||||
personIDs[assignment.PersonID] = true
|
||||
}
|
||||
var relevantPeople []domain.Person
|
||||
for _, person := range resources.Resources.People {
|
||||
if personIDs[person.ID] {
|
||||
relevantPeople = append(relevantPeople, person)
|
||||
}
|
||||
}
|
||||
var relevantAbsences []domain.Absence
|
||||
for _, absence := range resources.Resources.Absences {
|
||||
if personIDs[absence.PersonID] {
|
||||
relevantAbsences = append(relevantAbsences, absence)
|
||||
}
|
||||
}
|
||||
resources.Resources.People = relevantPeople
|
||||
resources.Resources.Absences = relevantAbsences
|
||||
return PlanExchange{
|
||||
FormatVersion: 1, ExportedAt: time.Now().UTC(), AppName: "LektorenPlan Web",
|
||||
Scope: ScopePlan,
|
||||
Range: ExchangeRange{Start: domain.Key(r.Start), End: domain.Key(r.End)},
|
||||
Resources: resources.Resources, Services: services, Assignments: assignments,
|
||||
LiturgicalDays: liturgicalDays,
|
||||
Note: fmt.Sprintf("Export aus LektorenPlan Web · %s bis %s",
|
||||
domain.Key(r.Start), domain.Key(r.End)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ParseExchange decodes an uploaded JSON document.
|
||||
func ParseExchange(data []byte) (PlanExchange, error) {
|
||||
var exchange PlanExchange
|
||||
if err := json.Unmarshal(data, &exchange); err != nil {
|
||||
return exchange, fmt.Errorf("Die Datei konnte nicht gelesen werden: %w", err)
|
||||
}
|
||||
if exchange.FormatVersion < 1 {
|
||||
exchange.FormatVersion = 1
|
||||
}
|
||||
if exchange.Scope == "" {
|
||||
exchange.Scope = ScopePlan
|
||||
}
|
||||
if exchange.Scope != ScopeResources && exchange.Scope != ScopePlan {
|
||||
return exchange, errors.New("Unbekannter Dateityp")
|
||||
}
|
||||
return exchange, nil
|
||||
}
|
||||
|
||||
// ApplyExchange imports resources, services and assignments into a tenant.
|
||||
func (s *Store) ApplyExchange(ctx context.Context, tenantID string, exchange PlanExchange, replaceExisting bool) (ExchangeSummary, error) {
|
||||
if replaceExisting {
|
||||
if err := s.DeleteAllTenantData(ctx, tenantID); err != nil {
|
||||
return ExchangeSummary{}, err
|
||||
}
|
||||
}
|
||||
// Use the store methods so validation and secondary cleanup stay in one place.
|
||||
for _, church := range exchange.Resources.Churches {
|
||||
if err := s.UpsertChurch(ctx, tenantID, church); err != nil {
|
||||
return ExchangeSummary{}, err
|
||||
}
|
||||
}
|
||||
for _, person := range exchange.Resources.People {
|
||||
if err := s.UpsertPerson(ctx, tenantID, person); err != nil {
|
||||
return ExchangeSummary{}, err
|
||||
}
|
||||
}
|
||||
for _, absence := range exchange.Resources.Absences {
|
||||
if err := s.UpsertAbsence(ctx, tenantID, absence); err != nil {
|
||||
return ExchangeSummary{}, err
|
||||
}
|
||||
}
|
||||
for _, template := range exchange.Resources.Templates {
|
||||
if err := s.UpsertTemplate(ctx, tenantID, template); err != nil {
|
||||
return ExchangeSummary{}, err
|
||||
}
|
||||
}
|
||||
for _, exception := range exchange.Resources.Exceptions {
|
||||
if err := s.UpsertException(ctx, tenantID, exception); err != nil {
|
||||
return ExchangeSummary{}, err
|
||||
}
|
||||
}
|
||||
if len(exchange.LiturgicalDays) > 0 {
|
||||
if err := s.UpsertLiturgicalDays(ctx, exchange.LiturgicalDays); err != nil {
|
||||
return ExchangeSummary{}, err
|
||||
}
|
||||
}
|
||||
for _, service := range exchange.Services {
|
||||
if _, err := s.UpsertService(ctx, tenantID, service); err != nil {
|
||||
return ExchangeSummary{}, err
|
||||
}
|
||||
}
|
||||
for _, assignment := range exchange.Assignments {
|
||||
if err := s.UpsertAssignment(ctx, tenantID, assignment); err != nil {
|
||||
if errors.Is(err, ErrConflict) {
|
||||
continue
|
||||
}
|
||||
return ExchangeSummary{}, err
|
||||
}
|
||||
}
|
||||
return exchange.Summary(), nil
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
// LiturgicalDays returns persisted calendar days inside a range.
|
||||
func (s *Store) LiturgicalDays(ctx context.Context, r domain.DayRange) ([]domain.LiturgicalDay, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT date, title, rank, color, remark, first_reading, psalm, second_reading,
|
||||
gospel, is_obligation, source, updated_at
|
||||
FROM liturgical_days WHERE date >= ? AND date <= ? ORDER BY date`,
|
||||
domain.Key(r.Start), domain.Key(r.End))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []domain.LiturgicalDay
|
||||
for rows.Next() {
|
||||
day, err := scanLiturgicalDay(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, *day)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// LiturgicalDay loads one calendar day.
|
||||
func (s *Store) LiturgicalDay(ctx context.Context, date time.Time) (*domain.LiturgicalDay, error) {
|
||||
row := s.db.QueryRowContext(ctx, `
|
||||
SELECT date, title, rank, color, remark, first_reading, psalm, second_reading,
|
||||
gospel, is_obligation, source, updated_at
|
||||
FROM liturgical_days WHERE date=?`, domain.Key(date))
|
||||
day, err := scanLiturgicalDay(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return day, err
|
||||
}
|
||||
|
||||
func scanLiturgicalDay(row rowScanner) (*domain.LiturgicalDay, error) {
|
||||
var day domain.LiturgicalDay
|
||||
var date, rank, color, updated string
|
||||
var obligation int
|
||||
if err := row.Scan(&date, &day.Title, &rank, &color, &day.Remark,
|
||||
&day.Readings.First, &day.Readings.Psalm, &day.Readings.Second, &day.Readings.Gospel,
|
||||
&obligation, &day.Source, &updated); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
day.Date = domain.MustDate(date)
|
||||
day.Rank = domain.LiturgicalRank(rank)
|
||||
day.Color = domain.LiturgicalColor(color)
|
||||
day.IsObligation = obligation != 0
|
||||
day.UpdatedAt = parseTime(updated)
|
||||
return &day, nil
|
||||
}
|
||||
|
||||
// LiturgicalDayCount returns the number of stored days.
|
||||
func (s *Store) LiturgicalDayCount(ctx context.Context) (int, error) {
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM liturgical_days").Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
// LiturgicalYears returns the years that have stored calendar data.
|
||||
func (s *Store) LiturgicalYears(ctx context.Context) ([]int, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
"SELECT DISTINCT substr(date,1,4) FROM liturgical_days ORDER BY 1")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []int
|
||||
for rows.Next() {
|
||||
var value string
|
||||
if err := rows.Scan(&value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
year := 0
|
||||
for _, r := range value {
|
||||
if r < '0' || r > '9' {
|
||||
break
|
||||
}
|
||||
year = year*10 + int(r-'0')
|
||||
}
|
||||
if year > 0 {
|
||||
out = append(out, year)
|
||||
}
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// UpsertLiturgicalDays stores a batch of calendar days.
|
||||
func (s *Store) UpsertLiturgicalDays(ctx context.Context, days []domain.LiturgicalDay) error {
|
||||
return s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
for _, day := range days {
|
||||
if err := upsertLiturgicalDayTx(ctx, tx, day); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// ReplaceLiturgicalYear replaces all stored days of one year.
|
||||
func (s *Store) ReplaceLiturgicalYear(ctx context.Context, year int, days []domain.LiturgicalDay) error {
|
||||
return s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"DELETE FROM liturgical_days WHERE date LIKE ?", time.Date(year, 1, 1, 0, 0, 0, 0, time.UTC).Format("2006")+"-%"); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, day := range days {
|
||||
if err := upsertLiturgicalDayTx(ctx, tx, day); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func upsertLiturgicalDayTx(ctx context.Context, tx *sql.Tx, day domain.LiturgicalDay) error {
|
||||
updated := day.UpdatedAt
|
||||
if updated.IsZero() {
|
||||
updated = time.Now().UTC()
|
||||
}
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO liturgical_days(date, title, rank, color, remark, first_reading, psalm,
|
||||
second_reading, gospel, is_obligation, source, updated_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(date) DO UPDATE SET title=excluded.title, rank=excluded.rank,
|
||||
color=excluded.color, remark=excluded.remark, first_reading=excluded.first_reading,
|
||||
psalm=excluded.psalm, second_reading=excluded.second_reading, gospel=excluded.gospel,
|
||||
is_obligation=excluded.is_obligation, source=excluded.source, updated_at=excluded.updated_at`,
|
||||
domain.Key(day.Date), day.Title, string(day.Rank), string(day.Color), day.Remark,
|
||||
day.Readings.First, day.Readings.Psalm, day.Readings.Second, day.Readings.Gospel,
|
||||
boolInt(day.IsObligation), day.Source, updated.Format(time.RFC3339))
|
||||
return err
|
||||
}
|
||||
|
||||
// SetLiturgicalDay stores one day.
|
||||
func (s *Store) SetLiturgicalDay(ctx context.Context, day domain.LiturgicalDay) error {
|
||||
return s.UpsertLiturgicalDays(ctx, []domain.LiturgicalDay{day})
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
func encodeStrings(values []string) string {
|
||||
if values == nil {
|
||||
values = []string{}
|
||||
}
|
||||
data, err := json.Marshal(values)
|
||||
if err != nil {
|
||||
return "[]"
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func decodeStrings(value string) []string {
|
||||
var out []string
|
||||
if err := json.Unmarshal([]byte(value), &out); err != nil {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func decodeInts(value string) []int {
|
||||
var out []int
|
||||
if err := json.Unmarshal([]byte(value), &out); err != nil {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func encodeInts(values []int) string {
|
||||
if values == nil {
|
||||
values = []int{}
|
||||
}
|
||||
data, err := json.Marshal(values)
|
||||
if err != nil {
|
||||
return "[]"
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
// Churches lists a tenant's churches.
|
||||
func (s *Store) Churches(ctx context.Context, tenantID string) ([]domain.Church, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, name, short_name, symbol, color_hex, address, sort_index, notes
|
||||
FROM churches WHERE tenant_id=? ORDER BY sort_index, name COLLATE NOCASE`, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []domain.Church
|
||||
for rows.Next() {
|
||||
var church domain.Church
|
||||
var symbol string
|
||||
if err := rows.Scan(&church.ID, &church.Name, &church.ShortName, &symbol,
|
||||
&church.ColorHex, &church.Address, &church.SortIndex, &church.Notes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
church.Symbol = domain.ChurchSymbol(symbol)
|
||||
out = append(out, church)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Church loads one church inside a tenant.
|
||||
func (s *Store) Church(ctx context.Context, tenantID, id string) (*domain.Church, error) {
|
||||
var church domain.Church
|
||||
var symbol string
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT id, name, short_name, symbol, color_hex, address, sort_index, notes
|
||||
FROM churches WHERE tenant_id=? AND id=?`, tenantID, id).
|
||||
Scan(&church.ID, &church.Name, &church.ShortName, &symbol,
|
||||
&church.ColorHex, &church.Address, &church.SortIndex, &church.Notes)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
church.Symbol = domain.ChurchSymbol(symbol)
|
||||
return &church, nil
|
||||
}
|
||||
|
||||
// CountChurches returns the number of churches in a tenant.
|
||||
func (s *Store) CountChurches(ctx context.Context, tenantID string) (int, error) {
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM churches WHERE tenant_id=?", tenantID).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
// UpsertChurch creates or updates a church.
|
||||
func (s *Store) UpsertChurch(ctx context.Context, tenantID string, church domain.Church) error {
|
||||
if strings.TrimSpace(church.ID) == "" {
|
||||
church.ID = domain.NewID()
|
||||
}
|
||||
if strings.TrimSpace(church.Name) == "" {
|
||||
return errors.New("Der Kirchenname ist erforderlich")
|
||||
}
|
||||
if church.Symbol == "" {
|
||||
church.Symbol = domain.SymbolChapel
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO churches(tenant_id, id, name, short_name, symbol, color_hex, address, sort_index, notes)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(tenant_id, id) DO UPDATE SET
|
||||
name=excluded.name, short_name=excluded.short_name, symbol=excluded.symbol,
|
||||
color_hex=excluded.color_hex, address=excluded.address,
|
||||
sort_index=excluded.sort_index, notes=excluded.notes`,
|
||||
tenantID, church.ID, church.Name, church.ShortName, string(church.Symbol),
|
||||
church.ColorHex, church.Address, church.SortIndex, church.Notes)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteChurch removes a church and all planning data that depends on it.
|
||||
func (s *Store) DeleteChurch(ctx context.Context, tenantID, id string) error {
|
||||
return s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM assignments WHERE tenant_id=? AND service_id IN (
|
||||
SELECT id FROM services WHERE tenant_id=? AND church_id=?)`,
|
||||
tenantID, tenantID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"DELETE FROM services WHERE tenant_id=? AND church_id=?", tenantID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM service_exceptions WHERE tenant_id=? AND template_id IN (
|
||||
SELECT id FROM service_templates WHERE tenant_id=? AND church_id=?)`,
|
||||
tenantID, tenantID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"DELETE FROM service_templates WHERE tenant_id=? AND church_id=?", tenantID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.ExecContext(ctx, "DELETE FROM churches WHERE tenant_id=? AND id=?", tenantID, id)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// People lists a tenant's volunteers.
|
||||
func (s *Store) People(ctx context.Context, tenantID string) ([]domain.Person, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, first_name, last_name, roles, email, phone, preferred_church_ids,
|
||||
preferred_weekdays, preferred_service_titles, max_per_month, active, notes
|
||||
FROM people WHERE tenant_id=? ORDER BY last_name COLLATE NOCASE, first_name COLLATE NOCASE`, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []domain.Person
|
||||
for rows.Next() {
|
||||
person, err := scanPerson(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, *person)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Person loads one volunteer.
|
||||
func (s *Store) Person(ctx context.Context, tenantID, id string) (*domain.Person, error) {
|
||||
row := s.db.QueryRowContext(ctx, `
|
||||
SELECT id, first_name, last_name, roles, email, phone, preferred_church_ids,
|
||||
preferred_weekdays, preferred_service_titles, max_per_month, active, notes
|
||||
FROM people WHERE tenant_id=? AND id=?`, tenantID, id)
|
||||
person, err := scanPerson(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return person, err
|
||||
}
|
||||
|
||||
func scanPerson(row rowScanner) (*domain.Person, error) {
|
||||
var person domain.Person
|
||||
var roles, churches, weekdays, titles string
|
||||
var active int
|
||||
if err := row.Scan(&person.ID, &person.FirstName, &person.LastName, &roles,
|
||||
&person.Email, &person.Phone, &churches, &weekdays, &titles,
|
||||
&person.MaxPerMonth, &active, &person.Notes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, raw := range decodeStrings(roles) {
|
||||
role := domain.Role(raw)
|
||||
if role.IsValid() {
|
||||
person.Roles = append(person.Roles, role)
|
||||
}
|
||||
}
|
||||
person.PreferredChurchIDs = decodeStrings(churches)
|
||||
person.PreferredWeekdays = decodeInts(weekdays)
|
||||
person.PreferredServiceTitles = decodeStrings(titles)
|
||||
person.Active = active != 0
|
||||
return &person, nil
|
||||
}
|
||||
|
||||
// UpsertPerson creates or updates a volunteer.
|
||||
func (s *Store) UpsertPerson(ctx context.Context, tenantID string, person domain.Person) error {
|
||||
if strings.TrimSpace(person.ID) == "" {
|
||||
person.ID = domain.NewID()
|
||||
}
|
||||
if strings.TrimSpace(person.FirstName) == "" && strings.TrimSpace(person.LastName) == "" {
|
||||
return errors.New("Der Name ist erforderlich")
|
||||
}
|
||||
roleStrings := make([]string, 0, len(person.Roles))
|
||||
for _, role := range person.Roles {
|
||||
if role.IsValid() {
|
||||
roleStrings = append(roleStrings, string(role))
|
||||
}
|
||||
}
|
||||
if person.MaxPerMonth < 0 {
|
||||
person.MaxPerMonth = 0
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO people(tenant_id, id, first_name, last_name, roles, email, phone,
|
||||
preferred_church_ids, preferred_weekdays, preferred_service_titles,
|
||||
max_per_month, active, notes)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(tenant_id, id) DO UPDATE SET
|
||||
first_name=excluded.first_name, last_name=excluded.last_name, roles=excluded.roles,
|
||||
email=excluded.email, phone=excluded.phone,
|
||||
preferred_church_ids=excluded.preferred_church_ids,
|
||||
preferred_weekdays=excluded.preferred_weekdays,
|
||||
preferred_service_titles=excluded.preferred_service_titles,
|
||||
max_per_month=excluded.max_per_month, active=excluded.active, notes=excluded.notes`,
|
||||
tenantID, person.ID, person.FirstName, person.LastName, encodeStrings(roleStrings),
|
||||
person.Email, person.Phone, encodeStrings(person.PreferredChurchIDs),
|
||||
encodeInts(person.PreferredWeekdays),
|
||||
encodeStrings(person.PreferredServiceTitles), person.MaxPerMonth,
|
||||
boolInt(person.Active), person.Notes)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeletePerson removes a volunteer with assignments and absences.
|
||||
func (s *Store) DeletePerson(ctx context.Context, tenantID, id string) error {
|
||||
return s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"DELETE FROM assignments WHERE tenant_id=? AND person_id=?", tenantID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"DELETE FROM absences WHERE tenant_id=? AND person_id=?", tenantID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.ExecContext(ctx, "DELETE FROM people WHERE tenant_id=? AND id=?", tenantID, id)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// Absences lists all absences in a tenant.
|
||||
func (s *Store) Absences(ctx context.Context, tenantID string) ([]domain.Absence, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, person_id, start_date, end_date, reason FROM absences
|
||||
WHERE tenant_id=? ORDER BY start_date`, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []domain.Absence
|
||||
for rows.Next() {
|
||||
var absence domain.Absence
|
||||
var start, end string
|
||||
if err := rows.Scan(&absence.ID, &absence.PersonID, &start, &end, &absence.Reason); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
absence.Start = domain.MustDate(start)
|
||||
absence.End = domain.MustDate(end)
|
||||
out = append(out, absence)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// AbsencesForPerson lists one person's absences.
|
||||
func (s *Store) AbsencesForPerson(ctx context.Context, tenantID, personID string) ([]domain.Absence, error) {
|
||||
all, err := s.Absences(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []domain.Absence
|
||||
for _, absence := range all {
|
||||
if absence.PersonID == personID {
|
||||
out = append(out, absence)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// UpsertAbsence creates or updates an absence.
|
||||
func (s *Store) UpsertAbsence(ctx context.Context, tenantID string, absence domain.Absence) error {
|
||||
if strings.TrimSpace(absence.ID) == "" {
|
||||
absence.ID = domain.NewID()
|
||||
}
|
||||
if absence.PersonID == "" {
|
||||
return errors.New("Es muss eine Person gewählt werden")
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO absences(tenant_id, id, person_id, start_date, end_date, reason)
|
||||
VALUES(?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(tenant_id, id) DO UPDATE SET
|
||||
person_id=excluded.person_id, start_date=excluded.start_date,
|
||||
end_date=excluded.end_date, reason=excluded.reason`,
|
||||
tenantID, absence.ID, absence.PersonID,
|
||||
domain.Key(absence.Start), domain.Key(absence.End), absence.Reason)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteAbsence removes one absence.
|
||||
func (s *Store) DeleteAbsence(ctx context.Context, tenantID, id string) error {
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM absences WHERE tenant_id=? AND id=?", tenantID, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// Templates lists service templates.
|
||||
func (s *Store) Templates(ctx context.Context, tenantID string) ([]domain.ServiceTemplate, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, church_id, weekday, time_minutes, title, lectors_needed, helpers_needed,
|
||||
valid_from, valid_to, active, notes
|
||||
FROM service_templates WHERE tenant_id=? ORDER BY weekday, time_minutes`, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []domain.ServiceTemplate
|
||||
for rows.Next() {
|
||||
var item domain.ServiceTemplate
|
||||
var validFrom string
|
||||
var validTo sql.NullString
|
||||
var active int
|
||||
if err := rows.Scan(&item.ID, &item.ChurchID, &item.Weekday, &item.TimeMinutes,
|
||||
&item.Title, &item.LectorsNeeded, &item.HelpersNeeded, &validFrom,
|
||||
&validTo, &active, &item.Notes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item.ValidFrom = domain.MustDate(validFrom)
|
||||
if validTo.Valid && validTo.String != "" {
|
||||
date := domain.MustDate(validTo.String)
|
||||
item.ValidTo = &date
|
||||
}
|
||||
item.Active = active != 0
|
||||
out = append(out, item)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Template loads one template.
|
||||
func (s *Store) Template(ctx context.Context, tenantID, id string) (*domain.ServiceTemplate, error) {
|
||||
all, err := s.Templates(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range all {
|
||||
if all[i].ID == id {
|
||||
return &all[i], nil
|
||||
}
|
||||
}
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
// UpsertTemplate creates or updates a service template.
|
||||
func (s *Store) UpsertTemplate(ctx context.Context, tenantID string, template domain.ServiceTemplate) error {
|
||||
if strings.TrimSpace(template.ID) == "" {
|
||||
template.ID = domain.NewID()
|
||||
}
|
||||
if template.ChurchID == "" || strings.TrimSpace(template.Title) == "" {
|
||||
return errors.New("Kirche und Titel sind erforderlich")
|
||||
}
|
||||
var validTo any
|
||||
if template.ValidTo != nil {
|
||||
validTo = domain.Key(*template.ValidTo)
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO service_templates(tenant_id, id, church_id, weekday, time_minutes, title,
|
||||
lectors_needed, helpers_needed, valid_from, valid_to, active, notes)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(tenant_id, id) DO UPDATE SET
|
||||
church_id=excluded.church_id, weekday=excluded.weekday,
|
||||
time_minutes=excluded.time_minutes, title=excluded.title,
|
||||
lectors_needed=excluded.lectors_needed, helpers_needed=excluded.helpers_needed,
|
||||
valid_from=excluded.valid_from, valid_to=excluded.valid_to,
|
||||
active=excluded.active, notes=excluded.notes`,
|
||||
tenantID, template.ID, template.ChurchID, template.Weekday, template.TimeMinutes,
|
||||
template.Title, template.LectorsNeeded, template.HelpersNeeded,
|
||||
domain.Key(template.ValidFrom), validTo, boolInt(template.Active), template.Notes)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteTemplate removes a template, its exceptions, and detaches services.
|
||||
func (s *Store) DeleteTemplate(ctx context.Context, tenantID, id string) error {
|
||||
return s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"UPDATE services SET template_id=NULL WHERE tenant_id=? AND template_id=?", tenantID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"DELETE FROM service_exceptions WHERE tenant_id=? AND template_id=?", tenantID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.ExecContext(ctx,
|
||||
"DELETE FROM service_templates WHERE tenant_id=? AND id=?", tenantID, id)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// Exceptions lists template exceptions.
|
||||
func (s *Store) Exceptions(ctx context.Context, tenantID string) ([]domain.ServiceException, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, template_id, date, reason FROM service_exceptions
|
||||
WHERE tenant_id=? ORDER BY date`, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []domain.ServiceException
|
||||
for rows.Next() {
|
||||
var item domain.ServiceException
|
||||
var date string
|
||||
if err := rows.Scan(&item.ID, &item.TemplateID, &date, &item.Reason); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item.Date = domain.MustDate(date)
|
||||
out = append(out, item)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// UpsertException creates or updates an exception. The unique key is
|
||||
// (tenant, template, date), matching the macOS app.
|
||||
func (s *Store) UpsertException(ctx context.Context, tenantID string, item domain.ServiceException) error {
|
||||
if strings.TrimSpace(item.ID) == "" {
|
||||
item.ID = domain.NewID()
|
||||
}
|
||||
if item.TemplateID == "" {
|
||||
return errors.New("Es muss eine Vorlage gewählt werden")
|
||||
}
|
||||
return s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
// An explicit ID means the caller is editing an existing exception in
|
||||
// place. Remove a conflicting row first so moving an exception to a new
|
||||
// template or date cannot violate the unique key.
|
||||
if strings.TrimSpace(item.ID) != "" {
|
||||
var count int
|
||||
if err := tx.QueryRowContext(ctx,
|
||||
"SELECT COUNT(*) FROM service_exceptions WHERE tenant_id=? AND id=?",
|
||||
tenantID, item.ID).Scan(&count); err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM service_exceptions
|
||||
WHERE tenant_id=? AND template_id=? AND date=? AND id<>?`,
|
||||
tenantID, item.TemplateID, domain.Key(item.Date), item.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
UPDATE service_exceptions SET template_id=?, date=?, reason=?
|
||||
WHERE tenant_id=? AND id=?`,
|
||||
item.TemplateID, domain.Key(item.Date), item.Reason, tenantID, item.ID)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
var existingID string
|
||||
err := tx.QueryRowContext(ctx, `
|
||||
SELECT id FROM service_exceptions WHERE tenant_id=? AND template_id=? AND date=?`,
|
||||
tenantID, item.TemplateID, domain.Key(item.Date)).Scan(&existingID)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
if existingID != "" {
|
||||
_, err = tx.ExecContext(ctx,
|
||||
"UPDATE service_exceptions SET reason=? WHERE tenant_id=? AND id=?",
|
||||
item.Reason, tenantID, existingID)
|
||||
return err
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
INSERT INTO service_exceptions(tenant_id, id, template_id, date, reason)
|
||||
VALUES(?, ?, ?, ?, ?)`,
|
||||
tenantID, item.ID, item.TemplateID, domain.Key(item.Date), item.Reason)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteException removes one exception.
|
||||
func (s *Store) DeleteException(ctx context.Context, tenantID, id string) error {
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM service_exceptions WHERE tenant_id=? AND id=?", tenantID, id)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
// Services returns occurrences inside an inclusive day range.
|
||||
func (s *Store) Services(ctx context.Context, tenantID string, r domain.DayRange) ([]domain.ServiceOccurrence, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, church_id, location, template_id, date, time_minutes, title,
|
||||
lectors_needed, helpers_needed, kind, notes, locked, created_at
|
||||
FROM services WHERE tenant_id=? AND date >= ? AND date <= ?
|
||||
ORDER BY date, time_minutes, church_id`,
|
||||
tenantID, domain.Key(r.Start), domain.Key(r.End))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []domain.ServiceOccurrence
|
||||
for rows.Next() {
|
||||
service, err := scanService(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, *service)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ServicesOn returns the services of one day.
|
||||
func (s *Store) ServicesOn(ctx context.Context, tenantID string, date time.Time) ([]domain.ServiceOccurrence, error) {
|
||||
return s.Services(ctx, tenantID, domain.NewDayRange(date, date))
|
||||
}
|
||||
|
||||
// Service loads one occurrence.
|
||||
func (s *Store) Service(ctx context.Context, tenantID, id string) (*domain.ServiceOccurrence, error) {
|
||||
row := s.db.QueryRowContext(ctx, `
|
||||
SELECT id, church_id, location, template_id, date, time_minutes, title,
|
||||
lectors_needed, helpers_needed, kind, notes, locked, created_at
|
||||
FROM services WHERE tenant_id=? AND id=?`, tenantID, id)
|
||||
service, err := scanService(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return service, err
|
||||
}
|
||||
|
||||
func scanService(row rowScanner) (*domain.ServiceOccurrence, error) {
|
||||
var service domain.ServiceOccurrence
|
||||
var location string
|
||||
var templateID sql.NullString
|
||||
var date, kind, created string
|
||||
var locked int
|
||||
if err := row.Scan(&service.ID, &service.ChurchID, &location, &templateID, &date,
|
||||
&service.TimeMinutes, &service.Title, &service.LectorsNeeded, &service.HelpersNeeded,
|
||||
&kind, &service.Notes, &locked, &created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if location != "" {
|
||||
service.Location = &location
|
||||
}
|
||||
if templateID.Valid && templateID.String != "" {
|
||||
value := templateID.String
|
||||
service.TemplateID = &value
|
||||
}
|
||||
service.Date = domain.MustDate(date)
|
||||
service.Kind = domain.ServiceKind(kind)
|
||||
service.Locked = locked != 0
|
||||
service.CreatedAt = parseTime(created)
|
||||
return &service, nil
|
||||
}
|
||||
|
||||
// SpecialServices lists services not generated from templates.
|
||||
func (s *Store) SpecialServices(ctx context.Context, tenantID string) ([]domain.ServiceOccurrence, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, church_id, location, template_id, date, time_minutes, title,
|
||||
lectors_needed, helpers_needed, kind, notes, locked, created_at
|
||||
FROM services WHERE tenant_id=? AND kind='special' ORDER BY date, time_minutes`, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []domain.ServiceOccurrence
|
||||
for rows.Next() {
|
||||
service, err := scanService(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, *service)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ServiceCount returns the number of occurrences in a tenant.
|
||||
func (s *Store) ServiceCount(ctx context.Context, tenantID string) (int, error) {
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM services WHERE tenant_id=?", tenantID).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
// UpsertService creates or updates an occurrence.
|
||||
func (s *Store) UpsertService(ctx context.Context, tenantID string, service domain.ServiceOccurrence) (string, error) {
|
||||
if strings.TrimSpace(service.ID) == "" {
|
||||
service.ID = domain.NewID()
|
||||
}
|
||||
if service.ChurchID == "" || strings.TrimSpace(service.Title) == "" {
|
||||
return "", errors.New("Kirche und Titel sind erforderlich")
|
||||
}
|
||||
if service.Kind == "" {
|
||||
service.Kind = domain.KindRegular
|
||||
}
|
||||
if service.CreatedAt.IsZero() {
|
||||
service.CreatedAt = time.Now().UTC()
|
||||
}
|
||||
if service.Date.IsZero() {
|
||||
service.Date = domain.Today()
|
||||
}
|
||||
location := ""
|
||||
if service.Location != nil {
|
||||
location = strings.TrimSpace(*service.Location)
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO services(tenant_id, id, church_id, location, template_id, date, time_minutes,
|
||||
title, lectors_needed, helpers_needed, kind, notes, locked, created_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(tenant_id, id) DO UPDATE SET
|
||||
church_id=excluded.church_id, location=excluded.location,
|
||||
template_id=excluded.template_id, date=excluded.date,
|
||||
time_minutes=excluded.time_minutes, title=excluded.title,
|
||||
lectors_needed=excluded.lectors_needed, helpers_needed=excluded.helpers_needed,
|
||||
kind=excluded.kind, notes=excluded.notes, locked=excluded.locked`,
|
||||
tenantID, service.ID, service.ChurchID, location, nullString(service.TemplateID),
|
||||
domain.Key(service.Date), service.TimeMinutes, service.Title,
|
||||
service.LectorsNeeded, service.HelpersNeeded, string(service.Kind),
|
||||
service.Notes, boolInt(service.Locked), service.CreatedAt.Format(time.RFC3339))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return service.ID, nil
|
||||
}
|
||||
|
||||
// DeleteService removes an occurrence and its assignments.
|
||||
func (s *Store) DeleteService(ctx context.Context, tenantID, id string) error {
|
||||
return s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"DELETE FROM assignments WHERE tenant_id=? AND service_id=?", tenantID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.ExecContext(ctx, "DELETE FROM services WHERE tenant_id=? AND id=?", tenantID, id)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// GenerateServices materialises regular services from templates. Existing
|
||||
// occurrences with assignments are never overwritten.
|
||||
func (s *Store) GenerateServices(ctx context.Context, tenantID string, r domain.DayRange, regenerateUnassigned bool) (int, error) {
|
||||
templates, err := s.Templates(ctx, tenantID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
exceptions, err := s.Exceptions(ctx, tenantID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
exceptionKeys := make(map[string]bool, len(exceptions))
|
||||
for _, exception := range exceptions {
|
||||
exceptionKeys[exception.TemplateID+"|"+domain.Key(exception.Date)] = true
|
||||
}
|
||||
existing, err := s.Services(ctx, tenantID, r)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
existingByTemplate := map[string]domain.ServiceOccurrence{}
|
||||
for _, service := range existing {
|
||||
if service.TemplateID != nil {
|
||||
existingByTemplate[*service.TemplateID+"|"+service.DateKey()] = service
|
||||
}
|
||||
}
|
||||
|
||||
created := 0
|
||||
err = s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
for _, day := range r.Days() {
|
||||
for _, template := range templates {
|
||||
if !template.IsValid(day) {
|
||||
continue
|
||||
}
|
||||
key := template.ID + "|" + domain.Key(day)
|
||||
if exceptionKeys[key] {
|
||||
continue
|
||||
}
|
||||
if service, ok := existingByTemplate[key]; ok {
|
||||
if !regenerateUnassigned {
|
||||
continue
|
||||
}
|
||||
var count int
|
||||
if err := tx.QueryRowContext(ctx,
|
||||
"SELECT COUNT(*) FROM assignments WHERE tenant_id=? AND service_id=?",
|
||||
tenantID, service.ID).Scan(&count); err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 0 {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE services SET time_minutes=?, title=?, lectors_needed=?, helpers_needed=?
|
||||
WHERE tenant_id=? AND id=?`,
|
||||
template.TimeMinutes, template.Title, template.LectorsNeeded,
|
||||
template.HelpersNeeded, tenantID, service.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
serviceID := domain.NewID()
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO services(tenant_id, id, church_id, location, template_id, date,
|
||||
time_minutes, title, lectors_needed, helpers_needed, kind, notes, locked, created_at)
|
||||
VALUES(?, ?, ?, '', ?, ?, ?, ?, ?, ?, 'regular', ?, 0, ?)`,
|
||||
tenantID, serviceID, template.ChurchID, template.ID, domain.Key(day),
|
||||
template.TimeMinutes, template.Title, template.LectorsNeeded,
|
||||
template.HelpersNeeded, template.Notes, time.Now().UTC().Format(time.RFC3339)); err != nil {
|
||||
return err
|
||||
}
|
||||
created++
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return created, err
|
||||
}
|
||||
|
||||
// DeleteGeneratedServices removes regular services in a range, for example
|
||||
// before regenerating after a template change.
|
||||
func (s *Store) DeleteGeneratedServices(ctx context.Context, tenantID string, r domain.DayRange) (int, error) {
|
||||
result, err := s.db.ExecContext(ctx, `
|
||||
DELETE FROM services WHERE tenant_id=? AND date >= ? AND date <= ? AND kind='regular'
|
||||
AND id IN (SELECT id FROM services s2 WHERE s2.tenant_id=? AND s2.date >= ? AND s2.date <= ?
|
||||
AND s2.kind='regular')`,
|
||||
tenantID, domain.Key(r.Start), domain.Key(r.End), tenantID, domain.Key(r.Start), domain.Key(r.End))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
affected, _ := result.RowsAffected()
|
||||
return int(affected), nil
|
||||
}
|
||||
|
||||
// Assignments returns assignments whose service lies in the range.
|
||||
func (s *Store) Assignments(ctx context.Context, tenantID string, r domain.DayRange) ([]domain.Assignment, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT a.id, a.service_id, a.person_id, a.role, a.locked, a.note, a.created_at
|
||||
FROM assignments a JOIN services s ON s.tenant_id=a.tenant_id AND s.id=a.service_id
|
||||
WHERE a.tenant_id=? AND s.date >= ? AND s.date <= ?
|
||||
ORDER BY s.date, s.time_minutes`, tenantID, domain.Key(r.Start), domain.Key(r.End))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanAssignments(rows)
|
||||
}
|
||||
|
||||
// AssignmentsForServices loads assignments for a set of service IDs.
|
||||
func (s *Store) AssignmentsForServices(ctx context.Context, tenantID string, serviceIDs []string) ([]domain.Assignment, error) {
|
||||
if len(serviceIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
placeholders := strings.TrimSuffix(strings.Repeat("?,", len(serviceIDs)), ",")
|
||||
args := make([]any, 0, len(serviceIDs)+1)
|
||||
args = append(args, tenantID)
|
||||
for _, id := range serviceIDs {
|
||||
args = append(args, id)
|
||||
}
|
||||
query := "SELECT id, service_id, person_id, role, locked, note, created_at FROM assignments " +
|
||||
"WHERE tenant_id=? AND service_id IN (" + placeholders + ")"
|
||||
rows, err := s.db.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanAssignments(rows)
|
||||
}
|
||||
|
||||
// AssignmentsForPerson lists all assignments of a volunteer.
|
||||
func (s *Store) AssignmentsForPerson(ctx context.Context, tenantID, personID string) ([]domain.Assignment, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, service_id, person_id, role, locked, note, created_at
|
||||
FROM assignments WHERE tenant_id=? AND person_id=? ORDER BY created_at`, tenantID, personID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanAssignments(rows)
|
||||
}
|
||||
|
||||
// AssignmentCount returns the number of assignments in a tenant.
|
||||
func (s *Store) AssignmentCount(ctx context.Context, tenantID string) (int, error) {
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM assignments WHERE tenant_id=?", tenantID).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
func scanAssignments(rows *sql.Rows) ([]domain.Assignment, error) {
|
||||
var out []domain.Assignment
|
||||
for rows.Next() {
|
||||
var assignment domain.Assignment
|
||||
var role, created string
|
||||
var locked int
|
||||
if err := rows.Scan(&assignment.ID, &assignment.ServiceID, &assignment.PersonID,
|
||||
&role, &locked, &assignment.Note, &created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
assignment.Role = domain.Role(role)
|
||||
assignment.Locked = locked != 0
|
||||
assignment.CreatedAt = parseTime(created)
|
||||
out = append(out, assignment)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// UpsertAssignment creates or updates an assignment.
|
||||
func (s *Store) UpsertAssignment(ctx context.Context, tenantID string, assignment domain.Assignment) error {
|
||||
if strings.TrimSpace(assignment.ID) == "" {
|
||||
assignment.ID = domain.NewID()
|
||||
}
|
||||
if assignment.ServiceID == "" || assignment.PersonID == "" || !assignment.Role.IsValid() {
|
||||
return errors.New("Dienst, Person und Rolle sind erforderlich")
|
||||
}
|
||||
if assignment.CreatedAt.IsZero() {
|
||||
assignment.CreatedAt = time.Now().UTC()
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO assignments(tenant_id, id, service_id, person_id, role, locked, note, created_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(tenant_id, id) DO UPDATE SET
|
||||
service_id=excluded.service_id, person_id=excluded.person_id,
|
||||
role=excluded.role, locked=excluded.locked, note=excluded.note`,
|
||||
tenantID, assignment.ID, assignment.ServiceID, assignment.PersonID,
|
||||
string(assignment.Role), boolInt(assignment.Locked), assignment.Note,
|
||||
assignment.CreatedAt.Format(time.RFC3339))
|
||||
if err != nil && isUniqueViolation(err) {
|
||||
return ErrConflict
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteAssignment removes one assignment.
|
||||
func (s *Store) DeleteAssignment(ctx context.Context, tenantID, id string) error {
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM assignments WHERE tenant_id=? AND id=?", tenantID, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// ToggleAssignmentLock flips the lock bit.
|
||||
func (s *Store) ToggleAssignmentLock(ctx context.Context, tenantID, id string) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
"UPDATE assignments SET locked = CASE locked WHEN 0 THEN 1 ELSE 0 END WHERE tenant_id=? AND id=?",
|
||||
tenantID, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// SavePlan stores planner results. With replaceUnlocked the unlocked
|
||||
// assignments of the range are cleared first, matching the macOS app.
|
||||
func (s *Store) SavePlan(ctx context.Context, tenantID string, assignments []domain.Assignment, r domain.DayRange, replaceUnlocked bool) error {
|
||||
return s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
if replaceUnlocked {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM assignments WHERE tenant_id=? AND locked=0 AND service_id IN (
|
||||
SELECT id FROM services WHERE tenant_id=? AND date >= ? AND date <= ?)`,
|
||||
tenantID, tenantID, domain.Key(r.Start), domain.Key(r.End)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, assignment := range assignments {
|
||||
if assignment.ID == "" {
|
||||
assignment.ID = domain.NewID()
|
||||
}
|
||||
if assignment.CreatedAt.IsZero() {
|
||||
assignment.CreatedAt = time.Now().UTC()
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO assignments(tenant_id, id, service_id, person_id, role, locked, note, created_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(tenant_id, id) DO UPDATE SET
|
||||
service_id=excluded.service_id, person_id=excluded.person_id,
|
||||
role=excluded.role, locked=excluded.locked, note=excluded.note`,
|
||||
tenantID, assignment.ID, assignment.ServiceID, assignment.PersonID,
|
||||
string(assignment.Role), boolInt(assignment.Locked), assignment.Note,
|
||||
assignment.CreatedAt.Format(time.RFC3339)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// PlanRows assembles the calendar rows for a range, including liturgy and
|
||||
// assignments, ready for templates.
|
||||
func (s *Store) PlanRows(ctx context.Context, tenantID string, r domain.DayRange) ([]domain.DayPlanRow, error) {
|
||||
services, err := s.Services(ctx, tenantID, r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
churches, err := s.Churches(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
churchByID := make(map[string]domain.Church, len(churches))
|
||||
for _, church := range churches {
|
||||
churchByID[church.ID] = church
|
||||
}
|
||||
liturgical, err := s.LiturgicalDays(ctx, r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
liturgicalByKey := make(map[string]domain.LiturgicalDay, len(liturgical))
|
||||
for _, day := range liturgical {
|
||||
liturgicalByKey[day.DateKey()] = day
|
||||
}
|
||||
|
||||
serviceIDs := make([]string, len(services))
|
||||
for i, service := range services {
|
||||
serviceIDs[i] = service.ID
|
||||
}
|
||||
assignments, err := s.AssignmentsForServices(ctx, tenantID, serviceIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
assignmentsByService := map[string][]domain.Assignment{}
|
||||
for _, assignment := range assignments {
|
||||
assignmentsByService[assignment.ServiceID] = append(assignmentsByService[assignment.ServiceID], assignment)
|
||||
}
|
||||
|
||||
rows := make([]domain.DayPlanRow, 0, r.DayCount())
|
||||
serviceByKey := map[string][]domain.ServiceWithAssignments{}
|
||||
for _, service := range services {
|
||||
church := churchByID[service.ChurchID]
|
||||
serviceByKey[service.DateKey()] = append(serviceByKey[service.DateKey()], domain.ServiceWithAssignments{
|
||||
Service: service, Church: church, Assignments: assignmentsByService[service.ID],
|
||||
})
|
||||
}
|
||||
for _, day := range r.Days() {
|
||||
key := domain.Key(day)
|
||||
row := domain.DayPlanRow{Date: day, Services: serviceByKey[key]}
|
||||
if liturgicalDay, ok := liturgicalByKey[key]; ok {
|
||||
copy := liturgicalDay
|
||||
row.LiturgicalDay = ©
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// PlanRowsForServices builds rows for an explicit set of services.
|
||||
func (s *Store) PlanRowsForServices(ctx context.Context, tenantID string, services []domain.ServiceOccurrence) ([]domain.DayPlanRow, error) {
|
||||
if len(services) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
sort.SliceStable(services, func(i, j int) bool {
|
||||
if !services[i].Date.Equal(services[j].Date) {
|
||||
return services[i].Date.Before(services[j].Date)
|
||||
}
|
||||
if services[i].TimeMinutes != services[j].TimeMinutes {
|
||||
return services[i].TimeMinutes < services[j].TimeMinutes
|
||||
}
|
||||
return services[i].ChurchID < services[j].ChurchID
|
||||
})
|
||||
start, end := services[0].Date, services[len(services)-1].Date
|
||||
return s.PlanRows(ctx, tenantID, domain.NewDayRange(start, end))
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// Setting returns a global setting or the empty string.
|
||||
func (s *Store) Setting(ctx context.Context, key string) string {
|
||||
var value string
|
||||
err := s.db.QueryRowContext(ctx, "SELECT value FROM settings WHERE key=?", key).Scan(&value)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// SetSetting stores a global setting.
|
||||
func (s *Store) SetSetting(ctx context.Context, key, value string) error {
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO settings(key, value) VALUES(?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET value=excluded.value`, key, value)
|
||||
return err
|
||||
}
|
||||
|
||||
// RemoveSetting deletes a global setting.
|
||||
func (s *Store) RemoveSetting(ctx context.Context, key string) error {
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM settings WHERE key=?", key)
|
||||
return err
|
||||
}
|
||||
|
||||
// TenantSetting returns a tenant-scoped setting or the empty string.
|
||||
func (s *Store) TenantSetting(ctx context.Context, tenantID, key string) string {
|
||||
var value string
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
"SELECT value FROM tenant_settings WHERE tenant_id=? AND key=?", tenantID, key).Scan(&value)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// SetTenantSetting stores a tenant-scoped setting.
|
||||
func (s *Store) SetTenantSetting(ctx context.Context, tenantID, key, value string) error {
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO tenant_settings(tenant_id, key, value) VALUES(?, ?, ?)
|
||||
ON CONFLICT(tenant_id, key) DO UPDATE SET value=excluded.value`, tenantID, key, value)
|
||||
return err
|
||||
}
|
||||
|
||||
// AllTenantSettings loads the settings map of one tenant.
|
||||
func (s *Store) AllTenantSettings(ctx context.Context, tenantID string) (map[string]string, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
"SELECT key, value FROM tenant_settings WHERE tenant_id=?", tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[string]string{}
|
||||
for rows.Next() {
|
||||
var key, value string
|
||||
if err := rows.Scan(&key, &value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[key] = value
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// CountTenantData returns a small summary used by admin screens.
|
||||
func (s *Store) CountTenantData(ctx context.Context, tenantID string) (map[string]int, error) {
|
||||
counts := map[string]int{}
|
||||
queries := map[string]string{
|
||||
"churches": "SELECT COUNT(*) FROM churches WHERE tenant_id=?",
|
||||
"people": "SELECT COUNT(*) FROM people WHERE tenant_id=?",
|
||||
"templates": "SELECT COUNT(*) FROM service_templates WHERE tenant_id=?",
|
||||
"services": "SELECT COUNT(*) FROM services WHERE tenant_id=?",
|
||||
"assignments": "SELECT COUNT(*) FROM assignments WHERE tenant_id=?",
|
||||
}
|
||||
for key, query := range queries {
|
||||
var value int
|
||||
if err := s.db.QueryRowContext(ctx, query, tenantID).Scan(&value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
counts[key] = value
|
||||
}
|
||||
return counts, nil
|
||||
}
|
||||
|
||||
// DeleteAllTenantData empties one tenant's planning data but keeps accounts.
|
||||
func (s *Store) DeleteAllTenantData(ctx context.Context, tenantID string) error {
|
||||
return s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
statements := []string{
|
||||
"DELETE FROM assignments WHERE tenant_id=?",
|
||||
"DELETE FROM services WHERE tenant_id=?",
|
||||
"DELETE FROM service_exceptions WHERE tenant_id=?",
|
||||
"DELETE FROM service_templates WHERE tenant_id=?",
|
||||
"DELETE FROM absences WHERE tenant_id=?",
|
||||
"DELETE FROM people WHERE tenant_id=?",
|
||||
"DELETE FROM churches WHERE tenant_id=?",
|
||||
"DELETE FROM tenant_settings WHERE tenant_id=?",
|
||||
}
|
||||
for _, statement := range statements {
|
||||
if _, err := tx.ExecContext(ctx, statement, tenantID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// Healthy verifies that the database answers a trivial query.
|
||||
func (s *Store) Healthy(ctx context.Context) error {
|
||||
var value int
|
||||
err := s.db.QueryRowContext(ctx, "SELECT 1").Scan(&value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if value != 1 {
|
||||
return errors.New("unerwartete Datenbankantwort")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
func testStore(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
s, err := Open(":memory:")
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return s
|
||||
}
|
||||
|
||||
func TestSeedDemoCreatesTwoTenants(t *testing.T) {
|
||||
s := testStore(t)
|
||||
ctx := context.Background()
|
||||
if err := s.SeedDemo(ctx); err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
tenants, err := s.Tenants(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("tenants: %v", err)
|
||||
}
|
||||
if len(tenants) != 2 {
|
||||
t.Fatalf("expected 2 tenants, got %d", len(tenants))
|
||||
}
|
||||
for _, tenant := range tenants {
|
||||
churches, err := s.Churches(ctx, tenant.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("churches: %v", err)
|
||||
}
|
||||
if len(churches) < 3 {
|
||||
t.Errorf("tenant %s: expected churches, got %d", tenant.Name, len(churches))
|
||||
}
|
||||
services, err := s.ServiceCount(ctx, tenant.ID)
|
||||
if err != nil || services == 0 {
|
||||
t.Errorf("tenant %s: expected services, got %d (%v)", tenant.Name, services, err)
|
||||
}
|
||||
assignments, err := s.AssignmentCount(ctx, tenant.ID)
|
||||
if err != nil || assignments == 0 {
|
||||
t.Errorf("tenant %s: expected assignments, got %d (%v)", tenant.Name, assignments, err)
|
||||
}
|
||||
}
|
||||
if count, _ := s.LiturgicalDayCount(ctx); count < 1400 {
|
||||
t.Errorf("expected liturgical snapshot, got %d days", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDemoAccountsAndMemberships(t *testing.T) {
|
||||
s := testStore(t)
|
||||
ctx := context.Background()
|
||||
if err := s.SeedDemo(ctx); err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
admin, err := s.Authenticate(ctx, "admin", "admin123")
|
||||
if err != nil {
|
||||
t.Fatalf("admin login: %v", err)
|
||||
}
|
||||
if admin.Role != RoleAdmin {
|
||||
t.Errorf("expected admin role, got %s", admin.Role)
|
||||
}
|
||||
editor, err := s.Authenticate(ctx, "editor", "editor123")
|
||||
if err != nil {
|
||||
t.Fatalf("editor login: %v", err)
|
||||
}
|
||||
if len(editor.TenantIDs) != 2 {
|
||||
t.Errorf("expected editor in two tenants, got %v", editor.TenantIDs)
|
||||
}
|
||||
reader, err := s.Authenticate(ctx, "reader", "reader123")
|
||||
if err != nil {
|
||||
t.Fatalf("reader login: %v", err)
|
||||
}
|
||||
tenants, err := s.TenantsForUser(ctx, reader)
|
||||
if err != nil || len(tenants) != 1 {
|
||||
t.Errorf("expected one tenant for reader, got %d (%v)", len(tenants), err)
|
||||
}
|
||||
for _, tenant := range tenants {
|
||||
if s.CanEditTenant(ctx, reader, tenant.ID) {
|
||||
t.Errorf("reader must not edit")
|
||||
}
|
||||
if !s.CanAccessTenant(ctx, reader, tenant.ID) {
|
||||
t.Errorf("reader must read assigned tenant")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlannerAndStatistics(t *testing.T) {
|
||||
s := testStore(t)
|
||||
ctx := context.Background()
|
||||
if err := s.SeedDemo(ctx); err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
tenants, _ := s.Tenants(ctx)
|
||||
tenant := tenants[0]
|
||||
people, _ := s.People(ctx, tenant.ID)
|
||||
churches, _ := s.Churches(ctx, tenant.ID)
|
||||
absences, _ := s.Absences(ctx, tenant.ID)
|
||||
start := domain.MustDate("2026-12-01")
|
||||
end := domain.MustDate("2026-12-14")
|
||||
r := domain.NewDayRange(start, end)
|
||||
services, err := s.Services(ctx, tenant.ID, r)
|
||||
if err != nil || len(services) == 0 {
|
||||
t.Fatalf("services: %d (%v)", len(services), err)
|
||||
}
|
||||
result := domain.ServicePlanner{
|
||||
People: people, Absences: absences, Services: services,
|
||||
Churches: churches, Options: domain.DefaultPlannerOptions(),
|
||||
}.Plan()
|
||||
if result.FilledCount == 0 {
|
||||
t.Errorf("expected planner to fill slots")
|
||||
}
|
||||
stats := domain.ComputeStatistics(r, services, result.Assignments, people, churches, absences)
|
||||
if stats.ServiceCount != len(services) {
|
||||
t.Errorf("statistics service count mismatch")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
// Tenant is an independent parish or planning group. All planning data is
|
||||
// scoped by tenant.
|
||||
type Tenant struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Slug string `json:"slug"`
|
||||
Notes string `json:"notes"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
// Tenants returns every tenant ordered by name.
|
||||
func (s *Store) Tenants(ctx context.Context) ([]Tenant, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
"SELECT id, name, slug, notes, created_at FROM tenants ORDER BY name COLLATE NOCASE")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []Tenant
|
||||
for rows.Next() {
|
||||
var tenant Tenant
|
||||
var created string
|
||||
if err := rows.Scan(&tenant.ID, &tenant.Name, &tenant.Slug, &tenant.Notes, &created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenant.CreatedAt = parseTime(created)
|
||||
out = append(out, tenant)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Tenant loads one tenant by id.
|
||||
func (s *Store) Tenant(ctx context.Context, id string) (*Tenant, error) {
|
||||
var tenant Tenant
|
||||
var created string
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
"SELECT id, name, slug, notes, created_at FROM tenants WHERE id=?", id).
|
||||
Scan(&tenant.ID, &tenant.Name, &tenant.Slug, &tenant.Notes, &created)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenant.CreatedAt = parseTime(created)
|
||||
return &tenant, nil
|
||||
}
|
||||
|
||||
// TenantBySlug loads one tenant by its URL slug.
|
||||
func (s *Store) TenantBySlug(ctx context.Context, slug string) (*Tenant, error) {
|
||||
var tenant Tenant
|
||||
var created string
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
"SELECT id, name, slug, notes, created_at FROM tenants WHERE slug=? COLLATE NOCASE", slug).
|
||||
Scan(&tenant.ID, &tenant.Name, &tenant.Slug, &tenant.Notes, &created)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenant.CreatedAt = parseTime(created)
|
||||
return &tenant, nil
|
||||
}
|
||||
|
||||
// CreateTenant adds a new planning group.
|
||||
func (s *Store) CreateTenant(ctx context.Context, name, slug, notes string) (*Tenant, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
slug = slugify(slug)
|
||||
if slug == "" {
|
||||
slug = slugify(name)
|
||||
}
|
||||
if name == "" || slug == "" {
|
||||
return nil, errors.New("Name und Kennung sind erforderlich")
|
||||
}
|
||||
tenant := &Tenant{
|
||||
ID: domain.NewID(), Name: name, Slug: slug, Notes: strings.TrimSpace(notes),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
"INSERT INTO tenants(id, name, slug, notes, created_at) VALUES(?, ?, ?, ?, ?)",
|
||||
tenant.ID, tenant.Name, tenant.Slug, tenant.Notes, tenant.CreatedAt.Format(time.RFC3339))
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return tenant, nil
|
||||
}
|
||||
|
||||
// UpdateTenant saves name, slug and notes.
|
||||
func (s *Store) UpdateTenant(ctx context.Context, tenant *Tenant) error {
|
||||
tenant.Name = strings.TrimSpace(tenant.Name)
|
||||
tenant.Slug = slugify(tenant.Slug)
|
||||
tenant.Notes = strings.TrimSpace(tenant.Notes)
|
||||
if tenant.ID == "" || tenant.Name == "" || tenant.Slug == "" {
|
||||
return errors.New("Name und Kennung sind erforderlich")
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
"UPDATE tenants SET name=?, slug=?, notes=? WHERE id=?",
|
||||
tenant.Name, tenant.Slug, tenant.Notes, tenant.ID)
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return ErrConflict
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteTenant removes a tenant and, through cascades, its planning data.
|
||||
func (s *Store) DeleteTenant(ctx context.Context, id string) error {
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM tenants WHERE id=?", id)
|
||||
return err
|
||||
}
|
||||
|
||||
func slugify(value string) string {
|
||||
value = strings.ToLower(strings.TrimSpace(value))
|
||||
replacer := strings.NewReplacer(
|
||||
"ä", "ae", "ö", "oe", "ü", "ue", "ß", "ss",
|
||||
" ", "-", "_", "-", ".", "-", "/", "-", ",", "",
|
||||
)
|
||||
value = replacer.Replace(value)
|
||||
var b strings.Builder
|
||||
lastDash := false
|
||||
for _, r := range value {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
|
||||
b.WriteRune(r)
|
||||
lastDash = false
|
||||
case r == '-':
|
||||
if !lastDash && b.Len() > 0 {
|
||||
b.WriteRune('-')
|
||||
lastDash = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.Trim(b.String(), "-")
|
||||
}
|
||||
|
||||
// Memberships lists the tenant IDs assigned to a user.
|
||||
func (s *Store) Memberships(ctx context.Context, userID string) ([]string, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
"SELECT tenant_id FROM memberships WHERE user_id=? ORDER BY tenant_id", userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []string
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, id)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// SetMemberships replaces the tenants assigned to a user.
|
||||
func (s *Store) SetMemberships(ctx context.Context, userID string, tenantIDs []string) error {
|
||||
return s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM memberships WHERE user_id=?", userID); err != nil {
|
||||
return err
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, tenantID := range tenantIDs {
|
||||
if tenantID == "" || seen[tenantID] {
|
||||
continue
|
||||
}
|
||||
seen[tenantID] = true
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"INSERT INTO memberships(user_id, tenant_id) VALUES(?, ?)", userID, tenantID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// TenantsForUser returns the tenants a user may open. Admins see all.
|
||||
func (s *Store) TenantsForUser(ctx context.Context, user *User) ([]Tenant, error) {
|
||||
if user == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if user.Role == RoleAdmin {
|
||||
return s.Tenants(ctx)
|
||||
}
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT t.id, t.name, t.slug, t.notes, t.created_at
|
||||
FROM tenants t JOIN memberships m ON m.tenant_id = t.id
|
||||
WHERE m.user_id=? ORDER BY t.name COLLATE NOCASE`, user.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []Tenant
|
||||
for rows.Next() {
|
||||
var tenant Tenant
|
||||
var created string
|
||||
if err := rows.Scan(&tenant.ID, &tenant.Name, &tenant.Slug, &tenant.Notes, &created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenant.CreatedAt = parseTime(created)
|
||||
out = append(out, tenant)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// CanAccessTenant reports whether the user may read the tenant.
|
||||
func (s *Store) CanAccessTenant(ctx context.Context, user *User, tenantID string) bool {
|
||||
if user == nil || !user.Active {
|
||||
return false
|
||||
}
|
||||
if user.Role == RoleAdmin {
|
||||
return true
|
||||
}
|
||||
var count int
|
||||
if err := s.db.QueryRowContext(ctx,
|
||||
"SELECT COUNT(*) FROM memberships WHERE user_id=? AND tenant_id=?", user.ID, tenantID).Scan(&count); err != nil {
|
||||
return false
|
||||
}
|
||||
return count > 0
|
||||
}
|
||||
|
||||
// CanEditTenant reports whether the user may change planning data.
|
||||
func (s *Store) CanEditTenant(ctx context.Context, user *User, tenantID string) bool {
|
||||
if user == nil || !user.Active {
|
||||
return false
|
||||
}
|
||||
if user.Role == RoleAdmin {
|
||||
return true
|
||||
}
|
||||
if user.Role != RoleEditor {
|
||||
return false
|
||||
}
|
||||
return s.CanAccessTenant(ctx, user, tenantID)
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"lektorenplan/domain"
|
||||
"lektorenplan/store"
|
||||
)
|
||||
|
||||
type adminTenantRow struct {
|
||||
Tenant store.Tenant
|
||||
Counts map[string]int
|
||||
UserCount int
|
||||
}
|
||||
|
||||
type adminTenantsPageData struct {
|
||||
Tenants []adminTenantRow
|
||||
Edit *store.Tenant
|
||||
}
|
||||
|
||||
type adminUsersPageData struct {
|
||||
Users []store.User
|
||||
Tenants []store.Tenant
|
||||
TenantsByID map[string]store.Tenant
|
||||
Roles []store.UserRole
|
||||
Edit *store.User
|
||||
SelfID string
|
||||
}
|
||||
|
||||
type adminChurchesPageData struct {
|
||||
Churches []domain.Church
|
||||
Symbols []domain.ChurchSymbol
|
||||
Edit *domain.Church
|
||||
Tenant *store.Tenant
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminRoot(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
s.redirect(w, r, "/admin/tenants")
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminTenants(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
tenants, err := s.store.Tenants(r.Context())
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Mandanten", err.Error())
|
||||
return
|
||||
}
|
||||
users, err := s.store.Users(r.Context())
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Konten", err.Error())
|
||||
return
|
||||
}
|
||||
rows := make([]adminTenantRow, 0, len(tenants))
|
||||
for _, item := range tenants {
|
||||
counts, err := s.store.CountTenantData(r.Context(), item.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Mandanten", err.Error())
|
||||
return
|
||||
}
|
||||
userCount := 0
|
||||
for _, account := range users {
|
||||
for _, tenantID := range account.TenantIDs {
|
||||
if tenantID == item.ID {
|
||||
userCount++
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
rows = append(rows, adminTenantRow{Tenant: item, Counts: counts, UserCount: userCount})
|
||||
}
|
||||
var edit *store.Tenant
|
||||
if id := strings.TrimSpace(r.URL.Query().Get("edit")); id != "" {
|
||||
for i := range tenants {
|
||||
if tenants[i].ID == id {
|
||||
copy := tenants[i]
|
||||
edit = ©
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
page := adminTenantsPageData{Tenants: rows, Edit: edit}
|
||||
data := s.baseView(w, r, "Mandanten", "admin_tenants")
|
||||
data.Data = page
|
||||
s.renderPage(w, r, "admin_tenants", data)
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminTenantSave(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
id := strings.TrimSpace(r.FormValue("id"))
|
||||
name := strings.TrimSpace(r.FormValue("name"))
|
||||
slug := strings.TrimSpace(r.FormValue("slug"))
|
||||
notes := strings.TrimSpace(r.FormValue("notes"))
|
||||
if name == "" {
|
||||
s.setFlash(w, "Der Name des Mandanten ist erforderlich.", "error")
|
||||
s.redirect(w, r, "/admin/tenants")
|
||||
return
|
||||
}
|
||||
if id == "" {
|
||||
created, err := s.store.CreateTenant(r.Context(), name, slug, notes)
|
||||
if err != nil {
|
||||
s.setFlash(w, "Der Mandant konnte nicht angelegt werden: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/admin/tenants")
|
||||
return
|
||||
}
|
||||
s.setFlash(w, "Mandant „"+created.Name+"“ angelegt.", "success")
|
||||
s.redirect(w, r, "/admin/tenants?edit="+created.ID)
|
||||
return
|
||||
}
|
||||
existing, err := s.store.Tenant(r.Context(), id)
|
||||
if err != nil {
|
||||
s.setFlash(w, "Der Mandant wurde nicht gefunden.", "error")
|
||||
s.redirect(w, r, "/admin/tenants")
|
||||
return
|
||||
}
|
||||
existing.Name = name
|
||||
existing.Slug = slug
|
||||
existing.Notes = notes
|
||||
if err := s.store.UpdateTenant(r.Context(), existing); err != nil {
|
||||
s.setFlash(w, "Der Mandant konnte nicht gespeichert werden: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/admin/tenants?edit="+id)
|
||||
return
|
||||
}
|
||||
s.setFlash(w, "Mandant gespeichert.", "success")
|
||||
s.redirect(w, r, "/admin/tenants?edit="+id)
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminTenantDelete(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
id := strings.TrimSpace(r.FormValue("id"))
|
||||
if id == "" {
|
||||
s.redirect(w, r, "/admin/tenants")
|
||||
return
|
||||
}
|
||||
if tenant != nil && tenant.ID == id {
|
||||
s.setFlash(w, "Der gerade aktive Mandant kann nicht gelöscht werden. Bitte zuerst wechseln.", "error")
|
||||
s.redirect(w, r, "/admin/tenants")
|
||||
return
|
||||
}
|
||||
if err := s.store.DeleteTenant(r.Context(), id); err != nil {
|
||||
s.setFlash(w, "Der Mandant konnte nicht gelöscht werden: "+err.Error(), "error")
|
||||
} else {
|
||||
s.setFlash(w, "Mandant und alle zugehörigen Daten gelöscht.", "success")
|
||||
}
|
||||
s.redirect(w, r, "/admin/tenants")
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminUsers(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
users, err := s.store.Users(r.Context())
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Konten", err.Error())
|
||||
return
|
||||
}
|
||||
tenants, err := s.store.Tenants(r.Context())
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Mandanten", err.Error())
|
||||
return
|
||||
}
|
||||
var edit *store.User
|
||||
if id := strings.TrimSpace(r.URL.Query().Get("edit")); id != "" {
|
||||
for i := range users {
|
||||
if users[i].ID == id {
|
||||
copy := users[i]
|
||||
edit = ©
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
tenantsByID := map[string]store.Tenant{}
|
||||
for _, item := range tenants {
|
||||
tenantsByID[item.ID] = item
|
||||
}
|
||||
page := adminUsersPageData{
|
||||
Users: users, Tenants: tenants, TenantsByID: tenantsByID, Edit: edit, SelfID: user.ID,
|
||||
Roles: []store.UserRole{store.RoleAdmin, store.RoleEditor, store.RoleReader},
|
||||
}
|
||||
data := s.baseView(w, r, "Konten", "admin_users")
|
||||
data.Data = page
|
||||
s.renderPage(w, r, "admin_users", data)
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminUserSave(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
id := strings.TrimSpace(r.FormValue("id"))
|
||||
username := strings.TrimSpace(r.FormValue("username"))
|
||||
displayName := strings.TrimSpace(r.FormValue("display_name"))
|
||||
password := r.FormValue("password")
|
||||
role := store.UserRole(strings.TrimSpace(r.FormValue("role")))
|
||||
active := r.FormValue("active") == "1" || r.FormValue("active") == "on"
|
||||
tenantIDs := r.Form["tenant_ids"]
|
||||
if !role.IsValid() {
|
||||
s.setFlash(w, "Bitte eine gültige Rolle auswählen.", "error")
|
||||
s.redirect(w, r, "/admin/users")
|
||||
return
|
||||
}
|
||||
if id == user.ID && (role != store.RoleAdmin || !active) {
|
||||
s.setFlash(w, "Das eigene Administratorkonto kann nicht herabgestuft oder deaktiviert werden.", "error")
|
||||
s.redirect(w, r, "/admin/users?edit="+id)
|
||||
return
|
||||
}
|
||||
if id == "" {
|
||||
if strings.TrimSpace(password) == "" {
|
||||
s.setFlash(w, "Für ein neues Konto ist ein Passwort erforderlich.", "error")
|
||||
s.redirect(w, r, "/admin/users")
|
||||
return
|
||||
}
|
||||
created, err := s.store.CreateUser(r.Context(), username, displayName, password, role, active, tenantIDs)
|
||||
if err != nil {
|
||||
s.setFlash(w, "Das Konto konnte nicht angelegt werden: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/admin/users")
|
||||
return
|
||||
}
|
||||
s.setFlash(w, "Konto „"+created.Username+"“ angelegt.", "success")
|
||||
s.redirect(w, r, "/admin/users?edit="+created.ID)
|
||||
return
|
||||
}
|
||||
if err := s.store.UpdateUser(r.Context(), id, username, displayName, password, role, active, tenantIDs); err != nil {
|
||||
s.setFlash(w, "Das Konto konnte nicht gespeichert werden: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/admin/users?edit="+id)
|
||||
return
|
||||
}
|
||||
s.setFlash(w, "Konto gespeichert.", "success")
|
||||
s.redirect(w, r, "/admin/users?edit="+id)
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminUserDelete(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
id := strings.TrimSpace(r.FormValue("id"))
|
||||
if id == user.ID {
|
||||
s.setFlash(w, "Das eigene Konto kann nicht gelöscht werden.", "error")
|
||||
s.redirect(w, r, "/admin/users")
|
||||
return
|
||||
}
|
||||
if err := s.store.DeleteUser(r.Context(), id); err != nil {
|
||||
s.setFlash(w, "Das Konto konnte nicht gelöscht werden: "+err.Error(), "error")
|
||||
} else {
|
||||
s.setFlash(w, "Konto gelöscht.", "success")
|
||||
}
|
||||
s.redirect(w, r, "/admin/users")
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminChurches(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.renderNoTenant(w, r)
|
||||
return
|
||||
}
|
||||
churches, err := s.store.Churches(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Kirchen", err.Error())
|
||||
return
|
||||
}
|
||||
var edit *domain.Church
|
||||
if id := strings.TrimSpace(r.URL.Query().Get("edit")); id != "" {
|
||||
for i := range churches {
|
||||
if churches[i].ID == id {
|
||||
copy := churches[i]
|
||||
edit = ©
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
page := adminChurchesPageData{
|
||||
Churches: churches, Symbols: domain.AllChurchSymbols, Edit: edit, Tenant: tenant,
|
||||
}
|
||||
data := s.baseView(w, r, "Kirchen", "admin_churches")
|
||||
data.Data = page
|
||||
s.renderPage(w, r, "admin_churches", data)
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminChurchSave(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.redirect(w, r, "/admin/churches")
|
||||
return
|
||||
}
|
||||
id := strings.TrimSpace(r.FormValue("id"))
|
||||
if id == "" {
|
||||
id = domain.NewID()
|
||||
}
|
||||
symbol := domain.ChurchSymbol(strings.TrimSpace(r.FormValue("symbol")))
|
||||
validSymbol := false
|
||||
for _, candidate := range domain.AllChurchSymbols {
|
||||
if candidate == symbol {
|
||||
validSymbol = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !validSymbol {
|
||||
symbol = domain.SymbolChapel
|
||||
}
|
||||
church := domain.Church{
|
||||
ID: id, Name: strings.TrimSpace(r.FormValue("name")),
|
||||
ShortName: strings.TrimSpace(r.FormValue("short_name")),
|
||||
Symbol: symbol, ColorHex: strings.TrimSpace(r.FormValue("color_hex")),
|
||||
Address: strings.TrimSpace(r.FormValue("address")),
|
||||
SortIndex: parseInt(r.FormValue("sort_index"), 0),
|
||||
Notes: strings.TrimSpace(r.FormValue("notes")),
|
||||
}
|
||||
if church.ColorHex == "" {
|
||||
church.ColorHex = "#4E6E5D"
|
||||
}
|
||||
if err := s.store.UpsertChurch(r.Context(), tenant.ID, church); err != nil {
|
||||
s.setFlash(w, "Die Kirche konnte nicht gespeichert werden: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/admin/churches?edit="+id)
|
||||
return
|
||||
}
|
||||
s.setFlash(w, "Kirche gespeichert.", "success")
|
||||
s.redirect(w, r, "/admin/churches?edit="+id)
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminChurchDelete(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.redirect(w, r, "/admin/churches")
|
||||
return
|
||||
}
|
||||
id := strings.TrimSpace(r.FormValue("id"))
|
||||
if err := s.store.DeleteChurch(r.Context(), tenant.ID, id); err != nil {
|
||||
s.setFlash(w, "Die Kirche konnte nicht gelöscht werden: "+err.Error(), "error")
|
||||
} else {
|
||||
s.setFlash(w, "Kirche sowie zugehörige Vorlagen und Gottesdienste gelöscht.", "success")
|
||||
}
|
||||
s.redirect(w, r, "/admin/churches")
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"lektorenplan/store"
|
||||
)
|
||||
|
||||
func (s *Server) handleLoginGet(w http.ResponseWriter, r *http.Request) {
|
||||
if userFrom(r) != nil {
|
||||
s.redirect(w, r, "/plan")
|
||||
return
|
||||
}
|
||||
data := s.baseView(w, r, "Anmelden", "")
|
||||
data.Data = struct {
|
||||
Next string
|
||||
}{Next: safeNext(r.URL.Query().Get("next"))}
|
||||
s.renderPage(w, r, "login", data)
|
||||
}
|
||||
|
||||
func (s *Server) handleLoginPost(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
s.setFlash(w, "Das Formular konnte nicht gelesen werden.", "error")
|
||||
s.redirect(w, r, "/login")
|
||||
return
|
||||
}
|
||||
username := strings.TrimSpace(r.FormValue("username"))
|
||||
password := r.FormValue("password")
|
||||
user, err := s.store.Authenticate(r.Context(), username, password)
|
||||
if err != nil {
|
||||
s.setFlash(w, err.Error(), "error")
|
||||
s.redirect(w, r, "/login")
|
||||
return
|
||||
}
|
||||
session, token, err := s.store.CreateSession(r.Context(), user.ID, s.sessionTTL)
|
||||
if err != nil {
|
||||
s.setFlash(w, "Die Sitzung konnte nicht erstellt werden.", "error")
|
||||
s.redirect(w, r, "/login")
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: sessionCookie, Value: token, Path: "/", HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode, Secure: s.opts.SecureCookies,
|
||||
MaxAge: int(s.sessionTTL.Seconds()),
|
||||
})
|
||||
_ = session
|
||||
s.setFlash(w, "Willkommen zurück, "+user.DisplayName+".", "success")
|
||||
next := safeNext(r.FormValue("next"))
|
||||
s.redirect(w, r, next)
|
||||
}
|
||||
|
||||
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if cookie, err := r.Cookie(sessionCookie); err == nil {
|
||||
_ = s.store.DeleteSessionByToken(r.Context(), cookie.Value)
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: sessionCookie, Value: "", Path: "/", MaxAge: -1, HttpOnly: true})
|
||||
s.redirect(w, r, "/login")
|
||||
}
|
||||
|
||||
func (s *Server) handleRoot(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
s.redirect(w, r, "/plan")
|
||||
}
|
||||
|
||||
func (s *Server) handleSwitchTenant(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
target := strings.TrimSpace(r.URL.Query().Get("tid"))
|
||||
if target == "" || !s.store.CanAccessTenant(r.Context(), user, target) {
|
||||
s.setFlash(w, "Dieser Mandant ist für Ihr Konto nicht freigegeben.", "error")
|
||||
s.redirectBack(w, r, "/plan")
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: tenantCookie, Value: target, Path: "/", HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode, Secure: s.opts.SecureCookies,
|
||||
MaxAge: 365 * 24 * 3600,
|
||||
})
|
||||
s.redirectBack(w, r, "/plan")
|
||||
}
|
||||
|
||||
func safeNext(value string) string {
|
||||
if value == "" {
|
||||
return "/plan"
|
||||
}
|
||||
parsed, err := url.Parse(value)
|
||||
if err != nil || parsed.IsAbs() || !strings.HasPrefix(parsed.Path, "/") {
|
||||
return "/plan"
|
||||
}
|
||||
return parsed.RequestURI()
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
"lektorenplan/store"
|
||||
)
|
||||
|
||||
type exchangePageData struct {
|
||||
Range domain.DayRange
|
||||
Start string
|
||||
End string
|
||||
Scope store.ExchangeScope
|
||||
Resource store.ExchangeSummary
|
||||
Preview *store.ExchangeSummary
|
||||
PreviewToken string
|
||||
FileName string
|
||||
Replace bool
|
||||
CanEdit bool
|
||||
LastImport string
|
||||
}
|
||||
|
||||
func (s *Server) handleExchange(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.renderNoTenant(w, r)
|
||||
return
|
||||
}
|
||||
rng := s.rangeFromRequest(r)
|
||||
resources, err := s.store.ExportResources(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Austausch", err.Error())
|
||||
return
|
||||
}
|
||||
scope := store.ExchangeScope(strings.TrimSpace(r.URL.Query().Get("scope")))
|
||||
if scope != store.ScopePlan {
|
||||
scope = store.ScopeResources
|
||||
}
|
||||
page := exchangePageData{
|
||||
Range: rng, Start: domain.Key(rng.Start), End: domain.Key(rng.End),
|
||||
Scope: scope, Resource: resources.Summary(),
|
||||
CanEdit: s.store.CanEditTenant(r.Context(), user, tenant.ID),
|
||||
}
|
||||
data := s.baseView(w, r, "Austausch", "exchange")
|
||||
data.Data = page
|
||||
s.renderPage(w, r, "exchange", data)
|
||||
}
|
||||
|
||||
func (s *Server) handleExport(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.renderNoTenant(w, r)
|
||||
return
|
||||
}
|
||||
scope := store.ExchangeScope(strings.TrimSpace(r.URL.Query().Get("scope")))
|
||||
rng := s.rangeFromRequest(r)
|
||||
var (
|
||||
exchange store.PlanExchange
|
||||
err error
|
||||
)
|
||||
if scope == store.ScopeResources {
|
||||
exchange, err = s.store.ExportResources(r.Context(), tenant.ID)
|
||||
} else {
|
||||
scope = store.ScopePlan
|
||||
exchange, err = s.store.ExportPlan(r.Context(), tenant.ID, rng)
|
||||
}
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Export", err.Error())
|
||||
return
|
||||
}
|
||||
body, err := json.Marshal(exchange)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Export", err.Error())
|
||||
return
|
||||
}
|
||||
name := "LektorenPlan-" + tenant.Slug + "-" + string(scope) + "-" + domain.Key(domain.Today()) + ".json"
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="`+name+`"`)
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
|
||||
func (s *Server) handleImport(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.renderNoTenant(w, r)
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(r.FormValue("confirm")) == "1" {
|
||||
encoded := strings.TrimSpace(r.FormValue("payload"))
|
||||
payload, err := base64.RawURLEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
s.setFlash(w, "Die Importdaten konnten nicht gelesen werden.", "error")
|
||||
s.redirect(w, r, "/exchange")
|
||||
return
|
||||
}
|
||||
exchange, err := store.ParseExchange(payload)
|
||||
if err != nil {
|
||||
s.setFlash(w, err.Error(), "error")
|
||||
s.redirect(w, r, "/exchange")
|
||||
return
|
||||
}
|
||||
replace := r.FormValue("replace") == "1" || r.FormValue("replace") == "on"
|
||||
summary, err := s.store.ApplyExchange(r.Context(), tenant.ID, exchange, replace)
|
||||
if err != nil {
|
||||
s.setFlash(w, "Der Import ist fehlgeschlagen: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/exchange")
|
||||
return
|
||||
}
|
||||
_ = s.store.SetTenantSetting(r.Context(), tenant.ID, "lastExchangeImport", time.Now().UTC().Format(time.RFC3339))
|
||||
s.setFlash(w, importMessage(summary), "success")
|
||||
s.redirect(w, r, "/exchange")
|
||||
return
|
||||
}
|
||||
|
||||
file, header, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
s.setFlash(w, "Bitte eine JSON-Datei auswählen.", "error")
|
||||
s.redirect(w, r, "/exchange")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(file, 32<<20))
|
||||
if err != nil {
|
||||
s.setFlash(w, "Die Datei konnte nicht gelesen werden.", "error")
|
||||
s.redirect(w, r, "/exchange")
|
||||
return
|
||||
}
|
||||
exchange, err := store.ParseExchange(data)
|
||||
if err != nil {
|
||||
s.setFlash(w, err.Error(), "error")
|
||||
s.redirect(w, r, "/exchange")
|
||||
return
|
||||
}
|
||||
summary := exchange.Summary()
|
||||
rng := s.rangeFromRequest(r)
|
||||
if exchange.Range.Start != "" && exchange.Range.End != "" {
|
||||
if parsed, ok := domain.DateFromKey(exchange.Range.Start); ok {
|
||||
rng.Start = parsed
|
||||
}
|
||||
if parsed, ok := domain.DateFromKey(exchange.Range.End); ok {
|
||||
rng.End = parsed
|
||||
}
|
||||
}
|
||||
page := exchangePageData{
|
||||
Range: rng, Start: domain.Key(rng.Start), End: domain.Key(rng.End),
|
||||
Scope: exchange.Scope, Resource: summary, Preview: &summary,
|
||||
PreviewToken: base64.RawURLEncoding.EncodeToString(data),
|
||||
FileName: header.Filename,
|
||||
Replace: r.FormValue("replace") == "1" || r.FormValue("replace") == "on",
|
||||
CanEdit: s.store.CanEditTenant(r.Context(), user, tenant.ID),
|
||||
}
|
||||
view := s.baseView(w, r, "Import prüfen", "exchange")
|
||||
view.Data = page
|
||||
s.renderPage(w, r, "exchange", view)
|
||||
}
|
||||
|
||||
func importMessage(summary store.ExchangeSummary) string {
|
||||
parts := []string{
|
||||
plural(summary.Churches, "Kirche", "Kirchen"),
|
||||
plural(summary.People, "Person", "Personen"),
|
||||
plural(summary.Templates, "Vorlage", "Vorlagen"),
|
||||
plural(summary.Services, "Gottesdienst", "Gottesdienste"),
|
||||
plural(summary.Assignments, "Einteilung", "Einteilungen"),
|
||||
}
|
||||
return "Import abgeschlossen: " + strings.Join(parts, ", ") + "."
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
"lektorenplan/liturgy"
|
||||
"lektorenplan/store"
|
||||
)
|
||||
|
||||
type liturgyPageData struct {
|
||||
Year int
|
||||
Month int
|
||||
Days []domain.LiturgicalDay
|
||||
Years []int
|
||||
Source string
|
||||
LastSync string
|
||||
CanEdit bool
|
||||
Total int
|
||||
Feasts int
|
||||
Obligations int
|
||||
Stored int
|
||||
LocalOnly bool
|
||||
}
|
||||
|
||||
func (s *Server) handleLiturgy(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
year := parseInt(r.URL.Query().Get("year"), domain.Year(domain.Today()))
|
||||
if year < 1900 || year > 2200 {
|
||||
year = domain.Year(domain.Today())
|
||||
}
|
||||
month := parseInt(r.URL.Query().Get("month"), 0)
|
||||
if month < 0 || month > 12 {
|
||||
month = 0
|
||||
}
|
||||
rng := domain.YearRange(year)
|
||||
stored, err := s.store.LiturgicalDays(r.Context(), rng)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Liturgischer Kalender", err.Error())
|
||||
return
|
||||
}
|
||||
storedCount := len(stored)
|
||||
days := liturgy.FillLocalGaps(year, stored)
|
||||
if month > 0 {
|
||||
start := domain.MustDate(domain.KeyYMD(year, month, 1))
|
||||
end := domain.EndOfMonth(start)
|
||||
var filtered []domain.LiturgicalDay
|
||||
for _, day := range days {
|
||||
if !day.Date.Before(start) && !day.Date.After(end) {
|
||||
filtered = append(filtered, day)
|
||||
}
|
||||
}
|
||||
days = filtered
|
||||
}
|
||||
years, err := s.store.LiturgicalYears(r.Context())
|
||||
if err != nil {
|
||||
years = nil
|
||||
}
|
||||
seenYears := map[int]bool{}
|
||||
for _, item := range years {
|
||||
seenYears[item] = true
|
||||
}
|
||||
for _, item := range liturgy.SnapshotYears() {
|
||||
if !seenYears[item] {
|
||||
years = append(years, item)
|
||||
seenYears[item] = true
|
||||
}
|
||||
}
|
||||
for item := year - 1; item <= year+1; item++ {
|
||||
if !seenYears[item] {
|
||||
years = append(years, item)
|
||||
seenYears[item] = true
|
||||
}
|
||||
}
|
||||
sort.Ints(years)
|
||||
feasts, obligations := 0, 0
|
||||
for _, day := range days {
|
||||
if day.IsFeast() {
|
||||
feasts++
|
||||
}
|
||||
if day.IsObligation {
|
||||
obligations++
|
||||
}
|
||||
}
|
||||
page := liturgyPageData{
|
||||
Year: year, Month: month, Days: days, Years: years,
|
||||
Source: liturgy.SourceLabel, LastSync: s.store.Setting(r.Context(), "lastLiturgicalSync"),
|
||||
CanEdit: s.store.CanEditTenant(r.Context(), user, tenant.ID),
|
||||
Total: len(days), Feasts: feasts, Obligations: obligations,
|
||||
Stored: storedCount, LocalOnly: storedCount == 0,
|
||||
}
|
||||
data := s.baseView(w, r, "Liturgischer Kalender", "liturgy")
|
||||
data.Data = page
|
||||
s.renderPage(w, r, "liturgy", data)
|
||||
}
|
||||
|
||||
func (s *Server) handleLiturgySync(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
year := parseInt(r.FormValue("year"), domain.Year(domain.Today()))
|
||||
if year < 1900 || year > 2200 {
|
||||
year = domain.Year(domain.Today())
|
||||
}
|
||||
api := liturgy.NewAPI()
|
||||
if diocese := strings.TrimSpace(s.store.Setting(r.Context(), "diocese")); diocese != "" {
|
||||
api.Diocese = diocese
|
||||
}
|
||||
days, err := api.Fetch(r.Context(), year)
|
||||
if err != nil {
|
||||
fallback := liturgy.LocalDays(domain.YearRange(year))
|
||||
if storeErr := s.store.ReplaceLiturgicalYear(r.Context(), year, fallback); storeErr != nil {
|
||||
s.setFlash(w, "Der Kalender konnte weder geladen noch lokal erzeugt werden: "+storeErr.Error(), "error")
|
||||
s.redirect(w, r, "/liturgy?year="+strconv.Itoa(year))
|
||||
return
|
||||
}
|
||||
s.setFlash(w, fmt.Sprintf("Online-Aktualisierung fehlgeschlagen (%v). Für %d wurden %d Tage aus der lokalen Berechnung gespeichert.",
|
||||
err, year, len(fallback)), "info")
|
||||
s.redirect(w, r, "/liturgy?year="+strconv.Itoa(year))
|
||||
return
|
||||
}
|
||||
days = liturgy.FillLocalGaps(year, days)
|
||||
if err := s.store.ReplaceLiturgicalYear(r.Context(), year, days); err != nil {
|
||||
s.setFlash(w, "Die Kalenderdaten konnten nicht gespeichert werden: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/liturgy?year="+strconv.Itoa(year))
|
||||
return
|
||||
}
|
||||
_ = s.store.SetSetting(r.Context(), "lastLiturgicalSync", time.Now().UTC().Format(time.RFC3339))
|
||||
_ = s.store.SetSetting(r.Context(), "lastLiturgicalYear", strconv.Itoa(year))
|
||||
s.setFlash(w, fmt.Sprintf("Liturgischer Kalender für %d mit %d Tagen aktualisiert. %s", year, len(days), liturgy.SourceLabel), "success")
|
||||
s.redirect(w, r, "/liturgy?year="+strconv.Itoa(year))
|
||||
}
|
||||
|
||||
// SyncLiturgyYear performs the daily background refresh used by main.
|
||||
func SyncLiturgyYear(ctx context.Context, st *store.Store, year int) error {
|
||||
api := liturgy.NewAPI()
|
||||
if diocese := strings.TrimSpace(st.Setting(ctx, "diocese")); diocese != "" {
|
||||
api.Diocese = diocese
|
||||
}
|
||||
days, err := api.Fetch(ctx, year)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
days = liturgy.FillLocalGaps(year, days)
|
||||
if err := st.ReplaceLiturgicalYear(ctx, year, days); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = st.SetSetting(ctx, "lastLiturgicalSync", time.Now().UTC().Format(time.RFC3339))
|
||||
_ = st.SetSetting(ctx, "lastLiturgicalYear", strconv.Itoa(year))
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"lektorenplan/domain"
|
||||
"lektorenplan/pdf"
|
||||
"lektorenplan/store"
|
||||
)
|
||||
|
||||
func (s *Server) handlePDF(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.renderNoTenant(w, r)
|
||||
return
|
||||
}
|
||||
rng := s.rangeFromRequest(r)
|
||||
rows, err := s.store.PlanRows(r.Context(), tenant.ID, rng)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "PDF", err.Error())
|
||||
return
|
||||
}
|
||||
churches, err := s.store.Churches(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "PDF", err.Error())
|
||||
return
|
||||
}
|
||||
people, err := s.store.People(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "PDF", err.Error())
|
||||
return
|
||||
}
|
||||
variant := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("variant")))
|
||||
options := pdf.Options{
|
||||
TenantName: tenant.Name, Diocese: s.opts.Diocese,
|
||||
GeneratedAt: domain.Today(),
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
if variant == "compact" || variant == "liste" {
|
||||
variant = "kompakt"
|
||||
if err := pdf.CompactPlan(&buffer, rng, rows, people, options); err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "PDF", err.Error())
|
||||
return
|
||||
}
|
||||
} else {
|
||||
variant = "plan"
|
||||
if err := pdf.FullPlan(&buffer, rng, rows, churches, people, options); err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "PDF", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
name := fmt.Sprintf("LektorenPlan-%s-%s-%s.pdf", tenant.Slug, variant, domain.Key(rng.Start))
|
||||
disposition := "inline"
|
||||
if r.URL.Query().Get("download") == "1" {
|
||||
disposition = "attachment"
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/pdf")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`%s; filename="%s"`, disposition, name))
|
||||
w.Header().Set("Content-Length", fmt.Sprintf("%d", buffer.Len()))
|
||||
_, _ = w.Write(buffer.Bytes())
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"lektorenplan/domain"
|
||||
"lektorenplan/store"
|
||||
)
|
||||
|
||||
type planPageData struct {
|
||||
Range domain.DayRange
|
||||
Start string
|
||||
End string
|
||||
Rows []domain.DayPlanRow
|
||||
Churches []domain.Church
|
||||
People map[string]domain.Person
|
||||
Stats domain.RangeStatistics
|
||||
CanEdit bool
|
||||
PrevStart string
|
||||
PrevEnd string
|
||||
NextStart string
|
||||
NextEnd string
|
||||
PresetFourStart string
|
||||
PresetFourEnd string
|
||||
}
|
||||
|
||||
func flattenRows(rows []domain.DayPlanRow) ([]domain.ServiceOccurrence, []domain.Assignment) {
|
||||
var services []domain.ServiceOccurrence
|
||||
var assignments []domain.Assignment
|
||||
for _, row := range rows {
|
||||
for _, service := range row.Services {
|
||||
services = append(services, service.Service)
|
||||
assignments = append(assignments, service.Assignments...)
|
||||
}
|
||||
}
|
||||
return services, assignments
|
||||
}
|
||||
|
||||
func (s *Server) handlePlan(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.renderNoTenant(w, r)
|
||||
return
|
||||
}
|
||||
rng := s.rangeFromRequest(r)
|
||||
rows, err := s.store.PlanRows(r.Context(), tenant.ID, rng)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Planung", err.Error())
|
||||
return
|
||||
}
|
||||
churches, err := s.store.Churches(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Kirchen", err.Error())
|
||||
return
|
||||
}
|
||||
peopleList, err := s.store.People(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Team", err.Error())
|
||||
return
|
||||
}
|
||||
absences, err := s.store.Absences(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Abwesenheiten", err.Error())
|
||||
return
|
||||
}
|
||||
people := make(map[string]domain.Person, len(peopleList))
|
||||
for _, person := range peopleList {
|
||||
people[person.ID] = person
|
||||
}
|
||||
services, assignments := flattenRows(rows)
|
||||
stats := domain.ComputeStatistics(rng, services, assignments, peopleList, churches, absences)
|
||||
|
||||
prev := domain.MonthRange(domain.AddingMonths(-1, rng.Start))
|
||||
next := domain.MonthRange(domain.AddingMonths(1, rng.Start))
|
||||
fourWeeks := domain.DaysRange(28, domain.Today())
|
||||
|
||||
data := s.baseView(w, r, "Gottesdienstplan", "plan")
|
||||
data.Data = planPageData{
|
||||
Range: rng, Start: domain.Key(rng.Start), End: domain.Key(rng.End),
|
||||
Rows: rows, Churches: churches, People: people, Stats: stats,
|
||||
CanEdit: s.store.CanEditTenant(r.Context(), user, tenant.ID),
|
||||
PrevStart: domain.Key(prev.Start), PrevEnd: domain.Key(prev.End),
|
||||
NextStart: domain.Key(next.Start), NextEnd: domain.Key(next.End),
|
||||
PresetFourStart: domain.Key(fourWeeks.Start), PresetFourEnd: domain.Key(fourWeeks.End),
|
||||
}
|
||||
s.renderPage(w, r, "plan", data)
|
||||
}
|
||||
|
||||
func (s *Server) handleGenerateServices(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.redirect(w, r, "/plan")
|
||||
return
|
||||
}
|
||||
rng := formRange(r)
|
||||
created, err := s.store.GenerateServices(r.Context(), tenant.ID, rng, true)
|
||||
if err != nil {
|
||||
s.setFlash(w, "Gottesdienste konnten nicht erzeugt werden: "+err.Error(), "error")
|
||||
} else if created == 0 {
|
||||
s.setFlash(w, "Alle regelmäßigen Gottesdienste im Zeitraum sind bereits vorhanden.", "info")
|
||||
} else {
|
||||
s.setFlash(w, fmt.Sprintf("%d Gottesdienste aus der Gottesdienstordnung erzeugt.", created), "success")
|
||||
}
|
||||
s.redirect(w, r, "/plan?start="+domain.Key(rng.Start)+"&end="+domain.Key(rng.End))
|
||||
}
|
||||
|
||||
func (s *Server) handleAutoPlan(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.redirect(w, r, "/plan")
|
||||
return
|
||||
}
|
||||
rng := formRange(r)
|
||||
options := s.planningOptions(r, tenant.ID)
|
||||
options.ReplaceExisting = r.FormValue("replace") == "1" || r.FormValue("replace") == "on"
|
||||
|
||||
services, err := s.store.Services(r.Context(), tenant.ID, rng)
|
||||
if err != nil {
|
||||
s.setFlash(w, "Planung fehlgeschlagen: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/plan")
|
||||
return
|
||||
}
|
||||
if len(services) == 0 {
|
||||
s.setFlash(w, "Für den Zeitraum sind keine Gottesdienste vorhanden. Bitte zuerst Termine erzeugen.", "info")
|
||||
s.redirect(w, r, "/plan?start="+domain.Key(rng.Start)+"&end="+domain.Key(rng.End))
|
||||
return
|
||||
}
|
||||
people, err := s.store.People(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.setFlash(w, "Planung fehlgeschlagen: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/plan")
|
||||
return
|
||||
}
|
||||
absences, err := s.store.Absences(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.setFlash(w, "Planung fehlgeschlagen: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/plan")
|
||||
return
|
||||
}
|
||||
churches, err := s.store.Churches(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.setFlash(w, "Planung fehlgeschlagen: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/plan")
|
||||
return
|
||||
}
|
||||
existing, err := s.store.Assignments(r.Context(), tenant.ID, rng)
|
||||
if err != nil {
|
||||
s.setFlash(w, "Planung fehlgeschlagen: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/plan")
|
||||
return
|
||||
}
|
||||
planner := domain.ServicePlanner{
|
||||
People: people, Absences: absences, Services: services,
|
||||
ExistingAssignments: existing, Churches: churches, Options: options,
|
||||
}
|
||||
result := planner.Plan()
|
||||
if err := s.store.SavePlan(r.Context(), tenant.ID, result.Assignments, rng, options.ReplaceExisting); err != nil {
|
||||
s.setFlash(w, "Der Plan konnte nicht gespeichert werden: "+err.Error(), "error")
|
||||
} else {
|
||||
kind := "success"
|
||||
if len(result.Unfilled) > 0 {
|
||||
kind = "info"
|
||||
}
|
||||
s.setFlash(w, result.Message, kind)
|
||||
}
|
||||
s.redirect(w, r, "/plan?start="+domain.Key(rng.Start)+"&end="+domain.Key(rng.End))
|
||||
}
|
||||
|
||||
func formRange(r *http.Request) domain.DayRange {
|
||||
start, startOK := domain.DateFromKey(strings.TrimSpace(r.FormValue("start")))
|
||||
end, endOK := domain.DateFromKey(strings.TrimSpace(r.FormValue("end")))
|
||||
today := domain.Today()
|
||||
if !startOK {
|
||||
start = domain.StartOfMonth(today)
|
||||
}
|
||||
if !endOK {
|
||||
end = domain.EndOfMonth(start)
|
||||
}
|
||||
if end.Before(start) {
|
||||
start, end = end, start
|
||||
}
|
||||
if domain.DaysBetween(start, end) > 400 {
|
||||
end = domain.AddingDays(400, start)
|
||||
}
|
||||
return domain.NewDayRange(start, end)
|
||||
}
|
||||
|
||||
func (s *Server) renderNoTenant(w http.ResponseWriter, r *http.Request) {
|
||||
data := s.baseView(w, r, "Kein Mandant", "")
|
||||
data.Data = struct {
|
||||
IsAdmin bool
|
||||
}{IsAdmin: data.IsAdmin}
|
||||
s.renderPage(w, r, "no_tenant", data)
|
||||
}
|
||||
|
||||
func parseInt(value string, fallback int) int {
|
||||
parsed, err := strconv.Atoi(strings.TrimSpace(value))
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
"lektorenplan/store"
|
||||
)
|
||||
|
||||
type viewData struct {
|
||||
Title string
|
||||
Active string
|
||||
User *store.User
|
||||
Session *store.Session
|
||||
Tenant *store.Tenant
|
||||
Tenants []store.Tenant
|
||||
CSRF string
|
||||
Flash string
|
||||
FlashKind string
|
||||
IsEditor bool
|
||||
IsAdmin bool
|
||||
Version string
|
||||
DemoMode bool
|
||||
Data any
|
||||
}
|
||||
|
||||
func (s *Server) baseView(w http.ResponseWriter, r *http.Request, title, active string) viewData {
|
||||
user := userFrom(r)
|
||||
session := sessionFrom(r)
|
||||
tenant := tenantFrom(r)
|
||||
flash, kind := s.popFlash(w, r)
|
||||
data := viewData{
|
||||
Title: title, Active: active, User: user, Session: session, Tenant: tenant,
|
||||
Flash: flash, FlashKind: kind, Version: s.opts.Version, DemoMode: s.opts.DemoMode,
|
||||
}
|
||||
if session != nil {
|
||||
data.CSRF = session.CSRFToken
|
||||
}
|
||||
if user != nil {
|
||||
data.IsAdmin = user.Role.IsAdmin()
|
||||
tenants, _ := s.store.TenantsForUser(r.Context(), user)
|
||||
data.Tenants = tenants
|
||||
if tenant != nil {
|
||||
data.IsEditor = s.store.CanEditTenant(r.Context(), user, tenant.ID)
|
||||
}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func (s *Server) render(w http.ResponseWriter, r *http.Request, status int, name string, data viewData) {
|
||||
t, ok := s.views[name]
|
||||
if !ok {
|
||||
http.Error(w, "template missing: "+name, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// Render into a buffer first: a template error must not leave a
|
||||
// half-written 200 response behind.
|
||||
var buf bytes.Buffer
|
||||
if err := t.ExecuteTemplate(&buf, "layout", data); err != nil {
|
||||
log.Printf("render %s: %v", name, err)
|
||||
http.Error(w, "Die Seite konnte nicht erstellt werden.", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
if _, err := buf.WriteTo(w); err != nil {
|
||||
log.Printf("write %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) renderPage(w http.ResponseWriter, r *http.Request, name string, data viewData) {
|
||||
s.render(w, r, http.StatusOK, name, data)
|
||||
}
|
||||
|
||||
func (s *Server) renderError(w http.ResponseWriter, r *http.Request, status int, title, message string) {
|
||||
data := s.baseView(w, r, title, "")
|
||||
data.Data = struct {
|
||||
Title string
|
||||
Message string
|
||||
Status int
|
||||
}{title, message, status}
|
||||
s.render(w, r, status, "error", data)
|
||||
}
|
||||
|
||||
func templateFunctions() template.FuncMap {
|
||||
return template.FuncMap{
|
||||
"longDate": domain.LongString,
|
||||
"mediumDate": domain.MediumString,
|
||||
"shortDate": dayMonthYear,
|
||||
"isoDate": domain.Key,
|
||||
"isoDatePtr": func(value *time.Time) string {
|
||||
if value == nil {
|
||||
return ""
|
||||
}
|
||||
return domain.Key(*value)
|
||||
},
|
||||
"dayNumber": domain.DayNumber,
|
||||
"monthNumber": domain.Month,
|
||||
"yearOf": domain.Year,
|
||||
"monthName": domain.MonthName,
|
||||
"monthNumberName": func(number int) string {
|
||||
if number < 1 || number > 12 {
|
||||
return ""
|
||||
}
|
||||
return domain.MonthName(time.Date(2024, time.Month(number), 1, 12, 0, 0, 0, time.UTC))
|
||||
},
|
||||
"shortMonthNumber": func(number int) string {
|
||||
if number < 1 || number > 12 {
|
||||
return ""
|
||||
}
|
||||
return domain.ShortMonthName(time.Date(2024, time.Month(number), 1, 12, 0, 0, 0, time.UTC))
|
||||
},
|
||||
"shortMonth": domain.ShortMonthName,
|
||||
"weekdayName": domain.WeekdayName,
|
||||
"shortWeekday": domain.ShortWeekdayName,
|
||||
"weekdayNumberName": func(number int) string {
|
||||
for _, option := range weekdays {
|
||||
if option.Number == number {
|
||||
return option.Name
|
||||
}
|
||||
}
|
||||
return "?"
|
||||
},
|
||||
"upperWeekday": func(t time.Time) string { return strings.ToUpper(domain.ShortWeekdayName(t)) },
|
||||
"addDays": func(days int, t time.Time) time.Time { return domain.AddingDays(days, t) },
|
||||
"addMonths": domain.AddingMonths,
|
||||
"rangeTitle": func(r domain.DayRange) string { return r.Title() },
|
||||
"rangeShort": func(r domain.DayRange) string { return r.ShortTitle() },
|
||||
"rangeLong": func(r domain.DayRange) string { return r.LongTitle() },
|
||||
"dayCount": func(r domain.DayRange) int { return r.DayCount() },
|
||||
"timeLabel": domain.TimeString,
|
||||
"roleTitle": func(role domain.Role) string { return role.Title() },
|
||||
"rolePlural": func(role domain.Role) string { return role.Plural() },
|
||||
"roleShort": func(role domain.Role) string { return role.ShortCode() },
|
||||
"userRole": func(role store.UserRole) string { return store.UserRoleTitle(role) },
|
||||
"dioceses": func() any { return dioceseOptions },
|
||||
"percent": percentLabel,
|
||||
"coverage": func(stats domain.RangeStatistics) string { return percentLabel(stats.CoverageRate()) },
|
||||
"preferencePct": func(stats domain.RangeStatistics) string { return percentLabel(stats.PreferenceRate()) },
|
||||
"initial": initial,
|
||||
"initials": initials,
|
||||
"deref": derefString,
|
||||
"derefTime": func(value *time.Time) time.Time {
|
||||
if value == nil {
|
||||
return time.Time{}
|
||||
}
|
||||
return *value
|
||||
},
|
||||
"formatFloat": func(value float64) string {
|
||||
return strings.Replace(strconv.FormatFloat(value, 'f', 1, 64), ".", ",", 1)
|
||||
},
|
||||
"setting": sSetting,
|
||||
"safe": func(value string) template.HTML { return template.HTML(value) },
|
||||
"churchGlyph": churchGlyph,
|
||||
"feastGlyph": feastGlyph,
|
||||
"icon": iconSVG,
|
||||
"barHeight": barHeight,
|
||||
"percentage": percentageWidth,
|
||||
"ratio": func(value, max int) float64 {
|
||||
if max <= 0 || value <= 0 {
|
||||
return 0
|
||||
}
|
||||
return float64(value) / float64(max)
|
||||
},
|
||||
"plural": plural,
|
||||
"abs": func(value int) int {
|
||||
if value < 0 {
|
||||
return -value
|
||||
}
|
||||
return value
|
||||
},
|
||||
"join": strings.Join,
|
||||
"trim": strings.TrimSpace,
|
||||
"lower": strings.ToLower,
|
||||
"eqs": func(a, b string) bool { return a == b },
|
||||
"containsInt": domain.IntContains,
|
||||
"containsString": domain.StringContains,
|
||||
"hasRole": func(person domain.Person, role domain.Role) bool { return person.CanFill(role) },
|
||||
"roleChecked": func(person domain.Person, role string) bool {
|
||||
return person.CanFill(domain.Role(role))
|
||||
},
|
||||
"monthLabel": func(key string) string { return monthLabel(key) },
|
||||
"add": func(a, b int) int { return a + b },
|
||||
"sub": func(a, b int) int { return a - b },
|
||||
"seq": func(from, to int) []int {
|
||||
if to < from {
|
||||
return nil
|
||||
}
|
||||
out := make([]int, 0, to-from+1)
|
||||
for i := from; i <= to; i++ {
|
||||
out = append(out, i)
|
||||
}
|
||||
return out
|
||||
},
|
||||
"liturgicalColor": func(day *domain.LiturgicalDay) string {
|
||||
if day == nil {
|
||||
return "#C2A14D"
|
||||
}
|
||||
return day.ColorHex()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// sSetting is a stub placeholder kept out of templates that need context; the
|
||||
// actual values are passed in page data.
|
||||
func sSetting(key string) string { return "" }
|
||||
|
||||
func dayMonthYear(t time.Time) string {
|
||||
return fmt.Sprintf("%02d.%02d.%d", domain.DayNumber(t), domain.Month(t), domain.Year(t))
|
||||
}
|
||||
|
||||
func monthLabel(key string) string {
|
||||
parts := strings.Split(key, "-")
|
||||
if len(parts) < 2 {
|
||||
return key
|
||||
}
|
||||
date, ok := domain.DateFromKey(key + "-01")
|
||||
if !ok {
|
||||
return key
|
||||
}
|
||||
return domain.MonthName(date) + " " + parts[0]
|
||||
}
|
||||
|
||||
func percentLabel(value float64) string {
|
||||
if math.IsNaN(value) || math.IsInf(value, 0) {
|
||||
return "0 %"
|
||||
}
|
||||
return fmt.Sprintf("%.0f %%", value*100)
|
||||
}
|
||||
|
||||
func percentageWidth(value float64) string {
|
||||
if math.IsNaN(value) || math.IsInf(value, 0) || value < 0 {
|
||||
value = 0
|
||||
}
|
||||
if value > 1 {
|
||||
value = 1
|
||||
}
|
||||
return fmt.Sprintf("%.1f%%", value*100)
|
||||
}
|
||||
|
||||
func barHeight(value, maxValue int) string {
|
||||
if maxValue <= 0 || value <= 0 {
|
||||
return "2px"
|
||||
}
|
||||
height := 4 + int(90*float64(value)/float64(maxValue))
|
||||
return fmt.Sprintf("%dpx", height)
|
||||
}
|
||||
|
||||
func initial(name string) string {
|
||||
runes := []rune(strings.TrimSpace(name))
|
||||
if len(runes) == 0 {
|
||||
return "?"
|
||||
}
|
||||
return strings.ToUpper(string(runes[0]))
|
||||
}
|
||||
|
||||
func initials(first, last string) string {
|
||||
out := ""
|
||||
if runes := []rune(strings.TrimSpace(first)); len(runes) > 0 {
|
||||
out += strings.ToUpper(string(runes[0]))
|
||||
}
|
||||
if runes := []rune(strings.TrimSpace(last)); len(runes) > 0 {
|
||||
out += strings.ToUpper(string(runes[0]))
|
||||
}
|
||||
if out == "" {
|
||||
return "?"
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func derefString(value *string) string {
|
||||
if value == nil {
|
||||
return ""
|
||||
}
|
||||
return *value
|
||||
}
|
||||
|
||||
func plural(count int, singular, pluralForm string) string {
|
||||
if count == 1 {
|
||||
return fmt.Sprintf("%d %s", count, singular)
|
||||
}
|
||||
return fmt.Sprintf("%d %s", count, pluralForm)
|
||||
}
|
||||
|
||||
// Church glyphs -------------------------------------------------------------
|
||||
|
||||
var glyphBodies = map[string]string{
|
||||
"basilica": `
|
||||
<path d="M42 42 L60 28 L78 42 L78 75 L42 75 Z" fill="currentColor" fill-opacity=".055"/>
|
||||
<path d="M39 43 L60 26 L81 43"/>
|
||||
<path d="M27 55 L27 75 L42 75 L42 50 L32 47"/>
|
||||
<path d="M78 50 L78 75 L93 75 L93 55 L83 59"/>
|
||||
<path d="M88 26 L99 26 L99 75 L88 75 Z" fill="currentColor" fill-opacity=".055"/>
|
||||
<path d="M86 27 L93.5 12 L101 27"/>
|
||||
<path d="M55 75 L55 62 Q60 54 65 62 L65 75"/>
|
||||
<path d="M48 68 L48 58 Q51 53 54 58 L54 68"/>
|
||||
<path d="M72 68 L72 58 Q75 53 78 58 L78 68"/>
|
||||
<path d="M93.5 12 L93.5 4 M90.5 7 L96.5 7"/>`,
|
||||
"gothic": `
|
||||
<path d="M36 75 L36 44 Q46 37 60 35 Q74 37 84 44 L84 75 Z" fill="currentColor" fill-opacity=".055"/>
|
||||
<path d="M31 45 L60 8 L89 45"/>
|
||||
<path d="M88 29 L101 29 L101 75 L88 75"/>
|
||||
<path d="M85 30 L94.5 10 L104 30"/>
|
||||
<path d="M54 75 L54 57 Q60 48 66 57 L66 75"/>
|
||||
<circle cx="60" cy="54" r="10"/>
|
||||
<path d="M69 54 L60 54 M64.5 61.8 L60 54 M55.5 61.8 L60 54 M51 54 L60 54 M55.5 46.2 L60 54 M64.5 46.2 L60 54"/>
|
||||
<path d="M60 8 L60 1 M57 4 L63 4"/>`,
|
||||
"modern": `
|
||||
<path d="M30 75 L34 43 L63 31 L87 46 L86 75 Z" fill="currentColor" fill-opacity=".055"/>
|
||||
<path d="M28 45 L63 28 L89 46"/>
|
||||
<path d="M91 24 L103 24 L103 75 L91 75 Z" fill="currentColor" fill-opacity=".055"/>
|
||||
<path d="M96.5 34 L96.5 62 M98.5 34 L98.5 62"/>
|
||||
<path d="M97 24 L97 12 M92 17 L102 17"/>
|
||||
<path d="M38 72 L38 50 L58 43 L58 72 Z"/>
|
||||
<path d="M40 70 L42.5 47 M46 70 L48.5 47 M52 70 L54.5 47"/>
|
||||
<path d="M66 75 L66 56 L82 51 L82 75"/>`,
|
||||
"rotunda": `
|
||||
<path d="M28 75 L32 53 Q60 39 88 53 L92 75 Z" fill="currentColor" fill-opacity=".055"/>
|
||||
<path d="M32 53 Q60 26 88 53"/>
|
||||
<path d="M56 36 L64 36 L64 31 L56 31 Z"/>
|
||||
<path d="M60 31 L60 20 M55.5 24 L64.5 24"/>
|
||||
<path d="M38 70 L38 58 M47 70 L47 58 M73 70 L73 58 M82 70 L82 58"/>
|
||||
<path d="M55 75 L55 61 Q60 55 65 61 L65 75"/>`,
|
||||
"roundTower": `
|
||||
<path d="M35 75 L35 35 L78 35 L78 75"/>
|
||||
<path d="M30 36 L56.5 12 L83 36"/>
|
||||
<ellipse cx="94" cy="55" rx="10" ry="20" fill="currentColor" fill-opacity=".055"/>
|
||||
<path d="M82 35 Q94 20 106 35"/>
|
||||
<path d="M94 24 L94 14 M90 18 L98 18"/>
|
||||
<path d="M51 70 L51 48 Q56 42 61 48 L61 70"/>`,
|
||||
"chapel": `
|
||||
<path d="M40 75 L40 46 L78 46 L78 75 Z" fill="currentColor" fill-opacity=".055"/>
|
||||
<path d="M35 47 L59 24 L83 47"/>
|
||||
<path d="M59 24 L59 13 M55 17 L63 17"/>
|
||||
<path d="M55 75 L55 60 Q60 53 65 60 L65 75"/>
|
||||
<ellipse cx="48.5" cy="60.5" rx="3.5" ry="5.5"/>
|
||||
<ellipse cx="70.5" cy="60.5" rx="3.5" ry="5.5"/>`,
|
||||
}
|
||||
|
||||
func churchGlyph(symbol any, color string) template.HTML {
|
||||
key := fmt.Sprint(symbol)
|
||||
body, ok := glyphBodies[key]
|
||||
if !ok {
|
||||
body = glyphBodies["chapel"]
|
||||
}
|
||||
if strings.TrimSpace(color) == "" {
|
||||
color = "#2E5C57"
|
||||
}
|
||||
return template.HTML(fmt.Sprintf(
|
||||
`<svg class="church-glyph" viewBox="0 0 120 86" role="img" aria-hidden="true" style="color:%s" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">%s<path d="M8 76 L112 76" stroke-opacity=".35" stroke-width=".8" stroke-dasharray="2 3"/></svg>`,
|
||||
template.HTMLEscapeString(color), body))
|
||||
}
|
||||
|
||||
var feastGlyphPaths = map[string]string{
|
||||
"star": `<path d="M12 2.5l2.6 6.1 6.4.6-4.9 4.3 1.5 6.3L12 16.4l-5.6 3.4 1.5-6.3-4.9-4.3 6.4-.6z"/>`,
|
||||
"sun": `<circle cx="12" cy="12" r="4.4"/><path d="M12 2v2.4M12 19.6V22M2 12h2.4M19.6 12H22M4.9 4.9l1.7 1.7M17.4 17.4l1.7 1.7M19.1 4.9l-1.7 1.7M6.6 17.4l-1.7 1.7"/>`,
|
||||
"flame": `<path d="M12 21c4 0 6.5-2.7 6.5-6.2 0-2.6-1.4-4.6-3.1-6.4-1.3-1.4-2.4-3-2.7-5.4-2.1 1.6-3.5 3.6-3.5 6 0 1.3.4 2.2 1 3.1-.9.1-2.4-.9-2.9-2.2-.4 1.2-.6 2.4-.6 3.5C6.7 18.1 8.5 21 12 21z"/>`,
|
||||
"lily": `<path d="M12 21V9M12 9C9.2 7.6 8.3 4.6 9.4 2c2.2.6 3.4 2.2 2.6 7zM12 9c2.8-1.4 3.7-4.4 2.6-7-2.2.6-3.4 2.2-2.6 7z"/><path d="M12 16c-2.6 0-4.4 1.5-5 3.4M12 16c2.6 0 4.4 1.5 5 3.4"/>`,
|
||||
"crown": `<path d="M3 18h18l-1.4-9-4.8 3.3L12 6l-2.8 6.3L4.4 9z"/><path d="M4 21h16"/>`,
|
||||
"heart": `<path d="M12 20.5S3.5 15.2 3.5 9.3C3.5 6.5 5.6 4.5 8 4.5c1.7 0 3.2 1 4 2.5.8-1.5 2.3-2.5 4-2.5 2.4 0 4.5 2 4.5 4.8 0 5.9-8.5 11.2-8.5 11.2z"/>`,
|
||||
"book": `<path d="M4 5.5c2.8-1 5.6-1 8 .5 2.4-1.5 5.2-1.5 8-.5v14c-2.8-1-5.6-1-8 .5-2.4-1.5-5.2-1.5-8-.5z"/><path d="M12 6v14"/>`,
|
||||
"candle": `<path d="M9 21h6V9H9zM12 9V6M12 6c-1.6 0-2.6-1.2-2.6-2.6C10.8 3.4 12 4.4 12 6zm0 0c1.6 0 2.6-1.2 2.6-2.6C13.2 3.4 12 4.4 12 6z"/><path d="M6 21h12"/>`,
|
||||
"dove": `<path d="M20.5 5.5c-2.2.2-4 1.2-5.2 2.8C14 6.6 12.6 5.5 10.5 5.5c-3 0-5 2.3-5 5.2 0 4 3.9 7 8.5 8.3 4.6-1.3 8.5-4.3 8.5-8.3 0-1.7-.7-3.2-1.5-4.2z"/><path d="M9 13c2 .2 3.8 1 5 2.2"/>`,
|
||||
"cross": `<path d="M12 2v20M6 8h12"/>`,
|
||||
}
|
||||
|
||||
func feastGlyph(symbol any) template.HTML {
|
||||
key := fmt.Sprint(symbol)
|
||||
body, ok := feastGlyphPaths[key]
|
||||
if !ok {
|
||||
body = feastGlyphPaths["book"]
|
||||
}
|
||||
return template.HTML(`<svg class="feast-glyph" viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">` + body + `</svg>`)
|
||||
}
|
||||
|
||||
var iconPaths = map[string]string{
|
||||
"calendar": `<rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4M16 3v4"/>`,
|
||||
"list": `<path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/>`,
|
||||
"users": `<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/>`,
|
||||
"chart": `<path d="M3 3v18h18"/><path d="M7 16v-5M12 16V7M17 16v-8"/>`,
|
||||
"exchange": `<path d="M4 7h13l-3-3M20 17H7l3 3"/>`,
|
||||
"settings": `<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .34 1.87l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 .6 1.7 1.7 0 0 0-.4 1.1V21a2 2 0 1 1-4 0v-.09A1.7 1.7 0 0 0 8.6 19.4a1.7 1.7 0 0 0-1.87.34l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-.6-1 1.7 1.7 0 0 0-1.1-.4H3a2 2 0 1 1 0-4h.09A1.7 1.7 0 0 0 4.6 8.6a1.7 1.7 0 0 0-.34-1.87l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-.6 1.7 1.7 0 0 0 .4-1.1V3a2 2 0 1 1 4 0v.09A1.7 1.7 0 0 0 15 4.6a1.7 1.7 0 0 0 1.87-.34l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.7 1.7 0 0 0 19.4 9c.1.4.3.8.6 1 .3.3.7.4 1.1.4H21a2 2 0 1 1 0 4h-.09a1.7 1.7 0 0 0-1.51.6z"/>`,
|
||||
"shield": `<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/>`,
|
||||
"printer": `<path d="M6 9V2h12v7M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/>`,
|
||||
"plus": `<path d="M12 5v14M5 12h14"/>`,
|
||||
"left": `<path d="M15 18l-6-6 6-6"/>`,
|
||||
"right": `<path d="M9 18l6-6-6-6"/>`,
|
||||
"sparkles": `<path d="M12 3l1.9 4.6L18.5 9.5l-4.6 1.9L12 16l-1.9-4.6L5.5 9.5l4.6-1.9z"/><path d="M19 15l.9 2.1L22 18l-2.1.9L19 21l-.9-2.1L16 18l2.1-.9z"/>`,
|
||||
"logout": `<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="M16 17l5-5-5-5M21 12H9"/>`,
|
||||
"church": `<path d="M12 2v6M9 5h6M6 22V11l6-4 6 4v11z"/><path d="M10 22v-5h4v5"/>`,
|
||||
"check": `<path d="M20 6L9 17l-5-5"/>`,
|
||||
"trash": `<path d="M3 6h18M8 6V4h8v2M19 6l-1 15H6L5 6M10 11v6M14 11v6"/>`,
|
||||
"external": `<path d="M14 3h7v7M10 14L21 3M21 14v7H3V3h7"/>`,
|
||||
"menu": `<path d="M4 7h16M4 12h16M4 17h16"/>`,
|
||||
"close": `<path d="M6 6l12 12M18 6L6 18"/>`,
|
||||
}
|
||||
|
||||
func iconSVG(name string) template.HTML {
|
||||
body, ok := iconPaths[name]
|
||||
if !ok {
|
||||
body = iconPaths["calendar"]
|
||||
}
|
||||
return template.HTML(`<svg class="icon" viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">` + body + `</svg>`)
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
// Package web serves the browser version of LektorenPlan.
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"embed"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
"lektorenplan/store"
|
||||
)
|
||||
|
||||
//go:embed templates/*.html static/*
|
||||
var assets embed.FS
|
||||
|
||||
// Options configures the HTTP server.
|
||||
type Options struct {
|
||||
SecureCookies bool
|
||||
SessionTTL time.Duration
|
||||
Version string
|
||||
DemoMode bool
|
||||
Diocese string
|
||||
}
|
||||
|
||||
// Server bundles templates, assets and the data store.
|
||||
type Server struct {
|
||||
store *store.Store
|
||||
views map[string]*template.Template
|
||||
static http.Handler
|
||||
opts Options
|
||||
sessionTTL time.Duration
|
||||
}
|
||||
|
||||
const (
|
||||
sessionCookie = "lp_session"
|
||||
tenantCookie = "lp_tenant"
|
||||
flashCookie = "lp_flash"
|
||||
flashKind = "lp_flash_kind"
|
||||
)
|
||||
|
||||
// New prepares the server and parses all page templates.
|
||||
func New(st *store.Store, opts Options) (*Server, error) {
|
||||
if opts.SessionTTL <= 0 {
|
||||
opts.SessionTTL = 30 * 24 * time.Hour
|
||||
}
|
||||
if opts.Version == "" {
|
||||
opts.Version = "1.0"
|
||||
}
|
||||
if opts.Diocese == "" {
|
||||
opts.Diocese = "Erzbistum Köln"
|
||||
}
|
||||
funcs := templateFunctions()
|
||||
names := []string{
|
||||
"login", "plan", "service", "services", "team", "person", "statistics",
|
||||
"exchange", "settings", "liturgy", "admin_tenants", "admin_users",
|
||||
"admin_churches", "error", "no_tenant",
|
||||
}
|
||||
views := make(map[string]*template.Template, len(names))
|
||||
for _, name := range names {
|
||||
t, err := template.New(name).Funcs(funcs).ParseFS(assets,
|
||||
"templates/layout.html", "templates/"+name+".html")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse template %s: %w", name, err)
|
||||
}
|
||||
views[name] = t
|
||||
}
|
||||
staticFS, err := fs.Sub(assets, "static")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Server{
|
||||
store: st, views: views, opts: opts, sessionTTL: opts.SessionTTL,
|
||||
static: http.StripPrefix("/static/", http.FileServer(http.FS(staticFS))),
|
||||
}, nil
|
||||
}
|
||||
|
||||
type contextKey string
|
||||
|
||||
const (
|
||||
userContext contextKey = "user"
|
||||
sessionContext contextKey = "session"
|
||||
tenantContext contextKey = "tenant"
|
||||
)
|
||||
|
||||
func userFrom(r *http.Request) *store.User {
|
||||
value, _ := r.Context().Value(userContext).(*store.User)
|
||||
return value
|
||||
}
|
||||
|
||||
func sessionFrom(r *http.Request) *store.Session {
|
||||
value, _ := r.Context().Value(sessionContext).(*store.Session)
|
||||
return value
|
||||
}
|
||||
|
||||
func tenantFrom(r *http.Request) *store.Tenant {
|
||||
value, _ := r.Context().Value(tenantContext).(*store.Tenant)
|
||||
return value
|
||||
}
|
||||
|
||||
// Handler builds the complete HTTP handler.
|
||||
func (s *Server) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("GET /static/", s.static)
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := s.store.Healthy(r.Context()); err != nil {
|
||||
http.Error(w, "unhealthy", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
fmt.Fprintln(w, "ok")
|
||||
})
|
||||
|
||||
mux.HandleFunc("GET /login", s.handleLoginGet)
|
||||
mux.HandleFunc("POST /login", s.handleLoginPost)
|
||||
mux.HandleFunc("POST /logout", s.auth(s.handleLogout))
|
||||
mux.HandleFunc("GET /switch", s.auth(s.handleSwitchTenant))
|
||||
mux.HandleFunc("GET /{$}", s.auth(s.handleRoot))
|
||||
|
||||
mux.HandleFunc("GET /plan", s.auth(s.handlePlan))
|
||||
mux.HandleFunc("POST /plan/generate", s.editor(s.handleGenerateServices))
|
||||
mux.HandleFunc("POST /plan/auto", s.editor(s.handleAutoPlan))
|
||||
mux.HandleFunc("GET /services", s.auth(s.handleServiceOrder))
|
||||
mux.HandleFunc("GET /services/{id}", s.auth(s.handleServiceDetail))
|
||||
mux.HandleFunc("POST /services/{id}/save", s.editor(s.handleServiceSave))
|
||||
mux.HandleFunc("POST /services/{id}/delete", s.editor(s.handleServiceDelete))
|
||||
mux.HandleFunc("POST /services/{id}/assign", s.editor(s.handleAssign))
|
||||
mux.HandleFunc("POST /services/{id}/unassign", s.editor(s.handleUnassign))
|
||||
mux.HandleFunc("POST /services/{id}/lock", s.editor(s.handleToggleLock))
|
||||
mux.HandleFunc("POST /services/new", s.editor(s.handleSpecialServiceSave))
|
||||
mux.HandleFunc("POST /templates/save", s.editor(s.handleTemplateSave))
|
||||
mux.HandleFunc("POST /templates/delete", s.editor(s.handleTemplateDelete))
|
||||
mux.HandleFunc("POST /exceptions/save", s.editor(s.handleExceptionSave))
|
||||
mux.HandleFunc("POST /exceptions/delete", s.editor(s.handleExceptionDelete))
|
||||
|
||||
mux.HandleFunc("GET /team", s.auth(s.handleTeam))
|
||||
mux.HandleFunc("GET /team/person/{id}", s.auth(s.handlePerson))
|
||||
mux.HandleFunc("POST /team/person/{id}/save", s.editor(s.handlePersonSave))
|
||||
mux.HandleFunc("POST /team/person/{id}/delete", s.editor(s.handlePersonDelete))
|
||||
mux.HandleFunc("POST /team/person/{id}/absence", s.editor(s.handleAbsenceSave))
|
||||
mux.HandleFunc("POST /team/person/{id}/absence/delete", s.editor(s.handleAbsenceDelete))
|
||||
|
||||
mux.HandleFunc("GET /statistics", s.auth(s.handleStatistics))
|
||||
mux.HandleFunc("GET /exchange", s.auth(s.handleExchange))
|
||||
mux.HandleFunc("GET /exchange/export", s.auth(s.handleExport))
|
||||
mux.HandleFunc("POST /exchange/import", s.editor(s.handleImport))
|
||||
mux.HandleFunc("GET /settings", s.auth(s.handleSettings))
|
||||
mux.HandleFunc("POST /settings/save", s.editor(s.handleSettingsSave))
|
||||
mux.HandleFunc("POST /settings/demo/reset", s.editor(s.handleResetDemo))
|
||||
mux.HandleFunc("POST /settings/data/delete", s.editor(s.handleDeleteTenantData))
|
||||
mux.HandleFunc("GET /liturgy", s.auth(s.handleLiturgy))
|
||||
mux.HandleFunc("POST /liturgy/sync", s.editor(s.handleLiturgySync))
|
||||
mux.HandleFunc("GET /pdf", s.auth(s.handlePDF))
|
||||
|
||||
mux.HandleFunc("GET /admin", s.admin(s.handleAdminRoot))
|
||||
mux.HandleFunc("GET /admin/tenants", s.admin(s.handleAdminTenants))
|
||||
mux.HandleFunc("POST /admin/tenants/save", s.admin(s.handleAdminTenantSave))
|
||||
mux.HandleFunc("POST /admin/tenants/delete", s.admin(s.handleAdminTenantDelete))
|
||||
mux.HandleFunc("GET /admin/users", s.admin(s.handleAdminUsers))
|
||||
mux.HandleFunc("POST /admin/users/save", s.admin(s.handleAdminUserSave))
|
||||
mux.HandleFunc("POST /admin/users/delete", s.admin(s.handleAdminUserDelete))
|
||||
mux.HandleFunc("GET /admin/churches", s.admin(s.handleAdminChurches))
|
||||
mux.HandleFunc("POST /admin/churches/save", s.admin(s.handleAdminChurchSave))
|
||||
mux.HandleFunc("POST /admin/churches/delete", s.admin(s.handleAdminChurchDelete))
|
||||
|
||||
return s.logging(s.withSession(s.withCSRF(s.withSecurity(mux))))
|
||||
}
|
||||
|
||||
func (s *Server) withSecurity(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
|
||||
w.Header().Set("Referrer-Policy", "same-origin")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) logging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
next.ServeHTTP(w, r)
|
||||
log.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start).Round(time.Millisecond))
|
||||
})
|
||||
}
|
||||
|
||||
// withSession loads the cookie session, user and active tenant into context.
|
||||
func (s *Server) withSession(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
cookie, err := r.Cookie(sessionCookie)
|
||||
if err == nil && cookie.Value != "" {
|
||||
session, user, err := s.store.SessionUser(r.Context(), cookie.Value)
|
||||
if err == nil {
|
||||
ctx := context.WithValue(r.Context(), userContext, user)
|
||||
ctx = context.WithValue(ctx, sessionContext, session)
|
||||
r = r.WithContext(ctx)
|
||||
|
||||
tenant, fromQuery := s.resolveTenant(w, r, user)
|
||||
if tenant != nil {
|
||||
ctx = context.WithValue(r.Context(), tenantContext, tenant)
|
||||
r = r.WithContext(ctx)
|
||||
if fromQuery {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: tenantCookie, Value: tenant.ID, Path: "/",
|
||||
HttpOnly: true, SameSite: http.SameSiteLaxMode,
|
||||
Secure: s.opts.SecureCookies, MaxAge: 365 * 24 * 3600,
|
||||
})
|
||||
}
|
||||
}
|
||||
} else if !errors.Is(err, store.ErrNotFound) {
|
||||
log.Printf("session: %v", err)
|
||||
}
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) resolveTenant(w http.ResponseWriter, r *http.Request, user *store.User) (*store.Tenant, bool) {
|
||||
tenants, err := s.store.TenantsForUser(r.Context(), user)
|
||||
if err != nil || len(tenants) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
if queryID := strings.TrimSpace(r.URL.Query().Get("tid")); queryID != "" {
|
||||
for i := range tenants {
|
||||
if tenants[i].ID == queryID {
|
||||
return &tenants[i], true
|
||||
}
|
||||
}
|
||||
}
|
||||
if cookie, err := r.Cookie(tenantCookie); err == nil {
|
||||
for i := range tenants {
|
||||
if tenants[i].ID == cookie.Value {
|
||||
return &tenants[i], false
|
||||
}
|
||||
}
|
||||
}
|
||||
return &tenants[0], true
|
||||
}
|
||||
|
||||
func (s *Server) withCSRF(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/login" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
session := sessionFrom(r)
|
||||
if session == nil {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
token := r.FormValue("csrf")
|
||||
if token == "" {
|
||||
token = r.Header.Get("X-CSRF-Token")
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(token), []byte(session.CSRFToken)) != 1 {
|
||||
s.renderError(w, r, http.StatusForbidden, "Sicherheitsprüfung fehlgeschlagen",
|
||||
"Das Formular ist abgelaufen oder ungültig. Bitte laden Sie die Seite neu.")
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
type authedHandler func(http.ResponseWriter, *http.Request, *store.User, *store.Session, *store.Tenant)
|
||||
|
||||
func (s *Server) auth(next authedHandler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := userFrom(r)
|
||||
session := sessionFrom(r)
|
||||
if user == nil || session == nil {
|
||||
target := r.URL.RequestURI()
|
||||
http.Redirect(w, r, "/login?next="+url.QueryEscape(target), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
next(w, r, user, session, tenantFrom(r))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) editor(next authedHandler) http.HandlerFunc {
|
||||
return s.auth(func(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.setFlash(w, "Kein Mandant ausgewählt.", "error")
|
||||
http.Redirect(w, r, "/plan", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
if !s.store.CanEditTenant(r.Context(), user, tenant.ID) {
|
||||
s.renderError(w, r, http.StatusForbidden, "Nur lesender Zugriff",
|
||||
"Ihr Konto darf in diesem Mandanten keine Daten ändern.")
|
||||
return
|
||||
}
|
||||
next(w, r, user, session, tenant)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) admin(next authedHandler) http.HandlerFunc {
|
||||
return s.auth(func(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if !user.Role.IsAdmin() {
|
||||
s.renderError(w, r, http.StatusForbidden, "Administration",
|
||||
"Diese Seite ist nur für Administratoren zugänglich.")
|
||||
return
|
||||
}
|
||||
next(w, r, user, session, tenant)
|
||||
})
|
||||
}
|
||||
|
||||
// Flash helpers -------------------------------------------------------------
|
||||
|
||||
func (s *Server) setFlash(w http.ResponseWriter, message, kind string) {
|
||||
encoded := base64.RawURLEncoding.EncodeToString([]byte(message))
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: flashCookie, Value: encoded, Path: "/", HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode, Secure: s.opts.SecureCookies, MaxAge: 60,
|
||||
})
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: flashKind, Value: kind, Path: "/", HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode, Secure: s.opts.SecureCookies, MaxAge: 60,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) popFlash(w http.ResponseWriter, r *http.Request) (string, string) {
|
||||
cookie, err := r.Cookie(flashCookie)
|
||||
if err != nil || cookie.Value == "" {
|
||||
return "", ""
|
||||
}
|
||||
data, err := base64.RawURLEncoding.DecodeString(cookie.Value)
|
||||
if err != nil {
|
||||
return "", ""
|
||||
}
|
||||
kind := "success"
|
||||
if kindCookie, err := r.Cookie(flashKind); err == nil && kindCookie.Value != "" {
|
||||
kind = kindCookie.Value
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: flashCookie, Value: "", Path: "/", MaxAge: -1})
|
||||
http.SetCookie(w, &http.Cookie{Name: flashKind, Value: "", Path: "/", MaxAge: -1})
|
||||
return string(data), kind
|
||||
}
|
||||
|
||||
func (s *Server) redirect(w http.ResponseWriter, r *http.Request, path string) {
|
||||
http.Redirect(w, r, path, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func (s *Server) redirectBack(w http.ResponseWriter, r *http.Request, fallback string) {
|
||||
if referer := r.Referer(); referer != "" {
|
||||
if parsed, err := url.Parse(referer); err == nil && parsed.Host == r.Host {
|
||||
http.Redirect(w, r, referer, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
}
|
||||
s.redirect(w, r, fallback)
|
||||
}
|
||||
|
||||
// Range helpers -------------------------------------------------------------
|
||||
|
||||
func (s *Server) rangeFromRequest(r *http.Request) domain.DayRange {
|
||||
startKey := strings.TrimSpace(r.URL.Query().Get("start"))
|
||||
endKey := strings.TrimSpace(r.URL.Query().Get("end"))
|
||||
start, startOK := domain.DateFromKey(startKey)
|
||||
end, endOK := domain.DateFromKey(endKey)
|
||||
if !startOK && !endOK {
|
||||
today := domain.Today()
|
||||
return domain.MonthRange(today)
|
||||
}
|
||||
if !startOK {
|
||||
start = domain.StartOfMonth(end)
|
||||
}
|
||||
if !endOK {
|
||||
end = domain.EndOfMonth(start)
|
||||
}
|
||||
if end.Before(start) {
|
||||
start, end = end, start
|
||||
}
|
||||
if domain.DaysBetween(start, end) > 400 {
|
||||
end = domain.AddingDays(400, start)
|
||||
}
|
||||
return domain.NewDayRange(start, end)
|
||||
}
|
||||
|
||||
func (s *Server) planningOptions(r *http.Request, tenantID string) domain.PlannerOptions {
|
||||
options := domain.DefaultPlannerOptions()
|
||||
get := func(key string) string { return s.store.TenantSetting(r.Context(), tenantID, "planner."+key) }
|
||||
if value := get("replaceExisting"); value != "" {
|
||||
options.ReplaceExisting = value == "1"
|
||||
}
|
||||
if value := get("respectPreferredWeekdays"); value != "" {
|
||||
options.RespectPreferredWeekdays = value == "1"
|
||||
}
|
||||
if value := get("allowDoubleRoles"); value != "" {
|
||||
options.AllowDoubleRolesOnSameDay = value == "1"
|
||||
}
|
||||
if value := get("weightChurch"); value != "" {
|
||||
fmt.Sscanf(value, "%f", &options.WeightChurchPreference)
|
||||
}
|
||||
if value := get("weightService"); value != "" {
|
||||
fmt.Sscanf(value, "%f", &options.WeightServicePreference)
|
||||
}
|
||||
if value := get("weightFairness"); value != "" {
|
||||
fmt.Sscanf(value, "%f", &options.WeightFairness)
|
||||
}
|
||||
if value := get("weightDualRole"); value != "" {
|
||||
fmt.Sscanf(value, "%f", &options.WeightDualRolePreference)
|
||||
}
|
||||
if value := get("maxPerDay"); value != "" {
|
||||
fmt.Sscanf(value, "%d", &options.MaxAssignmentsPerDay)
|
||||
}
|
||||
if options.MaxAssignmentsPerDay < 1 {
|
||||
options.MaxAssignmentsPerDay = 1
|
||||
}
|
||||
return options
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
"lektorenplan/store"
|
||||
)
|
||||
|
||||
// newTestServer seeds an in-memory database and returns a running server.
|
||||
func newTestServer(t *testing.T) (*httptest.Server, *store.Store) {
|
||||
t.Helper()
|
||||
st, err := store.Open(":memory:")
|
||||
if err != nil {
|
||||
t.Fatalf("open store: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { st.Close() })
|
||||
if err := st.SeedDemo(context.Background()); err != nil {
|
||||
t.Fatalf("seed demo: %v", err)
|
||||
}
|
||||
srv, err := New(st, Options{Version: "test", DemoMode: true})
|
||||
if err != nil {
|
||||
t.Fatalf("new server: %v", err)
|
||||
}
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
t.Cleanup(ts.Close)
|
||||
return ts, st
|
||||
}
|
||||
|
||||
func newClient(t *testing.T) *http.Client {
|
||||
t.Helper()
|
||||
jar, err := cookiejar.New(nil)
|
||||
if err != nil {
|
||||
t.Fatalf("cookie jar: %v", err)
|
||||
}
|
||||
return &http.Client{
|
||||
Jar: jar,
|
||||
Timeout: 10 * time.Second,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func login(t *testing.T, client *http.Client, base, username, password string) {
|
||||
t.Helper()
|
||||
resp, err := client.PostForm(base+"/login", url.Values{
|
||||
"username": {username}, "password": {password},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("login: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusSeeOther {
|
||||
t.Fatalf("login status = %d, want 303", resp.StatusCode)
|
||||
}
|
||||
if !strings.HasPrefix(resp.Header.Get("Location"), "/plan") {
|
||||
t.Fatalf("login redirect = %q, want /plan", resp.Header.Get("Location"))
|
||||
}
|
||||
}
|
||||
|
||||
func get(t *testing.T, client *http.Client, url string, want int) string {
|
||||
t.Helper()
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
t.Fatalf("GET %s: %v", url, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != want {
|
||||
t.Fatalf("GET %s = %d, want %d\n%s", url, resp.StatusCode, want, firstBytes(body, 400))
|
||||
}
|
||||
if want == http.StatusOK {
|
||||
text := string(body)
|
||||
if strings.Contains(text, "Die Seite konnte nicht erstellt werden.") {
|
||||
t.Fatalf("GET %s rendered a template error", url)
|
||||
}
|
||||
}
|
||||
return string(body)
|
||||
}
|
||||
|
||||
func firstBytes(data []byte, n int) string {
|
||||
if len(data) > n {
|
||||
data = data[:n]
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func TestFormatFloatUsesGermanComma(t *testing.T) {
|
||||
fn, ok := templateFunctions()["formatFloat"].(func(float64) string)
|
||||
if !ok {
|
||||
t.Fatal("formatFloat template function missing")
|
||||
}
|
||||
for value, want := range map[float64]string{5: "5,0", 12.36: "12,4", 0.25: "0,3"} {
|
||||
if got := fn(value); got != want {
|
||||
t.Fatalf("formatFloat(%v) = %q, want %q", value, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticatedPagesRender(t *testing.T) {
|
||||
ts, st := newTestServer(t)
|
||||
client := newClient(t)
|
||||
login(t, client, ts.URL, "admin", "admin123")
|
||||
|
||||
ctx := context.Background()
|
||||
tenants, err := st.Tenants(ctx)
|
||||
if err != nil || len(tenants) == 0 {
|
||||
t.Fatalf("tenants: %v", err)
|
||||
}
|
||||
tenantID := tenants[0].ID
|
||||
churches, _ := st.Churches(ctx, tenantID)
|
||||
people, _ := st.People(ctx, tenantID)
|
||||
templates, _ := st.Templates(ctx, tenantID)
|
||||
exceptions, _ := st.Exceptions(ctx, tenantID)
|
||||
services, _ := st.Services(ctx, tenantID, domain.YearRange(2025))
|
||||
specials, _ := st.SpecialServices(ctx, tenantID)
|
||||
if len(churches) == 0 || len(people) == 0 || len(templates) == 0 || len(services) == 0 || len(specials) == 0 {
|
||||
t.Fatalf("demo data incomplete: churches=%d people=%d templates=%d services=%d specials=%d",
|
||||
len(churches), len(people), len(templates), len(services), len(specials))
|
||||
}
|
||||
|
||||
pages := []string{
|
||||
"/plan",
|
||||
"/plan?start=2025-01-01&end=2025-01-31",
|
||||
"/services",
|
||||
"/services?edit=" + templates[0].ID,
|
||||
"/services?edit_special=" + specials[0].ID,
|
||||
"/services/" + services[0].ID,
|
||||
"/team",
|
||||
"/team/person/" + people[0].ID,
|
||||
"/statistics",
|
||||
"/statistics?start=2025-01-01&end=2025-12-31",
|
||||
"/exchange",
|
||||
"/exchange/export",
|
||||
"/settings",
|
||||
"/liturgy?year=2025",
|
||||
"/admin/tenants",
|
||||
"/admin/tenants?edit=" + tenantID,
|
||||
"/admin/users",
|
||||
"/admin/churches",
|
||||
"/admin/churches?edit=" + churches[0].ID,
|
||||
"/pdf?variant=plan&start=2025-01-01&end=2025-01-31",
|
||||
"/pdf?variant=compact&start=2025-01-01&end=2025-01-31",
|
||||
}
|
||||
if len(exceptions) > 0 {
|
||||
pages = append(pages, "/services?edit_exception="+exceptions[0].ID)
|
||||
}
|
||||
for _, page := range pages {
|
||||
get(t, client, ts.URL+page, http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoleAndTenantGuards(t *testing.T) {
|
||||
ts, _ := newTestServer(t)
|
||||
|
||||
reader := newClient(t)
|
||||
login(t, reader, ts.URL, "reader", "reader123")
|
||||
get(t, reader, ts.URL+"/plan", http.StatusOK)
|
||||
get(t, reader, ts.URL+"/admin/users", http.StatusForbidden)
|
||||
|
||||
editor := newClient(t)
|
||||
login(t, editor, ts.URL, "editor", "editor123")
|
||||
get(t, editor, ts.URL+"/settings", http.StatusOK)
|
||||
get(t, editor, ts.URL+"/admin/tenants", http.StatusForbidden)
|
||||
|
||||
anonymous := newClient(t)
|
||||
get(t, anonymous, ts.URL+"/plan", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func TestWritesAndCSRF(t *testing.T) {
|
||||
ts, st := newTestServer(t)
|
||||
client := newClient(t)
|
||||
login(t, client, ts.URL, "admin", "admin123")
|
||||
|
||||
body := get(t, client, ts.URL+"/plan", http.StatusOK)
|
||||
csrf := extractCSRF(t, body)
|
||||
|
||||
// The login cookie session and CSRF token are valid for follow-up writes.
|
||||
post := func(path string, form url.Values, want int) {
|
||||
t.Helper()
|
||||
form.Set("csrf", csrf)
|
||||
resp, err := client.PostForm(ts.URL+path, form)
|
||||
if err != nil {
|
||||
t.Fatalf("POST %s: %v", path, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != want {
|
||||
t.Fatalf("POST %s = %d, want %d", path, resp.StatusCode, want)
|
||||
}
|
||||
}
|
||||
|
||||
post("/plan/generate", url.Values{"start": {"2026-12-01"}, "end": {"2026-12-31"}}, http.StatusSeeOther)
|
||||
post("/plan/auto", url.Values{"start": {"2026-12-01"}, "end": {"2026-12-31"}}, http.StatusSeeOther)
|
||||
get(t, client, ts.URL+"/plan?start=2026-12-01&end=2026-12-31", http.StatusOK)
|
||||
|
||||
// A missing CSRF token must be rejected before any mutation.
|
||||
resp, err := client.PostForm(ts.URL+"/settings/save", url.Values{"auto_sync": {"1"}})
|
||||
if err != nil {
|
||||
t.Fatalf("POST without csrf: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusForbidden {
|
||||
t.Fatalf("POST without csrf = %d, want 403", resp.StatusCode)
|
||||
}
|
||||
|
||||
// The write above must not have reached the store.
|
||||
if err := st.Healthy(context.Background()); err != nil {
|
||||
t.Fatalf("store unhealthy: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func extractCSRF(t *testing.T, body string) string {
|
||||
t.Helper()
|
||||
const marker = `name="csrf" value="`
|
||||
index := strings.Index(body, marker)
|
||||
if index < 0 {
|
||||
t.Fatal("csrf token not found")
|
||||
}
|
||||
rest := body[index+len(marker):]
|
||||
end := strings.Index(rest, `"`)
|
||||
if end < 0 {
|
||||
t.Fatal("malformed csrf token")
|
||||
}
|
||||
return rest[:end]
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
"lektorenplan/store"
|
||||
)
|
||||
|
||||
type serviceOrderData struct {
|
||||
Churches []domain.Church
|
||||
Templates []domain.ServiceTemplate
|
||||
TemplatesByChurch map[string][]domain.ServiceTemplate
|
||||
TemplateByID map[string]domain.ServiceTemplate
|
||||
ExceptionCount map[string]int
|
||||
ExceptionList map[string][]domain.ServiceException
|
||||
Exceptions []domain.ServiceException
|
||||
Specials []domain.ServiceOccurrence
|
||||
ChurchByID map[string]domain.Church
|
||||
EditingTemplate *domain.ServiceTemplate
|
||||
EditingException *domain.ServiceException
|
||||
EditingSpecial *domain.ServiceOccurrence
|
||||
CanEdit bool
|
||||
Start string
|
||||
End string
|
||||
}
|
||||
|
||||
type serviceDetailData struct {
|
||||
Service domain.ServiceWithAssignments
|
||||
Church domain.Church
|
||||
Churches []domain.Church
|
||||
People map[string]domain.Person
|
||||
Start string
|
||||
End string
|
||||
CanEdit bool
|
||||
LectorOpen int
|
||||
HelperOpen int
|
||||
LectorCandidates []domain.CandidateSuggestion
|
||||
HelperCandidates []domain.CandidateSuggestion
|
||||
LectorAssigned []domain.Assignment
|
||||
HelperAssigned []domain.Assignment
|
||||
}
|
||||
|
||||
func (s *Server) handleServiceOrder(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.renderNoTenant(w, r)
|
||||
return
|
||||
}
|
||||
churches, err := s.store.Churches(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Gottesdienstordnung", err.Error())
|
||||
return
|
||||
}
|
||||
templates, err := s.store.Templates(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Gottesdienstordnung", err.Error())
|
||||
return
|
||||
}
|
||||
exceptions, err := s.store.Exceptions(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Ausnahmen", err.Error())
|
||||
return
|
||||
}
|
||||
specials, err := s.store.SpecialServices(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Sondergottesdienste", err.Error())
|
||||
return
|
||||
}
|
||||
templatesByChurch := map[string][]domain.ServiceTemplate{}
|
||||
templateByID := map[string]domain.ServiceTemplate{}
|
||||
for _, template := range templates {
|
||||
templatesByChurch[template.ChurchID] = append(templatesByChurch[template.ChurchID], template)
|
||||
templateByID[template.ID] = template
|
||||
}
|
||||
exceptionCount := map[string]int{}
|
||||
exceptionList := map[string][]domain.ServiceException{}
|
||||
for _, exception := range exceptions {
|
||||
exceptionCount[exception.TemplateID]++
|
||||
exceptionList[exception.TemplateID] = append(exceptionList[exception.TemplateID], exception)
|
||||
}
|
||||
churchByID := map[string]domain.Church{}
|
||||
for _, church := range churches {
|
||||
churchByID[church.ID] = church
|
||||
}
|
||||
var editingTemplate *domain.ServiceTemplate
|
||||
if id := strings.TrimSpace(r.URL.Query().Get("edit")); id != "" {
|
||||
for i := range templates {
|
||||
if templates[i].ID == id {
|
||||
copy := templates[i]
|
||||
editingTemplate = ©
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
var editingException *domain.ServiceException
|
||||
if id := strings.TrimSpace(r.URL.Query().Get("edit_exception")); id != "" {
|
||||
for i := range exceptions {
|
||||
if exceptions[i].ID == id {
|
||||
copy := exceptions[i]
|
||||
editingException = ©
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
var editingSpecial *domain.ServiceOccurrence
|
||||
if id := strings.TrimSpace(r.URL.Query().Get("edit_special")); id != "" {
|
||||
for i := range specials {
|
||||
if specials[i].ID == id {
|
||||
copy := specials[i]
|
||||
editingSpecial = ©
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
data := s.baseView(w, r, "Gottesdienstordnung", "services")
|
||||
data.Data = serviceOrderData{
|
||||
Churches: churches, Templates: templates, TemplatesByChurch: templatesByChurch, TemplateByID: templateByID,
|
||||
ExceptionCount: exceptionCount, ExceptionList: exceptionList, Exceptions: exceptions,
|
||||
Specials: specials, ChurchByID: churchByID,
|
||||
EditingTemplate: editingTemplate, EditingException: editingException,
|
||||
EditingSpecial: editingSpecial,
|
||||
CanEdit: s.store.CanEditTenant(r.Context(), user, tenant.ID),
|
||||
Start: domain.Key(domain.Today()), End: domain.Key(domain.EndOfMonth(domain.Today())),
|
||||
}
|
||||
s.renderPage(w, r, "services", data)
|
||||
}
|
||||
|
||||
func (s *Server) handleServiceDetail(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.renderNoTenant(w, r)
|
||||
return
|
||||
}
|
||||
service, err := s.store.Service(r.Context(), tenant.ID, r.PathValue("id"))
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusNotFound, "Gottesdienst", "Dieser Gottesdienst wurde nicht gefunden.")
|
||||
return
|
||||
}
|
||||
church, err := s.store.Church(r.Context(), tenant.ID, service.ChurchID)
|
||||
if err != nil {
|
||||
church = &domain.Church{ID: service.ChurchID, Name: "Unbekannte Kirche"}
|
||||
}
|
||||
people, err := s.store.People(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Team", err.Error())
|
||||
return
|
||||
}
|
||||
churches, err := s.store.Churches(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Kirchen", err.Error())
|
||||
return
|
||||
}
|
||||
assignments, err := s.store.AssignmentsForServices(r.Context(), tenant.ID, []string{service.ID})
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Einteilungen", err.Error())
|
||||
return
|
||||
}
|
||||
rng := s.serviceRange(r, service.Date)
|
||||
rangeServices, err := s.store.Services(r.Context(), tenant.ID, rng)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Planung", err.Error())
|
||||
return
|
||||
}
|
||||
rangeAssignments, err := s.store.Assignments(r.Context(), tenant.ID, rng)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Einteilungen", err.Error())
|
||||
return
|
||||
}
|
||||
absences, err := s.store.Absences(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Abwesenheiten", err.Error())
|
||||
return
|
||||
}
|
||||
withAssignments := domain.ServiceWithAssignments{Service: *service, Church: *church, Assignments: assignments}
|
||||
data := s.baseView(w, r, "Gottesdienst", "services")
|
||||
peopleByID := make(map[string]domain.Person, len(people))
|
||||
for _, person := range people {
|
||||
peopleByID[person.ID] = person
|
||||
}
|
||||
detail := serviceDetailData{
|
||||
Service: withAssignments, Church: *church, Churches: churches, People: peopleByID,
|
||||
Start: domain.Key(rng.Start), End: domain.Key(rng.End),
|
||||
CanEdit: s.store.CanEditTenant(r.Context(), user, tenant.ID),
|
||||
LectorAssigned: withAssignments.AssignmentsFor(domain.RoleLector),
|
||||
HelperAssigned: withAssignments.AssignmentsFor(domain.RoleHelper),
|
||||
}
|
||||
detail.LectorOpen = withAssignments.OpenSlotsFor(domain.RoleLector)
|
||||
detail.HelperOpen = withAssignments.OpenSlotsFor(domain.RoleHelper)
|
||||
if detail.LectorOpen > 0 {
|
||||
detail.LectorCandidates = domain.CandidateSuggestions(*service, domain.RoleLector, people, absences,
|
||||
rangeAssignments, rangeServices, assignments, false)
|
||||
}
|
||||
if detail.HelperOpen > 0 {
|
||||
detail.HelperCandidates = domain.CandidateSuggestions(*service, domain.RoleHelper, people, absences,
|
||||
rangeAssignments, rangeServices, assignments, false)
|
||||
}
|
||||
data.Data = detail
|
||||
s.renderPage(w, r, "service", data)
|
||||
}
|
||||
|
||||
func (s *Server) serviceRange(r *http.Request, date time.Time) domain.DayRange {
|
||||
start, startOK := domain.DateFromKey(strings.TrimSpace(r.URL.Query().Get("start")))
|
||||
end, endOK := domain.DateFromKey(strings.TrimSpace(r.URL.Query().Get("end")))
|
||||
if startOK && endOK {
|
||||
if end.Before(start) {
|
||||
start, end = end, start
|
||||
}
|
||||
if domain.DaysBetween(start, end) > 400 {
|
||||
end = domain.AddingDays(400, start)
|
||||
}
|
||||
return domain.NewDayRange(start, end)
|
||||
}
|
||||
return domain.MonthRange(date)
|
||||
}
|
||||
|
||||
func (s *Server) handleAssign(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
service, err := s.store.Service(r.Context(), tenant.ID, r.PathValue("id"))
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusNotFound, "Gottesdienst", "Dieser Gottesdienst wurde nicht gefunden.")
|
||||
return
|
||||
}
|
||||
role := domain.Role(strings.TrimSpace(r.FormValue("role")))
|
||||
personID := strings.TrimSpace(r.FormValue("person_id"))
|
||||
if !role.IsValid() || personID == "" {
|
||||
s.setFlash(w, "Bitte Rolle und Person auswählen.", "error")
|
||||
s.redirectBack(w, r, "/services/"+service.ID)
|
||||
return
|
||||
}
|
||||
person, err := s.store.Person(r.Context(), tenant.ID, personID)
|
||||
if err != nil {
|
||||
s.setFlash(w, "Die Person wurde nicht gefunden.", "error")
|
||||
s.redirectBack(w, r, "/services/"+service.ID)
|
||||
return
|
||||
}
|
||||
if !person.CanFill(role) {
|
||||
s.setFlash(w, person.FullName()+" hat die Rolle "+role.Title()+" nicht.", "error")
|
||||
s.redirectBack(w, r, "/services/"+service.ID)
|
||||
return
|
||||
}
|
||||
assignments, _ := s.store.AssignmentsForServices(r.Context(), tenant.ID, []string{service.ID})
|
||||
filled := 0
|
||||
for _, assignment := range assignments {
|
||||
if assignment.Role == role {
|
||||
filled++
|
||||
}
|
||||
}
|
||||
if filled >= service.RequiredCount(role) {
|
||||
s.setFlash(w, "Für diese Rolle sind bereits alle Plätze besetzt.", "info")
|
||||
s.redirectBack(w, r, "/services/"+service.ID)
|
||||
return
|
||||
}
|
||||
locked := r.FormValue("locked") == "1" || r.FormValue("locked") == "on"
|
||||
assignment := domain.Assignment{
|
||||
ID: domain.NewID(), ServiceID: service.ID, PersonID: person.ID,
|
||||
Role: role, Locked: locked, Note: strings.TrimSpace(r.FormValue("note")),
|
||||
}
|
||||
if err := s.store.UpsertAssignment(r.Context(), tenant.ID, assignment); err != nil {
|
||||
s.setFlash(w, "Die Einteilung konnte nicht gespeichert werden: "+err.Error(), "error")
|
||||
} else {
|
||||
s.setFlash(w, person.FullName()+" wurde als "+role.Title()+" eingeteilt.", "success")
|
||||
}
|
||||
s.redirectBack(w, r, "/services/"+service.ID)
|
||||
}
|
||||
|
||||
func (s *Server) handleUnassign(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
assignmentID := strings.TrimSpace(r.FormValue("assignment_id"))
|
||||
if assignmentID != "" {
|
||||
if err := s.store.DeleteAssignment(r.Context(), tenant.ID, assignmentID); err != nil {
|
||||
s.setFlash(w, "Die Einteilung konnte nicht entfernt werden.", "error")
|
||||
} else {
|
||||
s.setFlash(w, "Einteilung entfernt.", "success")
|
||||
}
|
||||
}
|
||||
s.redirectBack(w, r, "/services/"+r.PathValue("id"))
|
||||
}
|
||||
|
||||
func (s *Server) handleToggleLock(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
assignmentID := strings.TrimSpace(r.FormValue("assignment_id"))
|
||||
if assignmentID != "" {
|
||||
if err := s.store.ToggleAssignmentLock(r.Context(), tenant.ID, assignmentID); err != nil {
|
||||
s.setFlash(w, "Die Sperre konnte nicht geändert werden.", "error")
|
||||
} else {
|
||||
s.setFlash(w, "Sperre aktualisiert.", "success")
|
||||
}
|
||||
}
|
||||
s.redirectBack(w, r, "/services/"+r.PathValue("id"))
|
||||
}
|
||||
|
||||
func (s *Server) handleServiceSave(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
service, err := s.store.Service(r.Context(), tenant.ID, r.PathValue("id"))
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusNotFound, "Gottesdienst", "Dieser Gottesdienst wurde nicht gefunden.")
|
||||
return
|
||||
}
|
||||
date, ok := domain.DateFromKey(strings.TrimSpace(r.FormValue("date")))
|
||||
if !ok {
|
||||
date = service.Date
|
||||
}
|
||||
timeMinutes, ok := domain.ParseTimeString(r.FormValue("time"))
|
||||
if !ok {
|
||||
timeMinutes = service.TimeMinutes
|
||||
}
|
||||
churchID := strings.TrimSpace(r.FormValue("church_id"))
|
||||
if churchID == "" {
|
||||
churchID = service.ChurchID
|
||||
}
|
||||
location := strings.TrimSpace(r.FormValue("location"))
|
||||
if location != "" {
|
||||
service.Location = &location
|
||||
} else {
|
||||
service.Location = nil
|
||||
}
|
||||
service.ChurchID = churchID
|
||||
service.Date = date
|
||||
service.TimeMinutes = timeMinutes
|
||||
service.Title = strings.TrimSpace(r.FormValue("title"))
|
||||
service.LectorsNeeded = parseInt(r.FormValue("lectors"), service.LectorsNeeded)
|
||||
service.HelpersNeeded = parseInt(r.FormValue("helpers"), service.HelpersNeeded)
|
||||
service.Notes = strings.TrimSpace(r.FormValue("notes"))
|
||||
service.Locked = r.FormValue("locked") == "1" || r.FormValue("locked") == "on"
|
||||
if service.Title == "" {
|
||||
s.setFlash(w, "Der Titel ist erforderlich.", "error")
|
||||
s.redirectBack(w, r, "/services/"+service.ID)
|
||||
return
|
||||
}
|
||||
if _, err := s.store.UpsertService(r.Context(), tenant.ID, *service); err != nil {
|
||||
s.setFlash(w, "Der Gottesdienst konnte nicht gespeichert werden: "+err.Error(), "error")
|
||||
} else {
|
||||
s.setFlash(w, "Gottesdienst gespeichert.", "success")
|
||||
}
|
||||
start, end := r.FormValue("start"), r.FormValue("end")
|
||||
target := "/services/" + service.ID
|
||||
if start != "" && end != "" {
|
||||
target += "?start=" + start + "&end=" + end
|
||||
}
|
||||
s.redirect(w, r, target)
|
||||
}
|
||||
|
||||
func (s *Server) handleServiceDelete(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
id := r.PathValue("id")
|
||||
service, err := s.store.Service(r.Context(), tenant.ID, id)
|
||||
if err != nil {
|
||||
s.redirect(w, r, "/plan")
|
||||
return
|
||||
}
|
||||
if service.Kind == domain.KindRegular {
|
||||
s.setFlash(w, "Regelmäßige Gottesdienste werden über die Gottesdienstordnung verwaltet und können nicht einzeln gelöscht werden.", "info")
|
||||
s.redirectBack(w, r, "/plan")
|
||||
return
|
||||
}
|
||||
if err := s.store.DeleteService(r.Context(), tenant.ID, id); err != nil {
|
||||
s.setFlash(w, "Der Gottesdienst konnte nicht gelöscht werden.", "error")
|
||||
s.redirectBack(w, r, "/services")
|
||||
return
|
||||
}
|
||||
s.setFlash(w, "Sondergottesdienst gelöscht.", "success")
|
||||
s.redirectBack(w, r, "/services")
|
||||
}
|
||||
|
||||
func (s *Server) handleSpecialServiceSave(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
date, ok := domain.DateFromKey(strings.TrimSpace(r.FormValue("date")))
|
||||
if !ok {
|
||||
date = domain.Today()
|
||||
}
|
||||
timeMinutes, ok := domain.ParseTimeString(r.FormValue("time"))
|
||||
if !ok {
|
||||
timeMinutes = 10 * 60
|
||||
}
|
||||
churchID := strings.TrimSpace(r.FormValue("church_id"))
|
||||
title := strings.TrimSpace(r.FormValue("title"))
|
||||
if churchID == "" || title == "" {
|
||||
s.setFlash(w, "Kirche und Titel sind erforderlich.", "error")
|
||||
s.redirectBack(w, r, "/services")
|
||||
return
|
||||
}
|
||||
location := strings.TrimSpace(r.FormValue("location"))
|
||||
var locationPtr *string
|
||||
if location != "" {
|
||||
locationPtr = &location
|
||||
}
|
||||
service := domain.ServiceOccurrence{
|
||||
ID: strings.TrimSpace(r.FormValue("id")),
|
||||
ChurchID: churchID, Location: locationPtr, Date: date, TimeMinutes: timeMinutes,
|
||||
Title: title, LectorsNeeded: parseInt(r.FormValue("lectors"), 1),
|
||||
HelpersNeeded: parseInt(r.FormValue("helpers"), 1), Kind: domain.KindSpecial,
|
||||
Notes: strings.TrimSpace(r.FormValue("notes")),
|
||||
}
|
||||
editing := service.ID != ""
|
||||
id, err := s.store.UpsertService(r.Context(), tenant.ID, service)
|
||||
if err != nil {
|
||||
s.setFlash(w, "Der Sondergottesdienst konnte nicht gespeichert werden: "+err.Error(), "error")
|
||||
s.redirectBack(w, r, "/services")
|
||||
return
|
||||
}
|
||||
if editing {
|
||||
s.setFlash(w, "Sondergottesdienst aktualisiert.", "success")
|
||||
} else {
|
||||
s.setFlash(w, "Sondergottesdienst angelegt.", "success")
|
||||
}
|
||||
s.redirect(w, r, "/services/"+id)
|
||||
}
|
||||
|
||||
func (s *Server) handleTemplateSave(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
id := strings.TrimSpace(r.FormValue("id"))
|
||||
churchID := strings.TrimSpace(r.FormValue("church_id"))
|
||||
title := strings.TrimSpace(r.FormValue("title"))
|
||||
weekday := parseInt(r.FormValue("weekday"), 1)
|
||||
timeMinutes, ok := domain.ParseTimeString(r.FormValue("time"))
|
||||
if !ok {
|
||||
timeMinutes = 10 * 60
|
||||
}
|
||||
validFrom, ok := domain.DateFromKey(strings.TrimSpace(r.FormValue("valid_from")))
|
||||
if !ok {
|
||||
validFrom = domain.MustDate("2024-01-01")
|
||||
}
|
||||
var validToTime *time.Time
|
||||
if raw := strings.TrimSpace(r.FormValue("valid_to")); raw != "" {
|
||||
if parsed, ok := domain.DateFromKey(raw); ok {
|
||||
validToTime = &parsed
|
||||
}
|
||||
}
|
||||
if churchID == "" || title == "" {
|
||||
s.setFlash(w, "Kirche und Titel sind erforderlich.", "error")
|
||||
s.redirectBack(w, r, "/services")
|
||||
return
|
||||
}
|
||||
template := domain.ServiceTemplate{
|
||||
ID: id, ChurchID: churchID, Weekday: weekday, TimeMinutes: timeMinutes,
|
||||
Title: title, LectorsNeeded: parseInt(r.FormValue("lectors"), 1),
|
||||
HelpersNeeded: parseInt(r.FormValue("helpers"), 1), ValidFrom: validFrom,
|
||||
ValidTo: validToTime, Active: r.FormValue("active") == "1" || r.FormValue("active") == "on",
|
||||
Notes: strings.TrimSpace(r.FormValue("notes")),
|
||||
}
|
||||
if err := s.store.UpsertTemplate(r.Context(), tenant.ID, template); err != nil {
|
||||
s.setFlash(w, "Die Vorlage konnte nicht gespeichert werden: "+err.Error(), "error")
|
||||
} else {
|
||||
s.setFlash(w, "Regelmäßiger Gottesdienst gespeichert.", "success")
|
||||
}
|
||||
s.redirectBack(w, r, "/services")
|
||||
}
|
||||
|
||||
func (s *Server) handleTemplateDelete(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
id := strings.TrimSpace(r.FormValue("id"))
|
||||
if err := s.store.DeleteTemplate(r.Context(), tenant.ID, id); err != nil {
|
||||
s.setFlash(w, "Die Vorlage konnte nicht gelöscht werden.", "error")
|
||||
} else {
|
||||
s.setFlash(w, "Vorlage gelöscht.", "success")
|
||||
}
|
||||
s.redirectBack(w, r, "/services")
|
||||
}
|
||||
|
||||
func (s *Server) handleExceptionSave(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
templateID := strings.TrimSpace(r.FormValue("template_id"))
|
||||
date, ok := domain.DateFromKey(strings.TrimSpace(r.FormValue("date")))
|
||||
if templateID == "" || !ok {
|
||||
s.setFlash(w, "Vorlage und Datum sind erforderlich.", "error")
|
||||
s.redirectBack(w, r, "/services")
|
||||
return
|
||||
}
|
||||
exception := domain.ServiceException{
|
||||
ID: strings.TrimSpace(r.FormValue("id")), TemplateID: templateID, Date: date,
|
||||
Reason: strings.TrimSpace(r.FormValue("reason")),
|
||||
}
|
||||
if exception.ID == "" {
|
||||
exception.ID = domain.NewID()
|
||||
}
|
||||
if err := s.store.UpsertException(r.Context(), tenant.ID, exception); err != nil {
|
||||
s.setFlash(w, "Die Ausnahme konnte nicht gespeichert werden.", "error")
|
||||
} else {
|
||||
s.setFlash(w, "Ausnahme gespeichert.", "success")
|
||||
}
|
||||
s.redirectBack(w, r, "/services")
|
||||
}
|
||||
|
||||
func (s *Server) handleExceptionDelete(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if err := s.store.DeleteException(r.Context(), tenant.ID, strings.TrimSpace(r.FormValue("id"))); err != nil {
|
||||
s.setFlash(w, "Die Ausnahme konnte nicht gelöscht werden.", "error")
|
||||
} else {
|
||||
s.setFlash(w, "Ausnahme gelöscht.", "success")
|
||||
}
|
||||
s.redirectBack(w, r, "/services")
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"lektorenplan/store"
|
||||
)
|
||||
|
||||
type settingsPageData struct {
|
||||
Settings map[string]string
|
||||
AutoSync bool
|
||||
Diocese string
|
||||
LastSync string
|
||||
Counts map[string]int
|
||||
ChurchCount int
|
||||
CanEdit bool
|
||||
Database string
|
||||
DemoReset bool
|
||||
}
|
||||
|
||||
var dioceseOptions = []struct {
|
||||
Key string
|
||||
Label string
|
||||
}{
|
||||
{"koeln", "Erzbistum Köln"},
|
||||
{"aachen", "Bistum Aachen"},
|
||||
{"muenster", "Bistum Münster"},
|
||||
{"paderborn", "Erzbistum Paderborn"},
|
||||
{"trier", "Bistum Trier"},
|
||||
{"limburg", "Bistum Limburg"},
|
||||
{"freiburg", "Erzbistum Freiburg"},
|
||||
{"mainz", "Bistum Mainz"},
|
||||
{"speyer", "Bistum Speyer"},
|
||||
{"wuerzburg", "Bistum Würzburg"},
|
||||
}
|
||||
|
||||
func (s *Server) handleSettings(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.renderNoTenant(w, r)
|
||||
return
|
||||
}
|
||||
settings, err := s.store.AllTenantSettings(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Einstellungen", err.Error())
|
||||
return
|
||||
}
|
||||
defaults := map[string]string{
|
||||
"planner.replaceExisting": "0",
|
||||
"planner.respectPreferredWeekdays": "1",
|
||||
"planner.allowDoubleRoles": "0",
|
||||
"planner.weightChurch": "8.0",
|
||||
"planner.weightService": "4.0",
|
||||
"planner.weightFairness": "2.2",
|
||||
"planner.weightDualRole": "14.0",
|
||||
"planner.maxPerDay": "1",
|
||||
}
|
||||
for key, value := range defaults {
|
||||
if _, ok := settings[key]; !ok {
|
||||
settings[key] = value
|
||||
}
|
||||
}
|
||||
counts, err := s.store.CountTenantData(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Einstellungen", err.Error())
|
||||
return
|
||||
}
|
||||
page := settingsPageData{
|
||||
Settings: settings,
|
||||
AutoSync: s.store.Setting(r.Context(), "autoSyncLiturgy") != "0",
|
||||
Diocese: s.store.Setting(r.Context(), "diocese"),
|
||||
LastSync: s.store.Setting(r.Context(), "lastLiturgicalSync"),
|
||||
Counts: counts,
|
||||
CanEdit: s.store.CanEditTenant(r.Context(), user, tenant.ID),
|
||||
Database: s.store.Path(),
|
||||
DemoReset: tenant.Slug == "bad-godesberg" || tenant.Slug == "rheinaue",
|
||||
}
|
||||
if page.Diocese == "" {
|
||||
page.Diocese = "koeln"
|
||||
}
|
||||
data := s.baseView(w, r, "Einstellungen", "settings")
|
||||
data.Data = page
|
||||
s.renderPage(w, r, "settings", data)
|
||||
}
|
||||
|
||||
func (s *Server) handleSettingsSave(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.redirect(w, r, "/plan")
|
||||
return
|
||||
}
|
||||
_ = s.store.SetSetting(r.Context(), "autoSyncLiturgy", boolSetting(r.FormValue("auto_sync")))
|
||||
diocese := strings.TrimSpace(r.FormValue("diocese"))
|
||||
if diocese == "" {
|
||||
diocese = "koeln"
|
||||
}
|
||||
_ = s.store.SetSetting(r.Context(), "diocese", diocese)
|
||||
|
||||
tenantValues := map[string]string{
|
||||
"planner.replaceExisting": boolSetting(r.FormValue("replace_existing")),
|
||||
"planner.respectPreferredWeekdays": boolSetting(r.FormValue("respect_weekdays")),
|
||||
"planner.allowDoubleRoles": boolSetting(r.FormValue("allow_double_roles")),
|
||||
"planner.weightChurch": floatSetting(r.FormValue("weight_church"), "8"),
|
||||
"planner.weightService": floatSetting(r.FormValue("weight_service"), "4"),
|
||||
"planner.weightFairness": floatSetting(r.FormValue("weight_fairness"), "2.2"),
|
||||
"planner.weightDualRole": floatSetting(r.FormValue("weight_dual"), "14"),
|
||||
"planner.maxPerDay": intSetting(r.FormValue("max_per_day"), "1", 1, 4),
|
||||
}
|
||||
for key, value := range tenantValues {
|
||||
if err := s.store.SetTenantSetting(r.Context(), tenant.ID, key, value); err != nil {
|
||||
s.setFlash(w, "Die Einstellungen konnten nicht gespeichert werden: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/settings")
|
||||
return
|
||||
}
|
||||
}
|
||||
_ = s.store.SetSetting(r.Context(), "respectPreferredWeekdays", tenantValues["planner.respectPreferredWeekdays"])
|
||||
_ = s.store.SetSetting(r.Context(), "fairnessWeight", tenantValues["planner.weightFairness"])
|
||||
s.setFlash(w, "Einstellungen gespeichert.", "success")
|
||||
s.redirect(w, r, "/settings")
|
||||
}
|
||||
|
||||
func (s *Server) handleResetDemo(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.redirect(w, r, "/plan")
|
||||
return
|
||||
}
|
||||
if tenant.Slug != "bad-godesberg" && tenant.Slug != "rheinaue" {
|
||||
s.setFlash(w, "Demo-Daten können nur für die mitgelieferten Demo-Mandanten wiederhergestellt werden.", "info")
|
||||
s.redirect(w, r, "/settings")
|
||||
return
|
||||
}
|
||||
if err := s.store.DeleteAllTenantData(r.Context(), tenant.ID); err != nil {
|
||||
s.setFlash(w, "Die Daten konnten nicht zurückgesetzt werden: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/settings")
|
||||
return
|
||||
}
|
||||
if err := s.store.SeedDemo(r.Context()); err != nil {
|
||||
s.setFlash(w, "Die Demo-Daten konnten nicht neu angelegt werden: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/settings")
|
||||
return
|
||||
}
|
||||
s.setFlash(w, "Demo-Daten wurden neu aufgebaut.", "success")
|
||||
s.redirect(w, r, "/plan")
|
||||
}
|
||||
|
||||
func (s *Server) handleDeleteTenantData(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.redirect(w, r, "/plan")
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(r.FormValue("confirm")) != "loeschen" {
|
||||
s.setFlash(w, "Bitte die Bestätigung „loeschen“ eingeben.", "error")
|
||||
s.redirect(w, r, "/settings")
|
||||
return
|
||||
}
|
||||
if err := s.store.DeleteAllTenantData(r.Context(), tenant.ID); err != nil {
|
||||
s.setFlash(w, "Die Daten konnten nicht gelöscht werden: "+err.Error(), "error")
|
||||
s.redirect(w, r, "/settings")
|
||||
return
|
||||
}
|
||||
s.setFlash(w, "Alle Planungsdaten dieses Mandanten wurden gelöscht.", "success")
|
||||
s.redirect(w, r, "/settings")
|
||||
}
|
||||
|
||||
func boolSetting(value string) string {
|
||||
if value == "1" || value == "on" || value == "true" {
|
||||
return "1"
|
||||
}
|
||||
return "0"
|
||||
}
|
||||
|
||||
func floatSetting(value, fallback string) string {
|
||||
value = strings.TrimSpace(strings.ReplaceAll(value, ",", "."))
|
||||
var parsed float64
|
||||
if _, err := fmt.Sscanf(value, "%f", &parsed); err != nil || parsed < 0 || parsed > 100 {
|
||||
return fallback
|
||||
}
|
||||
return fmt.Sprintf("%.1f", parsed)
|
||||
}
|
||||
|
||||
func intSetting(value, fallback string, min, max int) string {
|
||||
parsed := parseInt(value, -1)
|
||||
if parsed < min {
|
||||
parsed = parseInt(fallback, min)
|
||||
}
|
||||
if parsed > max {
|
||||
parsed = max
|
||||
}
|
||||
return fmt.Sprintf("%d", parsed)
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
/* LektorenPlan – kleine progressive Verbesserungen für die Web-Oberfläche. */
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
function onReady(fn) {
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", fn, { once: true });
|
||||
} else {
|
||||
fn();
|
||||
}
|
||||
}
|
||||
|
||||
/* Bestätigung vor destruktiven Formularen ------------------------------- */
|
||||
function initConfirmations() {
|
||||
document.querySelectorAll("form[data-confirm]").forEach(function (form) {
|
||||
form.addEventListener("submit", function (event) {
|
||||
var message = form.getAttribute("data-confirm");
|
||||
if (message && !window.confirm(message)) {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/* Gottesdienstplan filtern --------------------------------------------- */
|
||||
function initPlanFilters() {
|
||||
var table = document.querySelector("[data-plan-table]");
|
||||
var chips = document.querySelectorAll("[data-plan-filter]");
|
||||
if (!table || !chips.length) return;
|
||||
|
||||
var rows = Array.prototype.slice.call(table.querySelectorAll("[data-plan-row]"));
|
||||
var empty = document.createElement("tr");
|
||||
empty.className = "plan-filter-empty";
|
||||
empty.innerHTML = '<td colspan="99">Keine Tage passen zu diesem Filter.</td>';
|
||||
empty.hidden = true;
|
||||
|
||||
function apply(filter) {
|
||||
var visible = 0;
|
||||
rows.forEach(function (row) {
|
||||
var show = true;
|
||||
if (filter === "services") {
|
||||
show = row.getAttribute("data-has-services") === "true";
|
||||
} else if (filter === "open") {
|
||||
show = parseInt(row.getAttribute("data-open") || "0", 10) > 0;
|
||||
} else if (filter === "feasts") {
|
||||
show = row.getAttribute("data-special") === "true";
|
||||
}
|
||||
row.hidden = !show;
|
||||
if (show) visible++;
|
||||
});
|
||||
empty.hidden = visible !== 0;
|
||||
if (visible === 0 && empty.parentNode !== table.tBodies[0]) {
|
||||
table.tBodies[0].appendChild(empty);
|
||||
}
|
||||
}
|
||||
|
||||
chips.forEach(function (chip) {
|
||||
chip.addEventListener("click", function () {
|
||||
chips.forEach(function (other) { other.classList.remove("active"); });
|
||||
chip.classList.add("active");
|
||||
apply(chip.getAttribute("data-plan-filter"));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/* Team-Suche ------------------------------------------------------------ */
|
||||
function initPersonSearch() {
|
||||
var input = document.querySelector("[data-person-search]");
|
||||
var grid = document.querySelector("[data-person-grid]");
|
||||
if (!input || !grid) return;
|
||||
|
||||
var cards = Array.prototype.slice.call(grid.querySelectorAll("[data-person-name]"));
|
||||
var empty = document.querySelector("[data-search-empty]");
|
||||
|
||||
function apply() {
|
||||
var needle = input.value.trim().toLowerCase();
|
||||
var visible = 0;
|
||||
cards.forEach(function (card) {
|
||||
var haystack = card.getAttribute("data-person-name") || "";
|
||||
var show = needle === "" || haystack.indexOf(needle) !== -1;
|
||||
card.hidden = !show;
|
||||
if (show) visible++;
|
||||
});
|
||||
if (empty) empty.hidden = visible !== 0 || needle === "";
|
||||
}
|
||||
|
||||
input.addEventListener("input", apply);
|
||||
}
|
||||
|
||||
/* Datei-Auswahl per Drag & Drop ---------------------------------------- */
|
||||
function initFileDrop() {
|
||||
document.querySelectorAll("[data-file-drop]").forEach(function (drop) {
|
||||
var input = drop.querySelector("[data-file-input]");
|
||||
if (!input) return;
|
||||
|
||||
function highlight(active) {
|
||||
drop.classList.toggle("dragging", active);
|
||||
}
|
||||
|
||||
["dragenter", "dragover"].forEach(function (name) {
|
||||
drop.addEventListener(name, function (event) {
|
||||
event.preventDefault();
|
||||
highlight(true);
|
||||
});
|
||||
});
|
||||
["dragleave", "drop"].forEach(function (name) {
|
||||
drop.addEventListener(name, function (event) {
|
||||
event.preventDefault();
|
||||
highlight(false);
|
||||
});
|
||||
});
|
||||
drop.addEventListener("drop", function (event) {
|
||||
if (event.dataTransfer && event.dataTransfer.files.length) {
|
||||
input.files = event.dataTransfer.files;
|
||||
input.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
}
|
||||
});
|
||||
input.addEventListener("change", function () {
|
||||
var label = drop.querySelector("small");
|
||||
if (input.files && input.files.length && label) {
|
||||
label.textContent = input.files[0].name;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/* Mobile Navigation ----------------------------------------------------- */
|
||||
function initNavToggle() {
|
||||
var toggle = document.querySelector("[data-nav-toggle]");
|
||||
var sidebar = document.querySelector(".sidebar");
|
||||
if (!toggle || !sidebar) return;
|
||||
|
||||
function setOpen(open) {
|
||||
sidebar.classList.toggle("open", open);
|
||||
document.body.classList.toggle("nav-open", open);
|
||||
toggle.setAttribute("aria-expanded", open ? "true" : "false");
|
||||
}
|
||||
|
||||
var close = document.querySelector("[data-nav-close]");
|
||||
if (close) {
|
||||
close.addEventListener("click", function () { setOpen(false); });
|
||||
}
|
||||
|
||||
toggle.addEventListener("click", function (event) {
|
||||
event.stopPropagation();
|
||||
setOpen(!sidebar.classList.contains("open"));
|
||||
});
|
||||
sidebar.querySelectorAll("a").forEach(function (link) {
|
||||
link.addEventListener("click", function () { setOpen(false); });
|
||||
});
|
||||
document.addEventListener("click", function (event) {
|
||||
if (!sidebar.classList.contains("open")) return;
|
||||
if (sidebar.contains(event.target) || toggle.contains(event.target)) return;
|
||||
setOpen(false);
|
||||
});
|
||||
document.addEventListener("keydown", function (event) {
|
||||
if (event.key === "Escape") setOpen(false);
|
||||
});
|
||||
}
|
||||
|
||||
/* Einheiten für Zahlenfelder ------------------------------------------- */
|
||||
function initRangeOutputs() {
|
||||
document.querySelectorAll('input[type="range"]').forEach(function (input) {
|
||||
var output = document.getElementById(input.id + "-value");
|
||||
if (!output) return;
|
||||
function update() { output.textContent = input.value; }
|
||||
input.addEventListener("input", update);
|
||||
update();
|
||||
});
|
||||
}
|
||||
|
||||
/* Formular-Doppelversand verhindern ------------------------------------ */
|
||||
function initSubmitGuards() {
|
||||
document.querySelectorAll("form").forEach(function (form) {
|
||||
if (form.hasAttribute("data-confirm")) return;
|
||||
form.addEventListener("submit", function () {
|
||||
var button = form.querySelector('button[type="submit"]');
|
||||
if (!button) return;
|
||||
window.setTimeout(function () {
|
||||
button.disabled = true;
|
||||
button.classList.add("is-busy");
|
||||
}, 0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
onReady(function () {
|
||||
initConfirmations();
|
||||
initNavToggle();
|
||||
initPlanFilters();
|
||||
initPersonSearch();
|
||||
initFileDrop();
|
||||
initRangeOutputs();
|
||||
initSubmitGuards();
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,771 @@
|
||||
/* LektorenPlan Web – warme Papieroptik
|
||||
Farben: Tinte, Salbeigrün, Gold, Burgunder, warmes Papier. */
|
||||
|
||||
:root {
|
||||
--paper: #f5efe2;
|
||||
--paper-deep: #ede4d2;
|
||||
--paper-soft: #faf6ec;
|
||||
--card: #fffdf7;
|
||||
--card-alt: #f8f2e4;
|
||||
--ink: #2b332d;
|
||||
--ink-soft: #4a5047;
|
||||
--muted: #77715f;
|
||||
--muted-light: #9a937f;
|
||||
--line: #ddd2bd;
|
||||
--line-soft: #e9e0ce;
|
||||
--green: #315e50;
|
||||
--green-dark: #244a3f;
|
||||
--green-soft: #e3ece4;
|
||||
--gold: #b9943f;
|
||||
--gold-soft: #f4ead0;
|
||||
--burgundy: #7c3b3f;
|
||||
--burgundy-soft: #f3e2e1;
|
||||
--blue-soft: #e5ebef;
|
||||
--shadow-sm: 0 1px 2px rgba(54, 43, 25, .06), 0 2px 8px rgba(54, 43, 25, .04);
|
||||
--shadow: 0 2px 4px rgba(54, 43, 25, .06), 0 14px 34px rgba(54, 43, 25, .07);
|
||||
--radius: 14px;
|
||||
--radius-sm: 9px;
|
||||
--serif: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, Georgia, serif;
|
||||
--sans: "Avenir Next", Avenir, "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||
--mono: "SFMono-Regular", Menlo, Consolas, monospace;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html { min-height: 100%; }
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
color: var(--ink);
|
||||
font-family: var(--sans);
|
||||
font-size: 15px;
|
||||
line-height: 1.5;
|
||||
background:
|
||||
radial-gradient(1200px 600px at 82% -8%, rgba(194, 161, 77, .13), transparent 58%),
|
||||
radial-gradient(900px 500px at 4% 102%, rgba(49, 94, 80, .10), transparent 62%),
|
||||
linear-gradient(180deg, #fbf7ed 0%, var(--paper) 42%, #f1e9d9 100%);
|
||||
}
|
||||
|
||||
a { color: var(--green-dark); text-decoration: none; }
|
||||
a:hover { color: var(--green); }
|
||||
img, svg { max-width: 100%; }
|
||||
h1, h2, h3, h4, h5 { margin: 0; font-family: var(--serif); font-weight: 600; letter-spacing: -.012em; color: var(--ink); }
|
||||
h1 { font-size: 1.9rem; }
|
||||
h2 { font-size: 1.65rem; }
|
||||
h3 { font-size: 1.2rem; }
|
||||
h4 { font-size: 1.02rem; }
|
||||
p { margin: 0; }
|
||||
small { font-size: .82em; }
|
||||
button, input, select, textarea { font: inherit; color: inherit; }
|
||||
button { cursor: pointer; }
|
||||
table { border-collapse: collapse; width: 100%; }
|
||||
hr { border: 0; border-top: 1px solid var(--line); margin: 1rem 0; }
|
||||
|
||||
.eyebrow {
|
||||
display: block;
|
||||
font-size: .7rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: .14em;
|
||||
text-transform: uppercase;
|
||||
color: var(--gold);
|
||||
margin-bottom: .25rem;
|
||||
}
|
||||
|
||||
.icon { width: 18px; height: 18px; flex: 0 0 auto; }
|
||||
.muted { color: var(--muted); }
|
||||
.mono { font-family: var(--mono); font-size: .82rem; word-break: break-all; }
|
||||
.muted-row { opacity: .62; }
|
||||
.hidden, [hidden] { display: none !important; }
|
||||
|
||||
/* ---------- Buttons and chips ---------- */
|
||||
.btn {
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: .45rem;
|
||||
min-height: 40px; padding: .55rem 1rem;
|
||||
border: 1px solid transparent; border-radius: 999px;
|
||||
font-weight: 650; font-size: .9rem; line-height: 1.1;
|
||||
transition: transform .12s ease, background .15s ease, box-shadow .15s ease, border-color .15s ease;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.btn:hover { transform: translateY(-1px); }
|
||||
.btn:active { transform: translateY(0); }
|
||||
.btn-primary { background: var(--green); color: #fffdf6; box-shadow: 0 4px 12px rgba(36, 74, 63, .22); }
|
||||
.btn-primary:hover { background: var(--green-dark); color: #fff; }
|
||||
.btn-secondary { background: var(--gold-soft); color: #5d4718; border-color: #dcc98f; }
|
||||
.btn-secondary:hover { background: #efdfae; color: #4b390f; }
|
||||
.btn-ghost { background: rgba(255, 253, 247, .5); border-color: var(--line); color: var(--ink-soft); }
|
||||
.btn-ghost:hover { background: var(--card); border-color: var(--gold); color: var(--ink); }
|
||||
.btn-danger { background: var(--burgundy); color: #fff7f3; }
|
||||
.btn-danger:hover { background: #652e32; color: #fff; }
|
||||
.btn-small { min-height: 34px; padding: .38rem .78rem; font-size: .82rem; }
|
||||
.btn-tiny { min-height: 30px; padding: .3rem .65rem; font-size: .76rem; }
|
||||
.btn-block { width: 100%; }
|
||||
.btn:disabled, button:disabled { opacity: .45; cursor: not-allowed; transform: none; }
|
||||
|
||||
.icon-button {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
width: 32px; height: 32px; padding: 0;
|
||||
border: 1px solid transparent; border-radius: 8px;
|
||||
background: transparent; color: var(--muted);
|
||||
transition: background .14s ease, color .14s ease, border-color .14s ease;
|
||||
}
|
||||
.icon-button:hover { background: var(--paper-deep); color: var(--ink); border-color: var(--line-soft); }
|
||||
.icon-button.danger:hover { background: var(--burgundy-soft); color: var(--burgundy); }
|
||||
.icon-button:disabled { opacity: .35; }
|
||||
|
||||
.chip {
|
||||
display: inline-flex; align-items: center; gap: .35rem;
|
||||
min-height: 32px; padding: .34rem .7rem;
|
||||
border: 1px solid var(--line); border-radius: 999px;
|
||||
background: rgba(255, 253, 247, .6); color: var(--ink-soft);
|
||||
font-size: .8rem; font-weight: 550; white-space: nowrap;
|
||||
transition: background .14s ease, border-color .14s ease, color .14s ease;
|
||||
}
|
||||
.chip:hover { background: var(--card); border-color: var(--gold); color: var(--ink); }
|
||||
.chip.active { background: var(--green); border-color: var(--green); color: #fff; }
|
||||
.chip .icon { width: 15px; height: 15px; }
|
||||
|
||||
.text-link { display: inline-flex; align-items: center; gap: .25rem; font-weight: 600; font-size: .86rem; }
|
||||
.text-link .icon { width: 15px; height: 15px; }
|
||||
|
||||
/* ---------- Badges, avatars ---------- */
|
||||
.badge {
|
||||
display: inline-flex; align-items: center; gap: .28rem;
|
||||
padding: .18rem .5rem; border-radius: 999px;
|
||||
font-size: .68rem; font-weight: 700; letter-spacing: .035em;
|
||||
line-height: 1.35; white-space: nowrap;
|
||||
}
|
||||
.badge-neutral { background: #f0eadc; color: #68614f; border: 1px solid #e3d8c3; }
|
||||
.badge-green { background: var(--green-soft); color: var(--green-dark); border: 1px solid #c9dbce; }
|
||||
.badge-gold { background: var(--gold-soft); color: #6b511a; border: 1px solid #e6d49f; }
|
||||
.badge-burgundy { background: var(--burgundy-soft); color: var(--burgundy); border: 1px solid #e6c8c7; }
|
||||
.badge-rank { text-transform: uppercase; letter-spacing: .08em; }
|
||||
.badge-rank.rank-H, .badge-rank.rank-F { background: var(--burgundy-soft); color: var(--burgundy); border-color: #e5c4c3; }
|
||||
.badge-rank.rank-G, .badge-rank.rank-g { background: var(--gold-soft); color: #6b511a; border-color: #e6d49f; }
|
||||
.badge-color { background: color-mix(in srgb, var(--badge-color) 15%, #fff); color: color-mix(in srgb, var(--badge-color) 78%, #222); border: 1px solid color-mix(in srgb, var(--badge-color) 35%, #fff); }
|
||||
.badge-color::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--badge-color); }
|
||||
.badge-row { display: flex; flex-wrap: wrap; gap: .35rem; align-items: center; }
|
||||
|
||||
.count-pill {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
min-width: 28px; height: 26px; padding: 0 .55rem;
|
||||
border-radius: 999px; background: var(--paper-deep); color: var(--ink-soft);
|
||||
font-size: .78rem; font-weight: 700;
|
||||
}
|
||||
.count-pill.warn { background: var(--burgundy-soft); color: var(--burgundy); }
|
||||
|
||||
.avatar {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
width: 42px; height: 42px; border-radius: 50%;
|
||||
background: linear-gradient(145deg, #dce8de, #f2ecdc);
|
||||
border: 1px solid #cbd9ca; color: var(--green-dark);
|
||||
font-family: var(--serif); font-size: .95rem; font-weight: 700;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.avatar.small { width: 32px; height: 32px; font-size: .78rem; }
|
||||
.avatar.tiny { width: 27px; height: 27px; font-size: .7rem; }
|
||||
.avatar.large { width: 66px; height: 66px; font-size: 1.4rem; }
|
||||
|
||||
.demo-pill {
|
||||
display: inline-flex; padding: .1rem .45rem; border-radius: 999px;
|
||||
background: var(--gold-soft); color: #725518; font-size: .64rem;
|
||||
font-weight: 800; letter-spacing: .09em; text-transform: uppercase;
|
||||
}
|
||||
|
||||
/* ---------- App shell ---------- */
|
||||
.app-shell { display: flex; min-height: 100vh; align-items: stretch; }
|
||||
.sidebar {
|
||||
position: sticky; top: 0; align-self: flex-start;
|
||||
display: flex; flex-direction: column;
|
||||
width: 268px; min-height: 100vh; max-height: 100vh;
|
||||
padding: 1.2rem 1rem 1rem;
|
||||
background:
|
||||
linear-gradient(180deg, rgba(255, 253, 247, .82), rgba(246, 239, 226, .92)),
|
||||
radial-gradient(400px 180px at 0% 0%, rgba(194, 161, 77, .13), transparent 70%);
|
||||
border-right: 1px solid var(--line);
|
||||
overflow-y: auto;
|
||||
z-index: 10;
|
||||
}
|
||||
.brand { display: flex; align-items: center; gap: .7rem; color: var(--ink); padding: .2rem .35rem 1rem; }
|
||||
.brand:hover { color: var(--ink); }
|
||||
.brand-mark {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
width: 44px; height: 44px; border-radius: 12px;
|
||||
background: linear-gradient(150deg, #f9f0d8, #e8dcc1);
|
||||
border: 1px solid #d9c89e; color: var(--green-dark);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .6);
|
||||
}
|
||||
.brand-mark svg { width: 30px; height: 30px; }
|
||||
.brand-mark.large { width: 64px; height: 64px; border-radius: 18px; }
|
||||
.brand-mark.large svg { width: 46px; height: 46px; }
|
||||
.brand-text { display: flex; flex-direction: column; line-height: 1.15; }
|
||||
.brand-text strong { font-family: var(--serif); font-size: 1.28rem; letter-spacing: -.02em; }
|
||||
.brand-text small { color: var(--muted); font-size: .67rem; letter-spacing: .04em; }
|
||||
|
||||
.tenant-switch { padding: .6rem .35rem .9rem; border-top: 1px solid var(--line-soft); border-bottom: 1px solid var(--line-soft); }
|
||||
.field-caption { display: block; margin-bottom: .3rem; color: var(--muted); font-size: .65rem; font-weight: 750; letter-spacing: .1em; text-transform: uppercase; }
|
||||
.tenant-form select {
|
||||
width: 100%; padding: .5rem .6rem; border: 1px solid var(--line); border-radius: 8px;
|
||||
background: var(--card); font-size: .85rem; font-weight: 600;
|
||||
}
|
||||
|
||||
.nav { display: flex; flex-direction: column; gap: .16rem; padding: .9rem 0 1rem; }
|
||||
.nav-heading { margin: .85rem .55rem .3rem; color: var(--muted-light); font-size: .62rem; font-weight: 800; letter-spacing: .14em; text-transform: uppercase; }
|
||||
.nav-link {
|
||||
display: flex; align-items: center; gap: .65rem;
|
||||
padding: .52rem .7rem; border-radius: 9px;
|
||||
color: var(--ink-soft); font-size: .87rem; font-weight: 560;
|
||||
border: 1px solid transparent;
|
||||
transition: background .13s ease, color .13s ease, border-color .13s ease;
|
||||
}
|
||||
.nav-link .icon { width: 17px; height: 17px; color: var(--muted); }
|
||||
.nav-link:hover { background: rgba(255, 253, 247, .85); color: var(--ink); border-color: var(--line-soft); }
|
||||
.nav-link.active { background: var(--green); color: #fffdf7; border-color: var(--green); box-shadow: 0 4px 12px rgba(36, 74, 63, .16); }
|
||||
.nav-link.active .icon { color: #f1e8d3; }
|
||||
.sidebar-foot { margin-top: auto; padding: 1rem .35rem .2rem; border-top: 1px solid var(--line-soft); display: flex; flex-direction: column; gap: .25rem; color: var(--muted); font-size: .68rem; }
|
||||
.sidebar-foot .version { font-weight: 650; }
|
||||
.sidebar-foot .source { color: var(--muted-light); }
|
||||
|
||||
.app-main { flex: 1; min-width: 0; display: flex; flex-direction: column; }
|
||||
.topbar {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 1rem;
|
||||
padding: 1.15rem clamp(1.1rem, 2.6vw, 2.2rem) 1rem;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
}
|
||||
.topbar-left { display: flex; align-items: center; gap: .65rem; min-width: 0; }
|
||||
.nav-toggle { display: none; flex: 0 0 auto; }
|
||||
.sidebar-close { display: none; position: absolute; top: .95rem; right: .8rem; }
|
||||
.topbar-title .eyebrow { margin-bottom: .1rem; }
|
||||
.topbar-title h1 { font-size: clamp(1.45rem, 2.3vw, 2rem); line-height: 1.1; }
|
||||
.topbar-actions { display: flex; align-items: center; gap: .6rem; }
|
||||
.account { display: flex; align-items: center; gap: .55rem; padding: .28rem .35rem .28rem .55rem; border-left: 1px solid var(--line); margin-left: .25rem; }
|
||||
.account-text { display: flex; flex-direction: column; line-height: 1.15; min-width: 0; }
|
||||
.account-text strong { font-size: .8rem; max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.account-text small { color: var(--muted); font-size: .67rem; }
|
||||
|
||||
.content { flex: 1; padding: 1.25rem clamp(1.1rem, 2.6vw, 2.2rem) 2.2rem; }
|
||||
.app-footer {
|
||||
display: flex; flex-wrap: wrap; justify-content: space-between; gap: .5rem;
|
||||
padding: .8rem clamp(1.1rem, 2.6vw, 2.2rem) 1.2rem;
|
||||
border-top: 1px solid var(--line-soft);
|
||||
color: var(--muted-light); font-size: .68rem;
|
||||
}
|
||||
|
||||
.page-stack { display: flex; flex-direction: column; gap: 1rem; }
|
||||
.card {
|
||||
background: rgba(255, 253, 247, .9);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-sm);
|
||||
padding: 1.1rem 1.15rem;
|
||||
backdrop-filter: blur(2px);
|
||||
}
|
||||
.card-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 1rem; margin-bottom: .9rem; }
|
||||
.card-head h3 { margin-top: .1rem; }
|
||||
.card-head .eyebrow { margin-bottom: .15rem; }
|
||||
.card-foot { margin-top: 1rem; padding-top: .9rem; border-top: 1px solid var(--line-soft); display: flex; justify-content: flex-end; }
|
||||
.two-column { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 1rem; align-items: start; }
|
||||
.two-column > .page-stack { gap: 1rem; }
|
||||
|
||||
/* ---------- Flash, notice ---------- */
|
||||
.flash {
|
||||
display: flex; align-items: flex-start; gap: .65rem;
|
||||
margin: 1rem clamp(1.1rem, 2.6vw, 2.2rem) 0;
|
||||
padding: .7rem .9rem;
|
||||
border-radius: 10px; border: 1px solid #c9dbce;
|
||||
background: #eef5ec; color: #2e5545; font-size: .88rem; font-weight: 550;
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
.flash-error { background: #f9e9e7; border-color: #e5bfbb; color: #743236; }
|
||||
.flash-info { background: #f6efd9; border-color: #e1d19e; color: #6c561d; }
|
||||
.flash-icon {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
width: 20px; height: 20px; border-radius: 50%;
|
||||
background: rgba(255, 255, 255, .65); font-size: .72rem; font-weight: 800;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.notice {
|
||||
display: flex; gap: .8rem; align-items: flex-start;
|
||||
padding: .9rem 1rem; border: 1px dashed #d7c58f; border-radius: var(--radius-sm);
|
||||
background: linear-gradient(135deg, #fbf5e4, #f7eed7); color: #5d4a1c;
|
||||
font-size: .87rem;
|
||||
}
|
||||
.notice .icon { color: var(--gold); width: 22px; height: 22px; margin-top: .1rem; }
|
||||
.notice strong { display: block; margin-bottom: .1rem; }
|
||||
|
||||
/* ---------- Page intro / toolbar ---------- */
|
||||
.page-intro { display: flex; align-items: flex-end; justify-content: space-between; gap: 1.5rem; padding: .35rem .2rem .2rem; }
|
||||
.page-intro h2 { font-size: clamp(1.5rem, 2.4vw, 2rem); margin-bottom: .3rem; }
|
||||
.page-intro p { max-width: 70ch; color: var(--muted); font-size: .9rem; }
|
||||
.intro-actions { display: flex; gap: .5rem; align-items: center; flex-wrap: wrap; justify-content: flex-end; }
|
||||
.intro-stats { display: flex; gap: 1.4rem; padding: .35rem .2rem; }
|
||||
.intro-stats div { display: flex; flex-direction: column; align-items: flex-end; }
|
||||
.intro-stats strong { font-family: var(--serif); font-size: 1.55rem; line-height: 1; color: var(--green-dark); }
|
||||
.intro-stats span { font-size: .68rem; color: var(--muted); text-transform: uppercase; letter-spacing: .08em; }
|
||||
|
||||
.toolbar { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; padding: .7rem .9rem; }
|
||||
.toolbar-group { display: flex; align-items: center; gap: .45rem; flex-wrap: wrap; }
|
||||
.range-nav { gap: .35rem; }
|
||||
.range-form { display: flex; align-items: flex-end; gap: .45rem; flex-wrap: wrap; }
|
||||
.field-inline { display: flex; flex-direction: column; gap: .15rem; }
|
||||
.field-inline span { color: var(--muted); font-size: .64rem; font-weight: 700; letter-spacing: .06em; text-transform: uppercase; }
|
||||
.field-inline input { min-height: 34px; padding: .25rem .45rem; border: 1px solid var(--line); border-radius: 7px; background: var(--card); font-size: .82rem; }
|
||||
.inline-form { display: inline-flex; }
|
||||
.inline-range { margin-top: .6rem; }
|
||||
|
||||
.range-banner {
|
||||
display: flex; justify-content: space-between; align-items: center; gap: 1.2rem; flex-wrap: wrap;
|
||||
padding: 1rem 1.2rem;
|
||||
border: 1px solid #d9c9a2; border-radius: var(--radius);
|
||||
background:
|
||||
linear-gradient(120deg, rgba(255, 252, 243, .95), rgba(247, 238, 216, .9)),
|
||||
radial-gradient(500px 160px at 100% 0%, rgba(49, 94, 80, .1), transparent 60%);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
.range-banner h2 { font-size: clamp(1.3rem, 2vw, 1.75rem); }
|
||||
.range-banner p { color: var(--muted); font-size: .86rem; margin-top: .15rem; }
|
||||
.range-actions { display: flex; align-items: center; gap: .45rem; flex-wrap: wrap; justify-content: flex-end; }
|
||||
|
||||
.stat-strip { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: .75rem; }
|
||||
.stat-strip.four { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||
.mini-stat {
|
||||
display: flex; flex-direction: column; gap: .1rem;
|
||||
padding: .8rem .9rem; border: 1px solid var(--line); border-radius: 12px;
|
||||
background: rgba(255, 253, 247, .75); box-shadow: var(--shadow-sm);
|
||||
}
|
||||
.mini-stat-label { color: var(--muted); font-size: .67rem; font-weight: 750; letter-spacing: .09em; text-transform: uppercase; }
|
||||
.mini-stat strong { font-family: var(--serif); font-size: 1.55rem; line-height: 1.1; color: var(--green-dark); }
|
||||
.mini-stat small { color: var(--muted); font-size: .72rem; }
|
||||
.mini-stat.warn strong { color: var(--burgundy); }
|
||||
|
||||
/* ---------- Forms ---------- */
|
||||
.form-stack { display: flex; flex-direction: column; gap: .8rem; }
|
||||
.form-stack.compact { gap: .55rem; }
|
||||
.form-row { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .7rem; }
|
||||
.form-row.three { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.field { display: flex; flex-direction: column; gap: .22rem; min-width: 0; }
|
||||
.field.narrow { max-width: 280px; }
|
||||
.field-label { color: var(--ink-soft); font-size: .74rem; font-weight: 700; letter-spacing: .015em; }
|
||||
.field-label small { color: var(--muted); font-weight: 500; }
|
||||
.field input, .field select, .field textarea {
|
||||
width: 100%; min-height: 38px; padding: .45rem .6rem;
|
||||
border: 1px solid var(--line); border-radius: 8px;
|
||||
background: var(--card); color: var(--ink);
|
||||
font-size: .88rem;
|
||||
transition: border-color .14s ease, box-shadow .14s ease;
|
||||
}
|
||||
.field textarea { min-height: 66px; resize: vertical; line-height: 1.4; }
|
||||
.field input:focus, .field select:focus, .field textarea:focus {
|
||||
outline: none; border-color: var(--green); box-shadow: 0 0 0 3px rgba(49, 94, 80, .12);
|
||||
}
|
||||
.field input[type="color"] { padding: .18rem; min-height: 38px; }
|
||||
.field-group { display: flex; flex-direction: column; gap: .35rem; }
|
||||
.field-hint { color: var(--muted); font-size: .75rem; }
|
||||
.checkbox-row { display: flex; flex-wrap: wrap; gap: .7rem 1.1rem; }
|
||||
.checkbox-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .35rem .9rem; }
|
||||
.checkbox-list { display: flex; flex-direction: column; gap: .35rem; max-height: 220px; overflow-y: auto; padding: .1rem; }
|
||||
.check { display: inline-flex; align-items: flex-start; gap: .45rem; color: var(--ink-soft); font-size: .84rem; cursor: pointer; }
|
||||
.check input { width: 15px; height: 15px; margin-top: .13rem; accent-color: var(--green); flex: 0 0 auto; }
|
||||
.check.standalone { padding-top: .3rem; }
|
||||
.check-inline { display: inline-flex; align-items: center; gap: .3rem; color: var(--muted); font-size: .72rem; white-space: nowrap; }
|
||||
.check-inline input { accent-color: var(--green); }
|
||||
.weekday-grid { display: flex; gap: .35rem; flex-wrap: wrap; }
|
||||
.weekday-check input { position: absolute; opacity: 0; width: 0; height: 0; }
|
||||
.weekday-check span {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
width: 38px; height: 34px; border-radius: 8px;
|
||||
border: 1px solid var(--line); background: var(--card);
|
||||
color: var(--muted); font-size: .76rem; font-weight: 700; cursor: pointer;
|
||||
}
|
||||
.weekday-check input:checked + span { background: var(--green); border-color: var(--green); color: #fff; }
|
||||
.form-actions { display: flex; align-items: center; gap: .5rem; flex-wrap: wrap; }
|
||||
.search-field { display: flex; align-items: center; gap: .4rem; padding: .3rem .6rem; border: 1px solid var(--line); border-radius: 999px; background: var(--card); }
|
||||
.search-field .icon { width: 16px; height: 16px; color: var(--muted); }
|
||||
.search-field input { border: 0; background: transparent; outline: none; font-size: .83rem; min-width: 180px; }
|
||||
|
||||
.file-drop {
|
||||
display: flex; align-items: center; gap: .9rem;
|
||||
padding: 1.3rem 1rem; border: 1.5px dashed #cdbfa0; border-radius: 12px;
|
||||
background: linear-gradient(135deg, #fcf8ee, #f6eedd); cursor: pointer;
|
||||
transition: border-color .15s ease, background .15s ease;
|
||||
}
|
||||
.file-drop:hover, .file-drop.dragging { border-color: var(--green); background: #f1f4e8; }
|
||||
.file-drop .icon { width: 28px; height: 28px; color: var(--green); }
|
||||
.file-drop span { display: flex; flex-direction: column; }
|
||||
.file-drop strong { font-size: .9rem; }
|
||||
.file-drop small { color: var(--muted); font-size: .75rem; }
|
||||
.file-drop input { display: none; }
|
||||
.btn.is-busy, button.is-busy { opacity: .55; cursor: progress; }
|
||||
.plan-filter-empty td { padding: 2rem 1rem; text-align: center; color: var(--muted); }
|
||||
|
||||
/* ---------- Tables ---------- */
|
||||
.table-scroll { overflow-x: auto; -webkit-overflow-scrolling: touch; }
|
||||
.data-table th, .data-table td { padding: .55rem .5rem; border-bottom: 1px solid var(--line-soft); text-align: left; font-size: .83rem; vertical-align: middle; }
|
||||
.data-table thead th { color: var(--muted); font-size: .66rem; font-weight: 750; letter-spacing: .08em; text-transform: uppercase; border-bottom: 1px solid var(--line); }
|
||||
.data-table tbody tr:hover { background: rgba(247, 241, 227, .7); }
|
||||
.data-table td small { color: var(--muted); }
|
||||
.data-table .row-actions, .row-actions { display: flex; align-items: center; gap: .1rem; justify-content: flex-end; }
|
||||
.compact-table th, .compact-table td { padding: .42rem .35rem; }
|
||||
.person-inline { display: inline-flex; align-items: center; gap: .45rem; }
|
||||
.person-inline > span:last-child { display: flex; flex-direction: column; line-height: 1.2; }
|
||||
.person-inline strong { font-size: .83rem; }
|
||||
.person-inline small { color: var(--muted); font-size: .7rem; }
|
||||
.tenant-tags { display: flex; flex-wrap: wrap; gap: .2rem; max-width: 330px; }
|
||||
.table-note { color: var(--muted); font-size: .74rem; padding: 0 .25rem; }
|
||||
|
||||
.calendar-card { background: rgba(255, 253, 247, .9); border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow); overflow: hidden; }
|
||||
.calendar-table { min-width: 960px; }
|
||||
.calendar-table thead th {
|
||||
position: sticky; top: 0; z-index: 2;
|
||||
padding: .55rem .45rem; text-align: left;
|
||||
background: #f8f2e4;
|
||||
border-bottom: 1px solid var(--line);
|
||||
color: var(--muted); font-size: .65rem; font-weight: 750; letter-spacing: .08em; text-transform: uppercase;
|
||||
}
|
||||
.calendar-table thead th.col-date { width: 78px; }
|
||||
.calendar-table thead th.col-liturgy { width: 27%; }
|
||||
.calendar-table .col-church { min-width: 165px; }
|
||||
.calendar-table td { border-bottom: 1px solid var(--line-soft); padding: .48rem .45rem; vertical-align: top; font-size: .8rem; }
|
||||
.plan-row.is-sunday { background: rgba(248, 240, 218, .55); }
|
||||
.plan-row.is-highfeast { background: rgba(124, 59, 63, .075); }
|
||||
.plan-row.is-feast { background: rgba(194, 161, 77, .09); }
|
||||
.plan-row.is-obligation { background: rgba(49, 94, 80, .06); }
|
||||
.plan-row:hover { background: rgba(239, 233, 217, .65); }
|
||||
.date-cell { position: relative; padding-left: .7rem !important; }
|
||||
.date-number { font-family: var(--serif); font-size: 1.32rem; line-height: 1; font-weight: 650; }
|
||||
.date-meta { display: flex; gap: .28rem; color: var(--muted); font-size: .65rem; margin-top: .12rem; text-transform: uppercase; letter-spacing: .04em; }
|
||||
.liturgical-bar { position: absolute; left: 0; top: .45rem; bottom: .45rem; width: 3px; border-radius: 3px; opacity: .85; }
|
||||
.liturgy-title { display: flex; align-items: flex-start; gap: .35rem; font-size: .82rem; line-height: 1.3; }
|
||||
.liturgy-title strong { font-weight: 650; }
|
||||
.feast-glyph { width: 17px; height: 17px; flex: 0 0 auto; color: var(--gold); margin-top: .05rem; }
|
||||
.liturgy-meta { display: flex; flex-wrap: wrap; gap: .2rem; margin-top: .22rem; }
|
||||
.readings { margin-top: .25rem; color: var(--muted); font-size: .69rem; line-height: 1.35; }
|
||||
.liturgy-remark { margin-top: .16rem; color: var(--muted); font-size: .68rem; font-style: italic; }
|
||||
.church-cell { background: rgba(255, 253, 247, .35); }
|
||||
.empty-cell { color: #c7bda7; font-size: .9rem; }
|
||||
.service-stack { display: flex; flex-direction: column; gap: .25rem; }
|
||||
.service-card {
|
||||
display: flex; flex-direction: column; gap: .06rem;
|
||||
padding: .28rem .38rem; border-radius: 7px;
|
||||
border: 1px solid transparent; background: rgba(255, 255, 255, .55);
|
||||
color: var(--ink); line-height: 1.25;
|
||||
transition: background .13s ease, border-color .13s ease, transform .13s ease;
|
||||
}
|
||||
.service-card:hover { background: #fffdf7; border-color: #d8c9a9; transform: translateY(-1px); color: var(--ink); }
|
||||
.service-card.open { border-left: 3px solid var(--burgundy); }
|
||||
.service-card.staffed { border-left: 3px solid var(--green); }
|
||||
.service-time { font-size: .66rem; font-weight: 750; color: var(--muted); letter-spacing: .03em; }
|
||||
.service-title { font-size: .76rem; font-weight: 650; }
|
||||
.service-kind { margin-left: .25rem; padding: 0 .25rem; border-radius: 4px; background: var(--burgundy-soft); color: var(--burgundy); font-size: .55rem; font-weight: 800; text-transform: uppercase; letter-spacing: .04em; }
|
||||
.service-location { color: var(--muted); font-size: .65rem; font-style: italic; }
|
||||
.service-people { display: flex; flex-wrap: wrap; gap: .18rem; margin-top: .13rem; }
|
||||
.person-chip { padding: 0 .28rem; border-radius: 4px; font-size: .62rem; font-weight: 650; background: #eef2e8; color: var(--green-dark); }
|
||||
.person-chip.role-K { background: var(--gold-soft); color: #6d5219; }
|
||||
.open-badge { color: var(--burgundy); font-size: .6rem; font-weight: 750; }
|
||||
.church-head { display: flex; align-items: center; gap: .4rem; }
|
||||
.church-glyph { width: 38px; height: 28px; flex: 0 0 auto; }
|
||||
.church-head-text { display: flex; flex-direction: column; line-height: 1.15; }
|
||||
.church-head-text strong { color: var(--ink-soft); font-size: .74rem; text-transform: none; letter-spacing: 0; }
|
||||
.church-head-text small { color: var(--muted); font-size: .6rem; text-transform: none; letter-spacing: 0; }
|
||||
|
||||
.plan-legend { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; padding: 0 .15rem; }
|
||||
.filter-chips { display: flex; gap: .3rem; flex-wrap: wrap; }
|
||||
.legend-items { display: flex; gap: .8rem; flex-wrap: wrap; color: var(--muted); font-size: .72rem; }
|
||||
.legend-items span { display: inline-flex; align-items: center; gap: .3rem; }
|
||||
.swatch { width: 13px; height: 13px; border-radius: 3px; display: inline-block; border: 1px solid var(--line); }
|
||||
.swatch.sunday { background: #f8f0da; }
|
||||
.swatch.feast { background: #f0dfe0; }
|
||||
.swatch.open { background: var(--burgundy); border-color: var(--burgundy); }
|
||||
|
||||
/* ---------- Church overview ---------- */
|
||||
.church-overview { display: grid; grid-template-columns: repeat(auto-fit, minmax(330px, 1fr)); gap: 1rem; }
|
||||
.church-card { border: 1px solid var(--line); border-radius: var(--radius); background: rgba(255, 253, 247, .88); box-shadow: var(--shadow-sm); padding: .9rem 1rem; }
|
||||
.church-card-head { display: flex; align-items: center; gap: .75rem; padding-bottom: .65rem; border-bottom: 1px solid var(--line-soft); }
|
||||
.church-card-head .church-glyph { width: 56px; height: 40px; color: var(--green-dark); }
|
||||
.church-card-head h3 { font-size: 1.05rem; }
|
||||
.church-card-head p { color: var(--muted); font-size: .72rem; }
|
||||
.church-card-head .count-pill { margin-left: auto; }
|
||||
.template-list { display: flex; flex-direction: column; }
|
||||
.template-row { display: flex; align-items: center; gap: .65rem; padding: .55rem 0; border-bottom: 1px solid var(--line-soft); }
|
||||
.template-row:last-child { border-bottom: 0; }
|
||||
.template-when { display: flex; flex-direction: column; min-width: 76px; }
|
||||
.template-when strong { font-size: .76rem; color: var(--green-dark); }
|
||||
.template-when span { font-size: .7rem; color: var(--muted); }
|
||||
.template-main { display: flex; flex-direction: column; flex: 1; min-width: 0; }
|
||||
.template-main strong { font-size: .82rem; }
|
||||
.template-main small { color: var(--muted); font-size: .68rem; }
|
||||
.template-actions { display: flex; align-items: center; gap: .1rem; }
|
||||
|
||||
/* ---------- Detail pages ---------- */
|
||||
.detail-hero { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; padding: 1.1rem 1.2rem; }
|
||||
.detail-hero-main { display: flex; align-items: center; gap: 1rem; min-width: 0; }
|
||||
.detail-church .church-glyph { width: 96px; height: 68px; color: var(--green-dark); }
|
||||
.detail-hero h2 { font-size: clamp(1.4rem, 2.2vw, 1.85rem); }
|
||||
.detail-place { color: var(--muted); font-size: .85rem; margin: .1rem 0 .4rem; }
|
||||
.detail-hero-actions { display: flex; align-items: center; gap: .4rem; flex-wrap: wrap; }
|
||||
.detail-grid { display: grid; grid-template-columns: minmax(0, 1.55fr) minmax(300px, .9fr); gap: 1rem; align-items: start; }
|
||||
.detail-list { display: grid; grid-template-columns: auto 1fr; gap: .4rem .8rem; margin: .2rem 0 0; font-size: .84rem; }
|
||||
.detail-list dt { color: var(--muted); font-size: .72rem; font-weight: 650; }
|
||||
.detail-list dd { margin: 0; }
|
||||
.detail-list.tight { gap: .3rem .8rem; margin-top: .8rem; }
|
||||
.side-note { background: linear-gradient(145deg, #faf4e5, #f6eedc); border-color: #ddd0ad; }
|
||||
.side-note p { color: #635535; font-size: .84rem; margin: .2rem 0 .6rem; }
|
||||
.inline-note { margin-top: 1rem; padding: .9rem 1rem; }
|
||||
.empty-note { color: var(--muted); font-size: .82rem; padding: .5rem 0; }
|
||||
|
||||
.assignment-list { display: flex; flex-direction: column; gap: .35rem; }
|
||||
.assignment-row { display: flex; align-items: center; gap: .55rem; padding: .45rem .5rem; border: 1px solid var(--line-soft); border-radius: 9px; background: rgba(250, 246, 236, .65); }
|
||||
.assignment-person { display: flex; flex-direction: column; flex: 1; min-width: 0; line-height: 1.2; }
|
||||
.assignment-person strong { font-size: .86rem; }
|
||||
.assignment-person small { color: var(--muted); font-size: .7rem; }
|
||||
.assignment-actions { display: flex; align-items: center; gap: .1rem; }
|
||||
.candidate-block { margin-top: .9rem; padding-top: .8rem; border-top: 1px dashed var(--line); }
|
||||
.candidate { display: flex; align-items: center; gap: .5rem; flex-wrap: wrap; padding: .5rem .55rem; border-radius: 9px; border: 1px solid var(--line-soft); background: var(--card); margin-top: .35rem; }
|
||||
.candidate.blocked { opacity: .6; }
|
||||
.candidate-main { display: flex; align-items: center; gap: .5rem; flex: 1; min-width: 190px; }
|
||||
.candidate-main > div { display: flex; flex-direction: column; line-height: 1.2; }
|
||||
.candidate-main strong { font-size: .84rem; }
|
||||
.candidate-main small { color: var(--muted); font-size: .7rem; }
|
||||
.candidate-tags { display: flex; gap: .2rem; flex-wrap: wrap; }
|
||||
.candidate-form { display: flex; align-items: center; gap: .45rem; }
|
||||
|
||||
/* ---------- Team ---------- */
|
||||
.team-layout { display: grid; grid-template-columns: minmax(0, 1.8fr) minmax(280px, .8fr); gap: 1rem; align-items: start; }
|
||||
.team-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: .7rem; }
|
||||
.person-card { display: flex; flex-direction: column; gap: .5rem; padding: .8rem .85rem; border: 1px solid var(--line); border-radius: 12px; background: rgba(255, 253, 247, .8); }
|
||||
.person-card.inactive { opacity: .65; }
|
||||
.person-card-head { display: flex; align-items: center; gap: .55rem; }
|
||||
.person-card-name { flex: 1; min-width: 0; line-height: 1.2; }
|
||||
.person-card-name h4 { font-size: .95rem; }
|
||||
.person-card-name span { color: var(--muted); font-size: .7rem; }
|
||||
.person-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: .2rem; padding: .45rem .1rem; border-top: 1px solid var(--line-soft); border-bottom: 1px solid var(--line-soft); }
|
||||
.person-stats div { display: flex; flex-direction: column; align-items: center; line-height: 1.1; }
|
||||
.person-stats strong { font-family: var(--serif); font-size: 1.05rem; color: var(--green-dark); }
|
||||
.person-stats span { color: var(--muted); font-size: .6rem; text-transform: uppercase; letter-spacing: .04em; }
|
||||
.person-stats.large strong { font-size: 1.4rem; }
|
||||
.person-details { display: flex; flex-direction: column; font-size: .73rem; color: var(--muted); overflow: hidden; }
|
||||
.person-details a { text-overflow: ellipsis; overflow: hidden; white-space: nowrap; }
|
||||
.preference-tags { display: flex; flex-wrap: wrap; gap: .18rem; }
|
||||
.person-foot { display: flex; justify-content: space-between; gap: .5rem; color: var(--muted); font-size: .66rem; }
|
||||
.absence-list { display: flex; flex-direction: column; }
|
||||
.absence-row { display: flex; align-items: center; gap: .7rem; padding: .5rem .1rem; border-bottom: 1px solid var(--line-soft); color: var(--ink); }
|
||||
.absence-row:hover { color: var(--ink); background: rgba(247, 241, 227, .6); }
|
||||
.absence-row:last-child { border-bottom: 0; }
|
||||
.absence-dates { display: flex; flex-direction: column; min-width: 74px; line-height: 1.15; }
|
||||
.absence-dates strong { font-size: .76rem; }
|
||||
.absence-dates small { color: var(--muted); font-size: .65rem; }
|
||||
.absence-person { display: flex; flex-direction: column; line-height: 1.2; min-width: 0; }
|
||||
.absence-person strong { font-size: .79rem; }
|
||||
.absence-person small { color: var(--muted); font-size: .68rem; }
|
||||
|
||||
.compact-list { display: flex; flex-direction: column; margin-top: .5rem; }
|
||||
.compact-row { display: flex; align-items: center; justify-content: space-between; gap: .65rem; padding: .5rem .1rem; border-bottom: 1px solid var(--line-soft); }
|
||||
.compact-row:last-child { border-bottom: 0; }
|
||||
.compact-row > div:first-child { display: flex; flex-direction: column; line-height: 1.25; min-width: 0; }
|
||||
.compact-row strong { font-size: .8rem; }
|
||||
.compact-row small { color: var(--muted); font-size: .69rem; }
|
||||
|
||||
/* ---------- Statistics ---------- */
|
||||
.stats-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1rem; align-items: start; }
|
||||
.stats-grid .span-2 { grid-column: span 2; }
|
||||
.month-chart { display: flex; align-items: flex-end; gap: .45rem; min-height: 190px; padding: .7rem .2rem 0; overflow-x: auto; }
|
||||
.month-bar-wrap { display: flex; flex-direction: column; align-items: center; gap: .25rem; min-width: 46px; flex: 1; }
|
||||
.month-count { font-size: .66rem; color: var(--muted); }
|
||||
.month-bar-track { display: flex; align-items: flex-end; justify-content: center; width: 100%; height: 130px; border-bottom: 1px solid var(--line); }
|
||||
.month-bar { width: 60%; max-width: 26px; border-radius: 5px 5px 0 0; background: linear-gradient(180deg, var(--green), #487d69); min-height: 2px; }
|
||||
.month-label { color: var(--muted); font-size: .64rem; text-align: center; white-space: nowrap; }
|
||||
.fairness-box { display: grid; grid-template-columns: repeat(2, 1fr); gap: .55rem; }
|
||||
.fairness-box div { display: flex; flex-direction: column; padding: .55rem .65rem; border-radius: 9px; background: var(--paper-soft); border: 1px solid var(--line-soft); }
|
||||
.fairness-box span { color: var(--muted); font-size: .66rem; text-transform: uppercase; letter-spacing: .06em; }
|
||||
.fairness-box strong { font-family: var(--serif); font-size: 1.35rem; color: var(--green-dark); }
|
||||
.inline-bar { height: 8px; border-radius: 999px; background: var(--paper-deep); overflow: hidden; width: 100%; min-width: 70px; }
|
||||
.inline-bar span { display: block; height: 100%; border-radius: inherit; background: linear-gradient(90deg, #4c7d69, var(--green)); }
|
||||
.inline-bar.tall { height: 10px; }
|
||||
.bar-cell { min-width: 100px; }
|
||||
.church-stat-list { display: flex; flex-direction: column; gap: .55rem; }
|
||||
.church-stat-row { display: flex; align-items: center; gap: .6rem; }
|
||||
.church-stat-icon .church-glyph { width: 52px; height: 38px; color: var(--green-dark); }
|
||||
.church-stat-main { flex: 1; min-width: 0; }
|
||||
.church-stat-head { display: flex; justify-content: space-between; gap: .5rem; margin-bottom: .2rem; }
|
||||
.church-stat-head strong { font-size: .8rem; }
|
||||
.church-stat-head span { color: var(--muted); font-size: .68rem; }
|
||||
.church-stat-meta { display: flex; flex-direction: column; align-items: flex-end; min-width: 64px; line-height: 1.15; }
|
||||
.church-stat-meta strong { font-family: var(--serif); font-size: 1.05rem; color: var(--green-dark); }
|
||||
.church-stat-meta span { color: var(--muted); font-size: .64rem; }
|
||||
.big-number-block { display: flex; flex-direction: column; align-items: flex-start; padding: .4rem 0; }
|
||||
.big-number-block strong { font-family: var(--serif); font-size: 3rem; line-height: 1; color: var(--green-dark); }
|
||||
.big-number-block span { font-size: .9rem; color: var(--ink-soft); }
|
||||
.big-number-block small { color: var(--muted); font-size: .74rem; margin-top: .2rem; }
|
||||
|
||||
/* ---------- Exchange ---------- */
|
||||
.export-option { display: flex; flex-direction: column; gap: .7rem; padding: .85rem 0; border-bottom: 1px solid var(--line-soft); }
|
||||
.export-option:last-of-type { border-bottom: 0; }
|
||||
.export-option h4 { margin-bottom: .2rem; }
|
||||
.export-option p { color: var(--muted); font-size: .82rem; margin-bottom: .45rem; }
|
||||
.export-option > .btn { align-self: flex-start; }
|
||||
.preview-panel { display: flex; flex-direction: column; gap: .8rem; }
|
||||
.preview-head h4 { margin: .25rem 0 .1rem; }
|
||||
.preview-head p { color: var(--muted); font-size: .78rem; }
|
||||
.preview-counts { display: grid; grid-template-columns: repeat(3, 1fr); gap: .45rem; }
|
||||
.preview-counts div { display: flex; flex-direction: column; padding: .5rem .6rem; border-radius: 8px; background: var(--paper-soft); border: 1px solid var(--line-soft); }
|
||||
.preview-counts strong { font-family: var(--serif); font-size: 1.15rem; color: var(--green-dark); }
|
||||
.preview-counts span { color: var(--muted); font-size: .68rem; }
|
||||
|
||||
/* ---------- Settings ---------- */
|
||||
.settings-grid { display: grid; grid-template-columns: minmax(0, 1.2fr) minmax(280px, .9fr); gap: 1.2rem; }
|
||||
.settings-copy h4 { margin-bottom: .25rem; }
|
||||
.settings-copy p { color: var(--muted); font-size: .84rem; margin-bottom: .6rem; }
|
||||
.settings-fields { display: flex; flex-direction: column; gap: .65rem; }
|
||||
.inline-meta { display: flex; justify-content: space-between; gap: .5rem; padding: .45rem .55rem; border-radius: 8px; background: var(--paper-soft); border: 1px solid var(--line-soft); font-size: .76rem; }
|
||||
.inline-meta span { color: var(--muted); }
|
||||
.source-note { display: flex; align-items: center; gap: .35rem; color: var(--muted); font-size: .72rem; }
|
||||
.source-note .icon { width: 14px; height: 14px; }
|
||||
.weight-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .55rem; }
|
||||
.data-summary { display: grid; grid-template-columns: repeat(5, 1fr); gap: .5rem; margin-bottom: 1rem; }
|
||||
.data-summary div { display: flex; flex-direction: column; align-items: center; padding: .5rem; border-radius: 9px; background: var(--paper-soft); border: 1px solid var(--line-soft); }
|
||||
.data-summary strong { font-family: var(--serif); font-size: 1.25rem; color: var(--green-dark); }
|
||||
.data-summary span { color: var(--muted); font-size: .66rem; text-transform: uppercase; letter-spacing: .05em; }
|
||||
.danger-zone { border-left: 2px solid #e3c5c2; padding-left: .9rem; }
|
||||
.danger-block { display: flex; flex-direction: column; gap: .5rem; padding-bottom: .7rem; border-bottom: 1px dashed var(--line); }
|
||||
.danger-block:last-child { border-bottom: 0; padding-bottom: 0; }
|
||||
.danger-block h4 { color: var(--burgundy); }
|
||||
.danger-block p { color: var(--muted); font-size: .78rem; }
|
||||
.delete-form { display: flex; flex-direction: column; gap: .45rem; }
|
||||
.about-card { display: flex; align-items: center; gap: 1rem; background: linear-gradient(140deg, #fbf6ea, #f5edda); border-color: #ddd0ae; }
|
||||
.about-mark { display: flex; align-items: center; justify-content: center; width: 52px; height: 52px; border-radius: 12px; background: var(--gold-soft); color: var(--gold); flex: 0 0 auto; }
|
||||
.about-mark .icon { width: 26px; height: 26px; }
|
||||
.about-card p { color: var(--muted); font-size: .82rem; margin-top: .2rem; }
|
||||
|
||||
/* ---------- Administration ---------- */
|
||||
.admin-layout { display: grid; grid-template-columns: minmax(0, 1.65fr) minmax(300px, .8fr); gap: 1rem; align-items: start; }
|
||||
.admin-layout.wide-form { grid-template-columns: minmax(0, 1.45fr) minmax(330px, .9fr); }
|
||||
.admin-list { display: flex; flex-direction: column; }
|
||||
.admin-row { display: flex; align-items: flex-start; justify-content: space-between; gap: 1rem; padding: .85rem .1rem; border-bottom: 1px solid var(--line-soft); }
|
||||
.admin-row:last-child { border-bottom: 0; }
|
||||
.admin-row-main { min-width: 0; }
|
||||
.admin-row-title { display: flex; align-items: center; gap: .4rem; flex-wrap: wrap; }
|
||||
.admin-row-title h4 { font-size: 1rem; }
|
||||
.admin-row p { color: var(--muted); font-size: .76rem; margin-top: .18rem; }
|
||||
.admin-row-actions { display: flex; align-items: center; gap: .15rem; flex-wrap: wrap; justify-content: flex-end; }
|
||||
.admin-metrics { display: flex; flex-wrap: wrap; gap: .35rem 1rem; margin-top: .35rem; color: var(--muted); font-size: .7rem; }
|
||||
.admin-metrics strong { color: var(--ink-soft); font-size: .76rem; }
|
||||
.church-admin-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(245px, 1fr)); gap: .7rem; }
|
||||
.church-admin-card { display: flex; flex-direction: column; gap: .5rem; padding: .75rem; border: 1px solid var(--line); border-radius: 11px; background: var(--card); }
|
||||
.church-admin-art { display: flex; justify-content: center; padding: .35rem; border-radius: 8px; background: linear-gradient(160deg, var(--paper-soft), var(--paper-deep)); }
|
||||
.church-admin-art .church-glyph { width: 84px; height: 60px; color: var(--green-dark); }
|
||||
.church-admin-body { display: flex; flex-direction: column; gap: .2rem; }
|
||||
.church-admin-body p { color: var(--muted); font-size: .72rem; }
|
||||
.church-admin-card .admin-row-actions { justify-content: flex-end; }
|
||||
.color-dot { width: 10px; height: 10px; border-radius: 50%; border: 1px solid rgba(0, 0, 0, .12); }
|
||||
|
||||
/* ---------- Auth ---------- */
|
||||
.auth-page { display: flex; align-items: center; justify-content: center; padding: 2rem 1.2rem; }
|
||||
.auth-shell { width: min(100%, 1080px); margin: 0 auto; }
|
||||
.auth-flash { margin: 0 0 1rem; }
|
||||
.auth-card {
|
||||
display: grid; grid-template-columns: minmax(0, 1.08fr) minmax(340px, .92fr);
|
||||
overflow: hidden; border: 1px solid #d8c9a7; border-radius: 22px;
|
||||
background: var(--card); box-shadow: 0 30px 80px rgba(56, 43, 20, .16), 0 2px 0 rgba(255, 255, 255, .6) inset;
|
||||
}
|
||||
.auth-art {
|
||||
display: flex; flex-direction: column; gap: 1.1rem; justify-content: space-between;
|
||||
padding: clamp(1.4rem, 3vw, 2.4rem);
|
||||
background:
|
||||
radial-gradient(500px 300px at 90% 10%, rgba(194, 161, 77, .22), transparent 65%),
|
||||
radial-gradient(400px 300px at 10% 90%, rgba(49, 94, 80, .18), transparent 65%),
|
||||
linear-gradient(150deg, #2e5548 0%, #28493f 48%, #233f37 100%);
|
||||
color: #f7f0df;
|
||||
}
|
||||
.auth-brand { display: flex; align-items: center; gap: .9rem; }
|
||||
.auth-brand h1 { color: #fdf7e8; font-size: clamp(1.7rem, 3vw, 2.3rem); line-height: 1; }
|
||||
.auth-brand p { color: #d7d8c5; font-size: .84rem; margin-top: .3rem; max-width: 30ch; }
|
||||
.auth-art .brand-mark { background: rgba(255, 253, 247, .12); border-color: rgba(255, 255, 255, .2); color: #f0dfa9; }
|
||||
.auth-church { display: flex; justify-content: center; padding: .4rem 0 .1rem; }
|
||||
.auth-church .church-glyph { width: min(100%, 330px); height: auto; opacity: .95; }
|
||||
.auth-quote { position: relative; padding-left: 1.3rem; color: #e7e1cd; }
|
||||
.quote-mark { position: absolute; left: 0; top: -.5rem; font-family: var(--serif); font-size: 2.8rem; color: var(--gold); line-height: 1; }
|
||||
.auth-quote p { font-family: var(--serif); font-size: clamp(1rem, 1.7vw, 1.2rem); line-height: 1.4; font-style: italic; }
|
||||
.quote-source { display: block; margin-top: .35rem; color: #bfc8b6; font-size: .68rem; letter-spacing: .05em; text-transform: uppercase; }
|
||||
.auth-badges { display: flex; gap: .35rem; }
|
||||
.auth-badges .badge { background: rgba(255, 253, 247, .1); border-color: rgba(255, 255, 255, .16); color: #eee5cf; }
|
||||
.auth-form-panel { display: flex; flex-direction: column; justify-content: center; gap: 1rem; padding: clamp(1.4rem, 3vw, 2.5rem); background: linear-gradient(160deg, #fffdf7, #faf5e8); }
|
||||
.auth-form-head h2 { font-size: 2rem; margin: .1rem 0 .35rem; }
|
||||
.auth-form-head p { color: var(--muted); font-size: .85rem; }
|
||||
.auth-form-panel .form-stack { gap: .9rem; }
|
||||
.demo-accounts { padding: .8rem .9rem; border: 1px dashed #d8c79b; border-radius: 11px; background: #fbf4e1; }
|
||||
.demo-accounts-title { display: block; color: #7a5d1c; font-size: .64rem; font-weight: 800; letter-spacing: .1em; text-transform: uppercase; margin-bottom: .4rem; }
|
||||
.demo-account-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: .4rem; }
|
||||
.demo-account-grid div { display: flex; flex-direction: column; gap: .1rem; font-size: .69rem; color: #6d5a2e; }
|
||||
.demo-account-grid strong { font-family: var(--mono); font-size: .72rem; color: #4f411f; }
|
||||
.auth-note { display: flex; align-items: flex-start; gap: .4rem; color: var(--muted); font-size: .7rem; }
|
||||
.auth-note .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--green); margin-top: .35rem; flex: 0 0 auto; }
|
||||
.auth-foot { text-align: center; color: var(--muted-light); font-size: .7rem; margin-top: 1rem; }
|
||||
|
||||
/* ---------- Error / no tenant ---------- */
|
||||
.error-page { display: flex; align-items: center; gap: 1.5rem; padding: 2rem; max-width: 760px; margin: 3rem auto; }
|
||||
.error-code { display: flex; align-items: center; justify-content: center; width: 110px; height: 110px; border-radius: 50%; background: var(--gold-soft); border: 1px solid #e2d199; color: #8c6a23; font-family: var(--serif); font-size: 2.1rem; flex: 0 0 auto; }
|
||||
.error-page h2 { margin-bottom: .35rem; }
|
||||
.error-page p { color: var(--muted); font-size: .9rem; margin-bottom: 1rem; }
|
||||
|
||||
/* ---------- Utilities and responsive ---------- */
|
||||
[data-plan-row].filtered { display: none; }
|
||||
[data-plan-row].filtered + [data-plan-row].filtered { border-top: 0; }
|
||||
.plan-table-empty { padding: 2rem; text-align: center; color: var(--muted); }
|
||||
.text-right { text-align: right; }
|
||||
.text-center { text-align: center; }
|
||||
.nowrap { white-space: nowrap; }
|
||||
|
||||
@media (max-width: 1180px) {
|
||||
.stats-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.stats-grid .span-2 { grid-column: span 2; }
|
||||
.detail-grid { grid-template-columns: minmax(0, 1.35fr) minmax(280px, .8fr); }
|
||||
.auth-card { grid-template-columns: 1fr; }
|
||||
.auth-art { min-height: 360px; }
|
||||
.auth-church { display: none; }
|
||||
}
|
||||
@media (max-width: 980px) {
|
||||
.sidebar { position: fixed; left: 0; top: 0; transform: translateX(-104%); transition: transform .2s ease; box-shadow: 0 0 60px rgba(43, 51, 45, .25); }
|
||||
.sidebar.open { transform: translateX(0); }
|
||||
.nav-toggle { display: inline-flex; }
|
||||
.sidebar-close { display: inline-flex; }
|
||||
body.nav-open::after { content: ""; position: fixed; inset: 0; background: rgba(38, 45, 39, .3); z-index: 9; }
|
||||
.topbar { position: sticky; top: 0; z-index: 8; background: rgba(250, 246, 236, .93); backdrop-filter: blur(8px); }
|
||||
.two-column, .team-layout, .detail-grid, .admin-layout, .admin-layout.wide-form { grid-template-columns: 1fr; }
|
||||
.stat-strip { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.page-intro { flex-direction: column; align-items: flex-start; }
|
||||
.intro-stats { align-self: stretch; justify-content: flex-start; }
|
||||
.intro-stats div { align-items: flex-start; }
|
||||
.settings-grid { grid-template-columns: 1fr; }
|
||||
.data-summary { grid-template-columns: repeat(3, 1fr); }
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.content { padding: 1rem .8rem 1.6rem; }
|
||||
.topbar { padding: .8rem .8rem; }
|
||||
.topbar-title h1 { font-size: 1.3rem; }
|
||||
.account-text { display: none; }
|
||||
.stat-strip, .stat-strip.four { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.stats-grid { grid-template-columns: 1fr; }
|
||||
.stats-grid .span-2 { grid-column: span 1; }
|
||||
.form-row, .form-row.three { grid-template-columns: 1fr; }
|
||||
.month-chart { gap: .25rem; }
|
||||
.month-bar-wrap { min-width: 38px; }
|
||||
.preview-counts { grid-template-columns: repeat(2, 1fr); }
|
||||
.data-summary { grid-template-columns: repeat(2, 1fr); }
|
||||
.detail-church .church-glyph { width: 70px; height: 50px; }
|
||||
.error-page { flex-direction: column; text-align: center; padding: 1.4rem; }
|
||||
.error-code { width: 84px; height: 84px; font-size: 1.6rem; }
|
||||
.auth-form-panel { padding: 1.3rem; }
|
||||
.demo-account-grid { grid-template-columns: 1fr; }
|
||||
.church-overview { grid-template-columns: 1fr; }
|
||||
.topbar-actions .btn span { display: none; }
|
||||
}
|
||||
|
||||
@media print {
|
||||
.sidebar, .topbar, .app-footer, .flash, .toolbar, .range-actions, .filter-chips, .legend-items, .plan-legend, .btn { display: none !important; }
|
||||
.app-shell, .app-main, .content { display: block; padding: 0; }
|
||||
body { background: #fff; }
|
||||
.card, .calendar-card { box-shadow: none; border-color: #bbb; }
|
||||
.calendar-table { min-width: 0; font-size: 9pt; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* { transition: none !important; animation: none !important; }
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"lektorenplan/domain"
|
||||
"lektorenplan/store"
|
||||
)
|
||||
|
||||
type statisticsMonth struct {
|
||||
Key string
|
||||
Label string
|
||||
Count int
|
||||
Width string
|
||||
}
|
||||
|
||||
type statisticsPageData struct {
|
||||
Range domain.DayRange
|
||||
Start string
|
||||
End string
|
||||
Stats domain.RangeStatistics
|
||||
Months []statisticsMonth
|
||||
MaxMonth int
|
||||
MinAssignments int
|
||||
MaxAssignments int
|
||||
Span int
|
||||
Average string
|
||||
CanEdit bool
|
||||
MaxChurch int
|
||||
MonthStart string
|
||||
MonthEnd string
|
||||
QuarterStart string
|
||||
QuarterEnd string
|
||||
YearStart string
|
||||
YearEnd string
|
||||
ChurchYearStart string
|
||||
ChurchYearEnd string
|
||||
PrevStart string
|
||||
PrevEnd string
|
||||
NextStart string
|
||||
NextEnd string
|
||||
RangeStart string
|
||||
RangeEnd string
|
||||
}
|
||||
|
||||
func (s *Server) handleStatistics(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.renderNoTenant(w, r)
|
||||
return
|
||||
}
|
||||
rng := s.rangeFromRequest(r)
|
||||
services, err := s.store.Services(r.Context(), tenant.ID, rng)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Statistik", err.Error())
|
||||
return
|
||||
}
|
||||
assignments, err := s.store.Assignments(r.Context(), tenant.ID, rng)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Statistik", err.Error())
|
||||
return
|
||||
}
|
||||
people, err := s.store.People(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Team", err.Error())
|
||||
return
|
||||
}
|
||||
churches, err := s.store.Churches(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Kirchen", err.Error())
|
||||
return
|
||||
}
|
||||
absences, err := s.store.Absences(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Abwesenheiten", err.Error())
|
||||
return
|
||||
}
|
||||
stats := domain.ComputeStatistics(rng, services, assignments, people, churches, absences)
|
||||
|
||||
months := []statisticsMonth{}
|
||||
cursor := domain.StartOfMonth(rng.Start)
|
||||
maxMonth := 0
|
||||
for !cursor.After(rng.End) {
|
||||
key := domain.MonthKey(cursor)
|
||||
count := stats.MonthlyCounts[key]
|
||||
if count > maxMonth {
|
||||
maxMonth = count
|
||||
}
|
||||
months = append(months, statisticsMonth{
|
||||
Key: key, Label: domain.MonthName(cursor) + " " + strconv.Itoa(domain.Year(cursor)), Count: count,
|
||||
})
|
||||
cursor = domain.AddingMonths(1, cursor)
|
||||
}
|
||||
for i := range months {
|
||||
width := "0%"
|
||||
if maxMonth > 0 && months[i].Count > 0 {
|
||||
width = percentageWidth(float64(months[i].Count) / float64(maxMonth))
|
||||
}
|
||||
months[i].Width = width
|
||||
}
|
||||
|
||||
minAssignments, maxAssignments := 0, 0
|
||||
first := true
|
||||
for _, stat := range stats.PersonStats {
|
||||
if !stat.Person.Active {
|
||||
continue
|
||||
}
|
||||
if first || stat.Total < minAssignments {
|
||||
minAssignments = stat.Total
|
||||
}
|
||||
if first || stat.Total > maxAssignments {
|
||||
maxAssignments = stat.Total
|
||||
}
|
||||
first = false
|
||||
}
|
||||
|
||||
maxChurch := 0
|
||||
for _, church := range stats.ChurchStats {
|
||||
if church.Assignments > maxChurch {
|
||||
maxChurch = church.Assignments
|
||||
}
|
||||
}
|
||||
monthRange := domain.MonthRange(rng.Start)
|
||||
quarterRange := domain.QuarterRange(rng.Start)
|
||||
yearRange := domain.YearRange(domain.Year(rng.Start))
|
||||
churchYear := domain.CurrentChurchYear(rng.Start)
|
||||
prevRange := domain.MonthRange(domain.AddingMonths(-1, rng.Start))
|
||||
nextRange := domain.MonthRange(domain.AddingMonths(1, rng.Start))
|
||||
page := statisticsPageData{
|
||||
Range: rng, Start: domain.Key(rng.Start), End: domain.Key(rng.End),
|
||||
Stats: stats, Months: months, MaxMonth: maxMonth,
|
||||
MinAssignments: minAssignments, MaxAssignments: maxAssignments,
|
||||
Span: maxAssignments - minAssignments,
|
||||
Average: formatDecimal(stats.AverageAssignments()), MaxChurch: maxChurch,
|
||||
MonthStart: domain.Key(monthRange.Start), MonthEnd: domain.Key(monthRange.End),
|
||||
QuarterStart: domain.Key(quarterRange.Start), QuarterEnd: domain.Key(quarterRange.End),
|
||||
YearStart: domain.Key(yearRange.Start), YearEnd: domain.Key(yearRange.End),
|
||||
ChurchYearStart: domain.Key(churchYear.Start), ChurchYearEnd: domain.Key(churchYear.End),
|
||||
PrevStart: domain.Key(prevRange.Start), PrevEnd: domain.Key(prevRange.End),
|
||||
NextStart: domain.Key(nextRange.Start), NextEnd: domain.Key(nextRange.End),
|
||||
RangeStart: domain.Key(rng.Start), RangeEnd: domain.Key(rng.End),
|
||||
CanEdit: s.store.CanEditTenant(r.Context(), user, tenant.ID),
|
||||
}
|
||||
data := s.baseView(w, r, "Statistik", "statistics")
|
||||
data.Data = page
|
||||
s.renderPage(w, r, "statistics", data)
|
||||
}
|
||||
|
||||
func formatDecimal(value float64) string {
|
||||
return fmt.Sprintf("%.1f", value)
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"lektorenplan/domain"
|
||||
"lektorenplan/store"
|
||||
)
|
||||
|
||||
type weekdayOption struct {
|
||||
Number int
|
||||
Name string
|
||||
Short string
|
||||
}
|
||||
|
||||
var weekdays = []weekdayOption{
|
||||
{1, "Sonntag", "So"},
|
||||
{2, "Montag", "Mo"},
|
||||
{3, "Dienstag", "Di"},
|
||||
{4, "Mittwoch", "Mi"},
|
||||
{5, "Donnerstag", "Do"},
|
||||
{6, "Freitag", "Fr"},
|
||||
{7, "Samstag", "Sa"},
|
||||
}
|
||||
|
||||
type teamPageData struct {
|
||||
People []domain.Person
|
||||
PeopleByID map[string]domain.Person
|
||||
Absences []domain.Absence
|
||||
AbsencesByPerson map[string][]domain.Absence
|
||||
Churches []domain.Church
|
||||
ChurchByID map[string]domain.Church
|
||||
Stats map[string]domain.PersonStat
|
||||
CanEdit bool
|
||||
ActiveCount int
|
||||
LectorCount int
|
||||
HelperCount int
|
||||
Year int
|
||||
}
|
||||
|
||||
type personAssignmentRow struct {
|
||||
Assignment domain.Assignment
|
||||
Service domain.ServiceOccurrence
|
||||
Church domain.Church
|
||||
}
|
||||
|
||||
type personPageData struct {
|
||||
Person domain.Person
|
||||
IsNew bool
|
||||
Absences []domain.Absence
|
||||
Churches []domain.Church
|
||||
Assignments []personAssignmentRow
|
||||
Stats domain.PersonStat
|
||||
Weekdays []weekdayOption
|
||||
CanEdit bool
|
||||
UpcomingCount int
|
||||
TotalCount int
|
||||
Year int
|
||||
PreferredChurches map[string]domain.Church
|
||||
}
|
||||
|
||||
func (s *Server) handleTeam(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.renderNoTenant(w, r)
|
||||
return
|
||||
}
|
||||
people, err := s.store.People(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Team", err.Error())
|
||||
return
|
||||
}
|
||||
absences, err := s.store.Absences(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Abwesenheiten", err.Error())
|
||||
return
|
||||
}
|
||||
churches, err := s.store.Churches(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Kirchen", err.Error())
|
||||
return
|
||||
}
|
||||
absencesByPerson := map[string][]domain.Absence{}
|
||||
for _, absence := range absences {
|
||||
absencesByPerson[absence.PersonID] = append(absencesByPerson[absence.PersonID], absence)
|
||||
}
|
||||
year := domain.Year(domain.Today())
|
||||
rng := domain.YearRange(year)
|
||||
services, err := s.store.Services(r.Context(), tenant.ID, rng)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Team", err.Error())
|
||||
return
|
||||
}
|
||||
assignments, err := s.store.Assignments(r.Context(), tenant.ID, rng)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Team", err.Error())
|
||||
return
|
||||
}
|
||||
stats := domain.ComputeStatistics(rng, services, assignments, people, churches, absences)
|
||||
statByPerson := map[string]domain.PersonStat{}
|
||||
for _, stat := range stats.PersonStats {
|
||||
statByPerson[stat.Person.ID] = stat
|
||||
}
|
||||
peopleByID := map[string]domain.Person{}
|
||||
for _, person := range people {
|
||||
peopleByID[person.ID] = person
|
||||
}
|
||||
churchByID := map[string]domain.Church{}
|
||||
for _, church := range churches {
|
||||
churchByID[church.ID] = church
|
||||
}
|
||||
page := teamPageData{
|
||||
People: people, PeopleByID: peopleByID, Absences: absences, AbsencesByPerson: absencesByPerson,
|
||||
Churches: churches, ChurchByID: churchByID, Stats: statByPerson,
|
||||
CanEdit: s.store.CanEditTenant(r.Context(), user, tenant.ID), Year: year,
|
||||
}
|
||||
for _, person := range people {
|
||||
if person.Active {
|
||||
page.ActiveCount++
|
||||
}
|
||||
if person.CanFill(domain.RoleLector) {
|
||||
page.LectorCount++
|
||||
}
|
||||
if person.CanFill(domain.RoleHelper) {
|
||||
page.HelperCount++
|
||||
}
|
||||
}
|
||||
data := s.baseView(w, r, "Team", "team")
|
||||
data.Data = page
|
||||
s.renderPage(w, r, "team", data)
|
||||
}
|
||||
|
||||
func blankPerson() domain.Person {
|
||||
return domain.Person{
|
||||
ID: domain.NewID(), Roles: []domain.Role{domain.RoleLector},
|
||||
MaxPerMonth: 6, Active: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handlePerson(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if tenant == nil {
|
||||
s.renderNoTenant(w, r)
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
isNew := id == "" || id == "new"
|
||||
var person domain.Person
|
||||
if isNew {
|
||||
person = blankPerson()
|
||||
} else {
|
||||
loaded, err := s.store.Person(r.Context(), tenant.ID, id)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusNotFound, "Person", "Diese Person wurde nicht gefunden.")
|
||||
return
|
||||
}
|
||||
person = *loaded
|
||||
}
|
||||
absences, err := s.store.AbsencesForPerson(r.Context(), tenant.ID, person.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Abwesenheiten", err.Error())
|
||||
return
|
||||
}
|
||||
churches, err := s.store.Churches(r.Context(), tenant.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Kirchen", err.Error())
|
||||
return
|
||||
}
|
||||
churchByID := map[string]domain.Church{}
|
||||
for _, church := range churches {
|
||||
churchByID[church.ID] = church
|
||||
}
|
||||
assignments, err := s.store.AssignmentsForPerson(r.Context(), tenant.ID, person.ID)
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "Einteilungen", err.Error())
|
||||
return
|
||||
}
|
||||
rows := make([]personAssignmentRow, 0, len(assignments))
|
||||
today := domain.Today()
|
||||
upcoming := 0
|
||||
var serviceIDs []string
|
||||
serviceByID := map[string]domain.ServiceOccurrence{}
|
||||
for _, assignment := range assignments {
|
||||
serviceIDs = append(serviceIDs, assignment.ServiceID)
|
||||
}
|
||||
for _, serviceID := range serviceIDs {
|
||||
if _, ok := serviceByID[serviceID]; ok {
|
||||
continue
|
||||
}
|
||||
service, err := s.store.Service(r.Context(), tenant.ID, serviceID)
|
||||
if err == nil {
|
||||
serviceByID[serviceID] = *service
|
||||
}
|
||||
}
|
||||
for _, assignment := range assignments {
|
||||
service, ok := serviceByID[assignment.ServiceID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if !service.Date.Before(today) {
|
||||
upcoming++
|
||||
}
|
||||
rows = append(rows, personAssignmentRow{
|
||||
Assignment: assignment, Service: service, Church: churchByID[service.ChurchID],
|
||||
})
|
||||
}
|
||||
sort.SliceStable(rows, func(i, j int) bool {
|
||||
return rows[i].Service.Date.After(rows[j].Service.Date)
|
||||
})
|
||||
page := personPageData{
|
||||
Person: person, IsNew: isNew, Absences: absences, Churches: churches,
|
||||
Assignments: rows, Weekdays: weekdays,
|
||||
CanEdit: s.store.CanEditTenant(r.Context(), user, tenant.ID),
|
||||
UpcomingCount: upcoming, TotalCount: len(rows), Year: domain.Year(today),
|
||||
PreferredChurches: map[string]domain.Church{},
|
||||
}
|
||||
for _, churchID := range person.PreferredChurchIDs {
|
||||
if church, ok := churchByID[churchID]; ok {
|
||||
page.PreferredChurches[churchID] = church
|
||||
}
|
||||
}
|
||||
if !isNew {
|
||||
yearRng := domain.YearRange(domain.Year(today))
|
||||
services, _ := s.store.Services(r.Context(), tenant.ID, yearRng)
|
||||
rangeAssignments, _ := s.store.Assignments(r.Context(), tenant.ID, yearRng)
|
||||
allPeople, _ := s.store.People(r.Context(), tenant.ID)
|
||||
allAbsences, _ := s.store.Absences(r.Context(), tenant.ID)
|
||||
stats := domain.ComputeStatistics(yearRng, services, rangeAssignments, allPeople, churches, allAbsences)
|
||||
for _, stat := range stats.PersonStats {
|
||||
if stat.Person.ID == person.ID {
|
||||
page.Stats = stat
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
data := s.baseView(w, r, person.FullName(), "team")
|
||||
if isNew {
|
||||
data.Title = "Neue Person"
|
||||
}
|
||||
data.Data = page
|
||||
s.renderPage(w, r, "person", data)
|
||||
}
|
||||
|
||||
func (s *Server) handlePersonSave(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
id := r.PathValue("id")
|
||||
if id == "" || id == "new" {
|
||||
id = domain.NewID()
|
||||
}
|
||||
var roles []domain.Role
|
||||
for _, role := range domain.AllRoles {
|
||||
if r.FormValue("role_"+string(role)) == "1" || r.FormValue("role_"+string(role)) == "on" {
|
||||
roles = append(roles, role)
|
||||
}
|
||||
}
|
||||
if len(roles) == 0 {
|
||||
s.setFlash(w, "Bitte mindestens eine Rolle auswählen.", "error")
|
||||
s.redirectBack(w, r, "/team/person/"+id)
|
||||
return
|
||||
}
|
||||
person := domain.Person{
|
||||
ID: id, FirstName: strings.TrimSpace(r.FormValue("first_name")),
|
||||
LastName: strings.TrimSpace(r.FormValue("last_name")), Roles: roles,
|
||||
Email: strings.TrimSpace(r.FormValue("email")), Phone: strings.TrimSpace(r.FormValue("phone")),
|
||||
PreferredChurchIDs: r.Form["preferred_churches"],
|
||||
PreferredServiceTitles: splitList(r.FormValue("preferred_titles")),
|
||||
MaxPerMonth: parseInt(r.FormValue("max_per_month"), 6),
|
||||
Active: r.FormValue("active") == "1" || r.FormValue("active") == "on",
|
||||
Notes: strings.TrimSpace(r.FormValue("notes")),
|
||||
}
|
||||
for _, raw := range r.Form["preferred_weekdays"] {
|
||||
if value := parseInt(raw, 0); value >= 1 && value <= 7 {
|
||||
person.PreferredWeekdays = append(person.PreferredWeekdays, value)
|
||||
}
|
||||
}
|
||||
if err := s.store.UpsertPerson(r.Context(), tenant.ID, person); err != nil {
|
||||
s.setFlash(w, "Die Person konnte nicht gespeichert werden: "+err.Error(), "error")
|
||||
s.redirectBack(w, r, "/team/person/"+id)
|
||||
return
|
||||
}
|
||||
s.setFlash(w, "Person gespeichert.", "success")
|
||||
s.redirect(w, r, "/team/person/"+id)
|
||||
}
|
||||
|
||||
func (s *Server) handlePersonDelete(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
id := r.PathValue("id")
|
||||
if err := s.store.DeletePerson(r.Context(), tenant.ID, id); err != nil {
|
||||
s.setFlash(w, "Die Person konnte nicht gelöscht werden: "+err.Error(), "error")
|
||||
s.redirectBack(w, r, "/team")
|
||||
return
|
||||
}
|
||||
s.setFlash(w, "Person und zugehörige Einteilungen gelöscht.", "success")
|
||||
s.redirect(w, r, "/team")
|
||||
}
|
||||
|
||||
func (s *Server) handleAbsenceSave(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
personID := r.PathValue("id")
|
||||
start, startOK := domain.DateFromKey(strings.TrimSpace(r.FormValue("start")))
|
||||
end, endOK := domain.DateFromKey(strings.TrimSpace(r.FormValue("end")))
|
||||
if !startOK {
|
||||
start = domain.Today()
|
||||
}
|
||||
if !endOK {
|
||||
end = start
|
||||
}
|
||||
if end.Before(start) {
|
||||
start, end = end, start
|
||||
}
|
||||
absence := domain.Absence{
|
||||
ID: strings.TrimSpace(r.FormValue("id")), PersonID: personID,
|
||||
Start: start, End: end, Reason: strings.TrimSpace(r.FormValue("reason")),
|
||||
}
|
||||
if err := s.store.UpsertAbsence(r.Context(), tenant.ID, absence); err != nil {
|
||||
s.setFlash(w, "Die Abwesenheit konnte nicht gespeichert werden: "+err.Error(), "error")
|
||||
} else {
|
||||
s.setFlash(w, "Abwesenheit gespeichert.", "success")
|
||||
}
|
||||
s.redirectBack(w, r, "/team/person/"+personID)
|
||||
}
|
||||
|
||||
func (s *Server) handleAbsenceDelete(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
|
||||
if err := s.store.DeleteAbsence(r.Context(), tenant.ID, strings.TrimSpace(r.FormValue("id"))); err != nil {
|
||||
s.setFlash(w, "Die Abwesenheit konnte nicht gelöscht werden.", "error")
|
||||
} else {
|
||||
s.setFlash(w, "Abwesenheit gelöscht.", "success")
|
||||
}
|
||||
s.redirectBack(w, r, "/team/person/"+r.PathValue("id"))
|
||||
}
|
||||
|
||||
func splitList(value string) []string {
|
||||
var out []string
|
||||
for _, part := range strings.Split(value, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part != "" {
|
||||
out = append(out, part)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
{{define "content"}}
|
||||
{{$edit := .Data.Edit}}
|
||||
<div class="page-stack">
|
||||
<section class="page-intro">
|
||||
<div>
|
||||
<span class="eyebrow">Administration · {{if .Data.Tenant}}{{.Data.Tenant.Name}}{{end}}</span>
|
||||
<h2>Kirchen und Gottesdienstorte</h2>
|
||||
<p>Kirchen prägen die Spalten des Plans, die Symbolzeichnung und die Farbgebung. Löscht man eine Kirche, werden auch ihre Vorlagen, Gottesdienste und Einteilungen entfernt.</p>
|
||||
</div>
|
||||
<div class="range-actions">
|
||||
<a class="btn btn-ghost btn-small" href="/admin/tenants">{{icon "church"}} Mandanten</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="admin-layout wide-form">
|
||||
<section class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Bestand</span><h3>Kirchen</h3></div><span class="count-pill">{{len .Data.Churches}}</span></div>
|
||||
<div class="church-admin-grid">
|
||||
{{range .Data.Churches}}
|
||||
<article class="church-admin-card">
|
||||
<div class="church-admin-art">{{churchGlyph .Symbol .ColorHex}}</div>
|
||||
<div class="church-admin-body">
|
||||
<div class="admin-row-title"><h4>{{.Name}}</h4><span class="color-dot" style="background:{{.ColorHex}}"></span></div>
|
||||
<p>{{if .ShortName}}{{.ShortName}}{{else}}{{.Name}}{{end}}{{if .Address}} · {{.Address}}{{end}}</p>
|
||||
<div class="badge-row">
|
||||
<span class="badge badge-neutral">{{.Symbol.Caption}}</span>
|
||||
<span class="badge badge-neutral">Sortierung {{.SortIndex}}</span>
|
||||
</div>
|
||||
{{if .Notes}}<p class="muted">{{.Notes}}</p>{{end}}
|
||||
</div>
|
||||
<div class="admin-row-actions">
|
||||
<a class="icon-button" href="/admin/churches?edit={{.ID}}" title="Kirche bearbeiten">{{icon "settings"}}</a>
|
||||
<form method="post" action="/admin/churches/delete" data-confirm="Kirche „{{.Name}}“ mit allen Vorlagen und Gottesdiensten löschen?">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
<input type="hidden" name="id" value="{{.ID}}">
|
||||
<button class="icon-button danger" type="submit" title="Kirche löschen">{{icon "trash"}}</button>
|
||||
</form>
|
||||
</div>
|
||||
</article>
|
||||
{{else}}
|
||||
<p class="empty-note">Noch keine Kirchen in diesem Mandanten.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<aside class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">{{if $edit}}Bearbeiten{{else}}Neu{{end}}</span><h3>{{if $edit}}Kirche bearbeiten{{else}}Kirche anlegen{{end}}</h3></div></div>
|
||||
<form method="post" action="/admin/churches/save" class="form-stack">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<input type="hidden" name="id" value="{{if $edit}}{{$edit.ID}}{{end}}">
|
||||
<label class="field"><span class="field-label">Name</span><input type="text" name="name" value="{{if $edit}}{{$edit.Name}}{{end}}" placeholder="z. B. St. Andreas" required></label>
|
||||
<label class="field"><span class="field-label">Kürzel</span><input type="text" name="short_name" value="{{if $edit}}{{$edit.ShortName}}{{end}}" placeholder="Andreas"></label>
|
||||
<label class="field"><span class="field-label">Kirchensymbol</span>
|
||||
<select name="symbol">
|
||||
{{range .Data.Symbols}}<option value="{{printf "%s" .}}" {{if and $edit (eq (printf "%s" .) (printf "%s" $edit.Symbol))}}selected{{end}}>{{.Caption}}</option>{{end}}
|
||||
</select>
|
||||
</label>
|
||||
<div class="form-row">
|
||||
<label class="field"><span class="field-label">Farbe</span><input type="color" name="color_hex" value="{{if $edit}}{{if $edit.ColorHex}}{{$edit.ColorHex}}{{else}}#4E6E5D{{end}}{{else}}#4E6E5D{{end}}"></label>
|
||||
<label class="field"><span class="field-label">Sortierung</span><input type="number" name="sort_index" min="0" max="99" value="{{if $edit}}{{$edit.SortIndex}}{{else}}0{{end}}"></label>
|
||||
</div>
|
||||
<label class="field"><span class="field-label">Adresse</span><input type="text" name="address" value="{{if $edit}}{{$edit.Address}}{{end}}" placeholder="Straße, PLZ Ort"></label>
|
||||
<label class="field"><span class="field-label">Notizen</span><textarea name="notes" rows="3">{{if $edit}}{{$edit.Notes}}{{end}}</textarea></label>
|
||||
<button class="btn btn-primary" type="submit">{{if $edit}}Kirche speichern{{else}}Kirche anlegen{{end}}</button>
|
||||
{{if $edit}}<a class="text-link" href="/admin/churches">Neue Kirche anlegen</a>{{end}}
|
||||
</form>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,62 @@
|
||||
{{define "content"}}
|
||||
<div class="page-stack">
|
||||
<section class="page-intro">
|
||||
<div>
|
||||
<span class="eyebrow">Administration</span>
|
||||
<h2>Mandanten verwalten</h2>
|
||||
<p>Jeder Mandant besitzt eigene Kirchen, Personen, Gottesdienste und Planungseinstellungen. Konten werden mandantenübergreifend angelegt und anschließend freigegeben.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="admin-layout">
|
||||
<section class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Bestand</span><h3>Mandanten</h3></div><span class="count-pill">{{len .Data.Tenants}}</span></div>
|
||||
<div class="admin-list">
|
||||
{{range .Data.Tenants}}
|
||||
<article class="admin-row">
|
||||
<div class="admin-row-main">
|
||||
<div class="admin-row-title">
|
||||
<h4>{{.Tenant.Name}}</h4>
|
||||
<span class="badge badge-neutral">{{.Tenant.Slug}}</span>
|
||||
{{if and $.Tenant (eq $.Tenant.ID .Tenant.ID)}}<span class="badge badge-green">aktiv</span>{{end}}
|
||||
</div>
|
||||
{{if .Tenant.Notes}}<p>{{.Tenant.Notes}}</p>{{end}}
|
||||
<div class="admin-metrics">
|
||||
<span><strong>{{index .Counts "churches"}}</strong> Kirchen</span>
|
||||
<span><strong>{{index .Counts "people"}}</strong> Personen</span>
|
||||
<span><strong>{{index .Counts "templates"}}</strong> Vorlagen</span>
|
||||
<span><strong>{{index .Counts "services"}}</strong> Gottesdienste</span>
|
||||
<span><strong>{{.UserCount}}</strong> Konten</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-row-actions">
|
||||
<a class="btn btn-ghost btn-tiny" href="/admin/churches?tid={{.Tenant.ID}}">{{icon "church"}} Kirchen</a>
|
||||
<a class="icon-button" href="/admin/tenants?edit={{.Tenant.ID}}" title="Mandant bearbeiten">{{icon "settings"}}</a>
|
||||
<form method="post" action="/admin/tenants/delete" data-confirm="Mandant „{{.Tenant.Name}}“ mit allen Daten löschen?">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
<input type="hidden" name="id" value="{{.Tenant.ID}}">
|
||||
<button class="icon-button danger" type="submit" title="Mandant löschen" {{if and $.Tenant (eq $.Tenant.ID .Tenant.ID)}}disabled{{end}}>{{icon "trash"}}</button>
|
||||
</form>
|
||||
</div>
|
||||
</article>
|
||||
{{else}}
|
||||
<p class="empty-note">Noch keine Mandanten angelegt.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<aside class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">{{if .Data.Edit}}Bearbeiten{{else}}Neu{{end}}</span><h3>{{if .Data.Edit}}Mandant bearbeiten{{else}}Mandant anlegen{{end}}</h3></div></div>
|
||||
<form method="post" action="/admin/tenants/save" class="form-stack">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<input type="hidden" name="id" value="{{if .Data.Edit}}{{.Data.Edit.ID}}{{end}}">
|
||||
<label class="field"><span class="field-label">Name</span><input type="text" name="name" value="{{if .Data.Edit}}{{.Data.Edit.Name}}{{end}}" placeholder="z. B. Pfarreiengemeinschaft Rheinaue" required></label>
|
||||
<label class="field"><span class="field-label">Kennung <small>optional, wird automatisch erzeugt</small></span><input type="text" name="slug" value="{{if .Data.Edit}}{{.Data.Edit.Slug}}{{end}}" placeholder="rheinaue"></label>
|
||||
<label class="field"><span class="field-label">Notizen</span><textarea name="notes" rows="4">{{if .Data.Edit}}{{.Data.Edit.Notes}}{{end}}</textarea></label>
|
||||
<button class="btn btn-primary" type="submit">{{if .Data.Edit}}Speichern{{else}}Mandant anlegen{{end}}</button>
|
||||
{{if .Data.Edit}}<a class="text-link" href="/admin/tenants">Neuen Mandanten anlegen</a>{{end}}
|
||||
</form>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,87 @@
|
||||
{{define "content"}}
|
||||
{{$edit := .Data.Edit}}
|
||||
{{$editRole := ""}}{{if $edit}}{{$editRole = printf "%s" $edit.Role}}{{end}}
|
||||
<div class="page-stack">
|
||||
<section class="page-intro">
|
||||
<div>
|
||||
<span class="eyebrow">Administration</span>
|
||||
<h2>Konten und Rechte</h2>
|
||||
<p>Administratoren verwalten Mandanten und Konten. Redakteure dürfen in freigegebenen Mandanten planen, Leser sehen die Daten nur an. Die Mitgliedschaft bestimmt den Zugriff auf einzelne Mandanten.</p>
|
||||
</div>
|
||||
<div class="intro-stats">
|
||||
<div><strong>{{len .Data.Users}}</strong><span>Konten</span></div>
|
||||
<div><strong>{{len .Data.Tenants}}</strong><span>Mandanten</span></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="admin-layout wide-form">
|
||||
<section class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Bestand</span><h3>Alle Konten</h3></div></div>
|
||||
<div class="table-scroll">
|
||||
<table class="data-table">
|
||||
<thead><tr><th>Konto</th><th>Rolle</th><th>Mandanten</th><th>Status</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Data.Users}}
|
||||
<tr>
|
||||
<td>
|
||||
<span class="person-inline">
|
||||
<span class="avatar tiny">{{initials .DisplayName ""}}</span>
|
||||
<span><strong>{{.DisplayName}}</strong><small>{{.Username}}{{if eq .ID $.Data.SelfID}} · Ihr Konto{{end}}</small></span>
|
||||
</span>
|
||||
</td>
|
||||
<td><span class="badge {{if eq (printf "%s" .Role) "admin"}}badge-burgundy{{else if eq (printf "%s" .Role) "editor"}}badge-green{{else}}badge-neutral{{end}}">{{userRole .Role}}</span></td>
|
||||
<td class="tenant-tags">
|
||||
{{if eq (printf "%s" .Role) "admin"}}<span class="badge badge-gold">alle Mandanten</span>{{else}}
|
||||
{{range .TenantIDs}}{{$tenant := index $.Data.TenantsByID .}}{{if $tenant}}<span class="badge badge-neutral">{{$tenant.Name}}</span>{{end}}{{else}}<span class="muted">keine Freigabe</span>{{end}}
|
||||
{{end}}
|
||||
</td>
|
||||
<td>{{if .Active}}<span class="badge badge-green">aktiv</span>{{else}}<span class="badge badge-neutral">deaktiviert</span>{{end}}</td>
|
||||
<td>
|
||||
<div class="row-actions">
|
||||
<a class="icon-button" href="/admin/users?edit={{.ID}}" title="Konto bearbeiten">{{icon "settings"}}</a>
|
||||
<form method="post" action="/admin/users/delete" data-confirm="Konto „{{.Username}}“ wirklich löschen?">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
<input type="hidden" name="id" value="{{.ID}}">
|
||||
<button class="icon-button danger" type="submit" title="Konto löschen" {{if eq .ID $.Data.SelfID}}disabled{{end}}>{{icon "trash"}}</button>
|
||||
</form>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<aside class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">{{if $edit}}Bearbeiten{{else}}Neu{{end}}</span><h3>{{if $edit}}Konto bearbeiten{{else}}Konto anlegen{{end}}</h3></div></div>
|
||||
<form method="post" action="/admin/users/save" class="form-stack">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<input type="hidden" name="id" value="{{if $edit}}{{$edit.ID}}{{end}}">
|
||||
<label class="field"><span class="field-label">Benutzername</span><input type="text" name="username" value="{{if $edit}}{{$edit.Username}}{{end}}" required autocomplete="off"></label>
|
||||
<label class="field"><span class="field-label">Anzeigename</span><input type="text" name="display_name" value="{{if $edit}}{{$edit.DisplayName}}{{end}}" required></label>
|
||||
<label class="field"><span class="field-label">Passwort {{if $edit}}<small>leer lassen = unverändert</small>{{end}}</span><input type="password" name="password" {{if not $edit}}required{{end}} autocomplete="new-password" placeholder="mindestens 6 Zeichen"></label>
|
||||
<label class="field"><span class="field-label">Rolle</span>
|
||||
<select name="role">
|
||||
{{range .Data.Roles}}<option value="{{printf "%s" .}}" {{if eq (printf "%s" .) $editRole}}selected{{end}}>{{userRole .}}</option>{{end}}
|
||||
</select>
|
||||
</label>
|
||||
<div class="field-group">
|
||||
<span class="field-label">Mandantenfreigaben</span>
|
||||
<p class="field-hint">Administratoren sehen automatisch alle Mandanten.</p>
|
||||
<div class="checkbox-list">
|
||||
{{range .Data.Tenants}}
|
||||
<label class="check"><input type="checkbox" name="tenant_ids" value="{{.ID}}" {{if $edit}}{{if containsString $edit.TenantIDs .ID}}checked{{end}}{{end}}><span>{{.Name}} <small>{{.Slug}}</small></span></label>
|
||||
{{else}}
|
||||
<span class="muted">Noch keine Mandanten vorhanden.</span>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
<label class="check"><input type="checkbox" name="active" value="1" {{if $edit}}{{if $edit.Active}}checked{{end}}{{else}}checked{{end}}><span>Konto ist aktiv</span></label>
|
||||
<button class="btn btn-primary" type="submit">{{if $edit}}Konto speichern{{else}}Konto anlegen{{end}}</button>
|
||||
{{if $edit}}<a class="text-link" href="/admin/users">Neues Konto anlegen</a>{{end}}
|
||||
</form>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,14 @@
|
||||
{{define "content"}}
|
||||
<div class="error-page card">
|
||||
<div class="error-code">{{.Data.Status}}</div>
|
||||
<div>
|
||||
<span class="eyebrow">Hinweis</span>
|
||||
<h2>{{.Data.Title}}</h2>
|
||||
<p>{{.Data.Message}}</p>
|
||||
<div class="form-actions">
|
||||
<a class="btn btn-primary" href="/plan">Zum Gottesdienstplan</a>
|
||||
<a class="btn btn-ghost" href="/">Startseite</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,96 @@
|
||||
{{define "content"}}
|
||||
<div class="page-stack">
|
||||
<section class="page-intro">
|
||||
<div>
|
||||
<span class="eyebrow">Daten austauschen</span>
|
||||
<h2>Planungsabschnitte und Stammdaten übergeben</h2>
|
||||
<p>Exportieren Sie Ressourcen oder einen kompletten Planungsabschnitt als lesbares JSON. Beim Import werden die Inhalte zunächst geprüft und erst nach Ihrer Bestätigung zusammengeführt.</p>
|
||||
</div>
|
||||
<div class="intro-stats">
|
||||
<div><strong>{{.Data.Resource.Churches}}</strong><span>Kirchen</span></div>
|
||||
<div><strong>{{.Data.Resource.People}}</strong><span>Personen</span></div>
|
||||
<div><strong>{{.Data.Resource.Templates}}</strong><span>Vorlagen</span></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="two-column">
|
||||
<section class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Herunterladen</span><h3>Export</h3></div></div>
|
||||
<div class="export-option">
|
||||
<div>
|
||||
<h4>Ressourcen</h4>
|
||||
<p>Kirchen, Personen, Abwesenheiten, wiederkehrende Gottesdienste und Ausnahmen. Ideal zur Weitergabe der Stammdaten an eine andere Installation.</p>
|
||||
<div class="badge-row">
|
||||
<span class="badge badge-neutral">{{plural .Data.Resource.Churches "Kirche" "Kirchen"}}</span>
|
||||
<span class="badge badge-neutral">{{plural .Data.Resource.People "Person" "Personen"}}</span>
|
||||
<span class="badge badge-neutral">{{plural .Data.Resource.Templates "Vorlage" "Vorlagen"}}</span>
|
||||
</div>
|
||||
</div>
|
||||
<a class="btn btn-secondary btn-small" href="/exchange/export?scope=resources">{{icon "exchange"}} JSON laden</a>
|
||||
</div>
|
||||
<div class="export-option">
|
||||
<div>
|
||||
<h4>Planungsabschnitt</h4>
|
||||
<p>Zusätzlich zu den Ressourcen werden Gottesdienste, Einteilungen und liturgische Tage des gewählten Zeitraums exportiert.</p>
|
||||
<form class="range-form inline-range" method="get" action="/exchange/export">
|
||||
<input type="hidden" name="scope" value="plan">
|
||||
<label class="field field-inline"><span>Von</span><input type="date" name="start" value="{{.Data.Start}}"></label>
|
||||
<label class="field field-inline"><span>Bis</span><input type="date" name="end" value="{{.Data.End}}"></label>
|
||||
<button class="btn btn-secondary btn-small" type="submit">{{icon "exchange"}} Plan laden</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="side-note inline-note">
|
||||
<span class="eyebrow">Hinweis</span>
|
||||
<p>Exportdateien enthalten personenbezogene Daten. Bitte nur über sichere Wege weitergeben. Die liturgischen Daten stammen von www.eucharistiefeier.de.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Hochladen</span><h3>Import</h3></div></div>
|
||||
{{with .Data.Preview}}
|
||||
<div class="preview-panel">
|
||||
<div class="preview-head">
|
||||
<span class="badge badge-green">Vorschau</span>
|
||||
<h4>{{.Scope.Title}} aus {{$.Data.FileName}}</h4>
|
||||
<p>{{if .Range.Start}}{{.Range.Start}} bis {{.Range.End}}{{else}}Ressourcen ohne Zeitraum{{end}}</p>
|
||||
</div>
|
||||
<div class="preview-counts">
|
||||
<div><strong>{{.Churches}}</strong><span>Kirchen</span></div>
|
||||
<div><strong>{{.People}}</strong><span>Personen</span></div>
|
||||
<div><strong>{{.Templates}}</strong><span>Vorlagen</span></div>
|
||||
<div><strong>{{.Services}}</strong><span>Gottesdienste</span></div>
|
||||
<div><strong>{{.Assignments}}</strong><span>Einteilungen</span></div>
|
||||
<div><strong>{{.LiturgicalDays}}</strong><span>Kalendertage</span></div>
|
||||
</div>
|
||||
<form method="post" action="/exchange/import" class="form-stack">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
<input type="hidden" name="confirm" value="1">
|
||||
<input type="hidden" name="payload" value="{{$.Data.PreviewToken}}">
|
||||
<label class="check"><input type="checkbox" name="replace" value="1" {{if $.Data.Replace}}checked{{end}}><span>Vorhandene Planungsdaten dieses Mandanten vor dem Import löschen</span></label>
|
||||
<div class="form-actions">
|
||||
<button class="btn btn-primary" type="submit">{{icon "check"}} Import bestätigen</button>
|
||||
<a class="btn btn-ghost" href="/exchange">Abbrechen</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
{{else}}
|
||||
<form method="post" action="/exchange/import" enctype="multipart/form-data" class="form-stack">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<label class="file-drop" data-file-drop>
|
||||
{{icon "exchange"}}
|
||||
<span><strong>JSON-Datei auswählen</strong><small>oder hier ablegen · maximal 32 MB</small></span>
|
||||
<input type="file" name="file" accept="application/json,.json" required data-file-input>
|
||||
</label>
|
||||
<label class="check"><input type="checkbox" name="replace" value="1"><span>Vorhandene Planungsdaten dieses Mandanten vor dem Import löschen</span></label>
|
||||
<button class="btn btn-secondary" type="submit">Datei prüfen</button>
|
||||
</form>
|
||||
<div class="side-note inline-note">
|
||||
<span class="eyebrow">Ablauf</span>
|
||||
<p>Nach dem Hochladen sehen Sie eine Vorschau mit allen enthaltenen Datensätzen. Erst mit „Import bestätigen“ werden Daten geschrieben. Der Import ist über stabile IDs wiederholbar und löscht ohne die Option oben keine bestehenden Daten.</p>
|
||||
</div>
|
||||
{{end}}
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,135 @@
|
||||
{{define "layout"}}<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{{.Title}} · LektorenPlan</title>
|
||||
<meta name="theme-color" content="#f4efe4">
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
<script defer src="/static/app.js"></script>
|
||||
</head>
|
||||
<body class="{{if not .User}}auth-page{{else}}app-page{{end}}">
|
||||
{{if .User}}
|
||||
<div class="app-shell">
|
||||
<aside class="sidebar">
|
||||
<a class="brand" href="/plan" aria-label="LektorenPlan Startseite">
|
||||
<span class="brand-mark" aria-hidden="true">
|
||||
<svg viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M8 40h32M12 40V22l12-8 12 8v18"/>
|
||||
<path d="M24 8v14M20 12h8"/>
|
||||
<path d="M19 40V31a5 5 0 0 1 10 0v9"/>
|
||||
<path d="M6 40h36" stroke-dasharray="2 3" stroke-opacity=".45"/>
|
||||
</svg>
|
||||
</span>
|
||||
<span class="brand-text"><strong>LektorenPlan</strong><small>Pfarreiplanung im Netz</small></span>
|
||||
</a>
|
||||
<button class="sidebar-close icon-button" type="button" data-nav-close aria-label="Navigation schließen">{{icon "close"}}</button>
|
||||
|
||||
{{if .Tenant}}
|
||||
<div class="tenant-switch">
|
||||
<span class="field-caption">Aktiver Mandant</span>
|
||||
<form method="get" action="/switch" class="tenant-form">
|
||||
<select name="tid" aria-label="Mandant wechseln" onchange="this.form.submit()">
|
||||
{{range .Tenants}}
|
||||
<option value="{{.ID}}" {{if eq $.Tenant.ID .ID}}selected{{end}}>{{.Name}}</option>
|
||||
{{end}}
|
||||
</select>
|
||||
<noscript><button class="btn btn-small" type="submit">Wechseln</button></noscript>
|
||||
</form>
|
||||
</div>
|
||||
{{else if .Tenants}}
|
||||
<div class="tenant-switch">
|
||||
<span class="field-caption">Mandant wählen</span>
|
||||
<form method="get" action="/switch" class="tenant-form">
|
||||
<select name="tid" aria-label="Mandant wählen" onchange="this.form.submit()">
|
||||
{{range .Tenants}}<option value="{{.ID}}">{{.Name}}</option>{{end}}
|
||||
</select>
|
||||
</form>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
<nav class="nav" id="main-navigation" aria-label="Hauptnavigation">
|
||||
<span class="nav-heading">Planung</span>
|
||||
<a class="nav-link {{if eq .Active "plan"}}active{{end}}" href="/plan">{{icon "calendar"}}<span>Gottesdienstplan</span></a>
|
||||
<a class="nav-link {{if eq .Active "services"}}active{{end}}" href="/services">{{icon "list"}}<span>Gottesdienstordnung</span></a>
|
||||
<a class="nav-link {{if eq .Active "team"}}active{{end}}" href="/team">{{icon "users"}}<span>Team & Abwesenheiten</span></a>
|
||||
<a class="nav-link {{if eq .Active "statistics"}}active{{end}}" href="/statistics">{{icon "chart"}}<span>Statistik</span></a>
|
||||
|
||||
<span class="nav-heading">Organisation</span>
|
||||
<a class="nav-link {{if eq .Active "exchange"}}active{{end}}" href="/exchange">{{icon "exchange"}}<span>Austausch</span></a>
|
||||
<a class="nav-link {{if eq .Active "liturgy"}}active{{end}}" href="/liturgy">{{icon "book"}}<span>Liturgischer Kalender</span></a>
|
||||
<a class="nav-link {{if eq .Active "settings"}}active{{end}}" href="/settings">{{icon "settings"}}<span>Einstellungen</span></a>
|
||||
|
||||
{{if .IsAdmin}}
|
||||
<span class="nav-heading">Administration</span>
|
||||
<a class="nav-link {{if eq .Active "admin_tenants"}}active{{end}}" href="/admin/tenants">{{icon "church"}}<span>Mandanten</span></a>
|
||||
<a class="nav-link {{if eq .Active "admin_users"}}active{{end}}" href="/admin/users">{{icon "shield"}}<span>Konten & Rechte</span></a>
|
||||
<a class="nav-link {{if eq .Active "admin_churches"}}active{{end}}" href="/admin/churches">{{icon "church"}}<span>Kirchen</span></a>
|
||||
{{end}}
|
||||
</nav>
|
||||
|
||||
<div class="sidebar-foot">
|
||||
{{if .DemoMode}}<span class="demo-pill">Demo</span>{{end}}
|
||||
<span class="version">Version {{.Version}}</span>
|
||||
<span class="source">Liturgie: www.eucharistiefeier.de</span>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div class="app-main">
|
||||
<header class="topbar">
|
||||
<div class="topbar-left">
|
||||
<button class="nav-toggle icon-button" type="button" data-nav-toggle aria-label="Navigation öffnen" aria-expanded="false" aria-controls="main-navigation">{{icon "menu"}}</button>
|
||||
<div class="topbar-title">
|
||||
<span class="eyebrow">{{if .Tenant}}{{.Tenant.Name}}{{else}}LektorenPlan{{end}}</span>
|
||||
<h1>{{.Title}}</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div class="topbar-actions">
|
||||
{{if or (eq .Active "plan") (eq .Active "services")}}
|
||||
<a class="btn btn-ghost btn-small" href="/pdf?variant=plan&start={{.Data.Start}}&end={{.Data.End}}" target="_blank" rel="noopener">{{icon "printer"}}<span>Drucken</span></a>
|
||||
{{end}}
|
||||
<div class="account">
|
||||
<span class="avatar" aria-hidden="true">{{initials .User.DisplayName ""}}</span>
|
||||
<span class="account-text">
|
||||
<strong>{{.User.DisplayName}}</strong>
|
||||
<small>{{userRole .User.Role}}</small>
|
||||
</span>
|
||||
<form method="post" action="/logout">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<button class="icon-button" type="submit" title="Abmelden">{{icon "logout"}}</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{{if .Flash}}
|
||||
<div class="flash flash-{{.FlashKind}}" role="status">
|
||||
<span class="flash-icon">{{if eq .FlashKind "error"}}!{{else if eq .FlashKind "info"}}i{{else}}✓{{end}}</span>
|
||||
<span>{{.Flash}}</span>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
<main class="content">
|
||||
{{template "content" .}}
|
||||
</main>
|
||||
|
||||
<footer class="app-footer">
|
||||
<span>LektorenPlan · warme Papieroptik für die Pfarrplanung</span>
|
||||
<span>Liturgische Daten: www.eucharistiefeier.de</span>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
{{else}}
|
||||
<div class="auth-shell">
|
||||
{{if .Flash}}
|
||||
<div class="flash flash-{{.FlashKind}} auth-flash" role="status">
|
||||
<span class="flash-icon">{{if eq .FlashKind "error"}}!{{else if eq .FlashKind "info"}}i{{else}}✓{{end}}</span>
|
||||
<span>{{.Flash}}</span>
|
||||
</div>
|
||||
{{end}}
|
||||
{{template "content" .}}
|
||||
<p class="auth-foot">Liturgische Daten von www.eucharistiefeier.de</p>
|
||||
</div>
|
||||
{{end}}
|
||||
</body>
|
||||
</html>{{end}}
|
||||
@@ -0,0 +1,88 @@
|
||||
{{define "content"}}
|
||||
<div class="page-stack">
|
||||
<section class="page-intro">
|
||||
<div>
|
||||
<span class="eyebrow">Kirchenjahr</span>
|
||||
<h2>Liturgischer Kalender {{.Data.Year}}</h2>
|
||||
<p>Rang, liturgische Farbe und Lesungen für jeden Tag. Der Bestand wird aus dem mitgelieferten Schnappschuss gelesen und kann online bei www.eucharistiefeier.de aktualisiert werden.</p>
|
||||
</div>
|
||||
<div class="intro-actions">
|
||||
{{if .Data.CanEdit}}
|
||||
<form method="post" action="/liturgy/sync" data-confirm="Kalenderjahr {{.Data.Year}} online aktualisieren?">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<input type="hidden" name="year" value="{{.Data.Year}}">
|
||||
<button class="btn btn-primary" type="submit">{{icon "sparkles"}} Jahr online aktualisieren</button>
|
||||
</form>
|
||||
{{end}}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="toolbar card">
|
||||
<div class="toolbar-group">
|
||||
<span class="field-caption">Jahr</span>
|
||||
{{range .Data.Years}}<a class="chip {{if eq . $.Data.Year}}active{{end}}" href="/liturgy?year={{.}}{{if $.Data.Month}}&month={{$.Data.Month}}{{end}}">{{.}}</a>{{end}}
|
||||
</div>
|
||||
<div class="toolbar-group">
|
||||
<span class="field-caption">Monat</span>
|
||||
<a class="chip {{if eq .Data.Month 0}}active{{end}}" href="/liturgy?year={{.Data.Year}}">Ganzes Jahr</a>
|
||||
{{range seq 1 12}}<a class="chip {{if eq . $.Data.Month}}active{{end}}" href="/liturgy?year={{$.Data.Year}}&month={{.}}">{{shortMonthNumber .}}</a>{{end}}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="stat-strip">
|
||||
<article class="mini-stat"><span class="mini-stat-label">Tage</span><strong>{{.Data.Total}}</strong><small>im gewählten Ausschnitt</small></article>
|
||||
<article class="mini-stat"><span class="mini-stat-label">Feste</span><strong>{{.Data.Feasts}}</strong><small>Feste und Hochfeste</small></article>
|
||||
<article class="mini-stat"><span class="mini-stat-label">Gebotene Tage</span><strong>{{.Data.Obligations}}</strong><small>Sonntage und Feiertage</small></article>
|
||||
<article class="mini-stat"><span class="mini-stat-label">Gespeichert</span><strong>{{.Data.Stored}}</strong><small>Tage aus der Datenbank</small></article>
|
||||
</section>
|
||||
|
||||
{{if .Data.LocalOnly}}
|
||||
<div class="notice">
|
||||
{{icon "book"}}
|
||||
<div><strong>Lokale Berechnung</strong><p>Für {{.Data.Year}} liegen noch keine gespeicherten Kalenderdaten vor. Die Tabelle zeigt die lokale Berechnung. Mit „Jahr online aktualisieren“ werden die Daten dauerhaft gespeichert.</p></div>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
<section class="calendar-card liturgy-card">
|
||||
<div class="table-scroll">
|
||||
<table class="calendar-table liturgy-table">
|
||||
<thead>
|
||||
<tr><th class="col-date">Datum</th><th>Wochentag</th><th>Liturgie</th><th>Rang</th><th>Farbe</th><th>Lesungen</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{{range .Data.Days}}
|
||||
<tr class="{{if .IsHighFeast}}is-highfeast{{else if .IsSunday}}is-sunday{{else if .IsFeast}}is-feast{{else if .IsObligation}}is-obligation{{end}}">
|
||||
<td class="date-cell">
|
||||
<div class="date-number">{{dayNumber .Date}}</div>
|
||||
<div class="date-meta"><span>{{shortMonth .Date}}</span><span>{{yearOf .Date}}</span></div>
|
||||
<span class="liturgical-bar" style="background:{{.ColorHex}}"></span>
|
||||
</td>
|
||||
<td>{{weekdayName .Date}}</td>
|
||||
<td>
|
||||
<div class="liturgy-title">{{feastGlyph .Symbol}}<strong>{{.DisplayTitle}}</strong></div>
|
||||
{{if .Remark}}<div class="liturgy-remark">{{.Remark}}</div>{{end}}
|
||||
{{if eq .Source "lokale Berechnung"}}<span class="badge badge-neutral">lokal berechnet</span>{{end}}
|
||||
</td>
|
||||
<td>{{if .Rank.ShortLabel}}<span class="badge badge-rank rank-{{.Rank.ShortLabel}}">{{.Rank.Label}}</span>{{else}}<span class="muted">Wochentag</span>{{end}}</td>
|
||||
<td><span class="badge badge-color" style="--badge-color:{{.ColorHex}}">{{.Color.Label}}</span></td>
|
||||
<td class="readings-cell">
|
||||
{{if .Readings.IsEmpty}}<span class="muted">—</span>{{else}}
|
||||
<div class="reading-lines">
|
||||
{{if .Readings.First}}<span><b>1.</b> {{.Readings.First}}</span>{{end}}
|
||||
{{if .Readings.Psalm}}<span><b>Ps.</b> {{.Readings.Psalm}}</span>{{end}}
|
||||
{{if .Readings.Second}}<span><b>2.</b> {{.Readings.Second}}</span>{{end}}
|
||||
{{if .Readings.Gospel}}<span><b>Ev.</b> {{.Readings.Gospel}}</span>{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
</td>
|
||||
</tr>
|
||||
{{else}}
|
||||
<tr><td colspan="6"><span class="empty-note">Keine Kalendertage verfügbar.</span></td></tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
<p class="table-note">Quelle: {{.Data.Source}} · Letzte Aktualisierung: {{if .Data.LastSync}}{{.Data.LastSync}}{{else}}noch nicht{{end}} · Die Daten bleiben Eigentum der Quelle.</p>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,67 @@
|
||||
{{define "content"}}
|
||||
<div class="auth-card">
|
||||
<section class="auth-art">
|
||||
<div class="auth-brand">
|
||||
<span class="brand-mark large" aria-hidden="true">
|
||||
<svg viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M8 40h32M12 40V22l12-8 12 8v18"/>
|
||||
<path d="M24 8v14M20 12h8"/>
|
||||
<path d="M19 40V31a5 5 0 0 1 10 0v9"/>
|
||||
<path d="M6 40h36" stroke-dasharray="2 3" stroke-opacity=".45"/>
|
||||
</svg>
|
||||
</span>
|
||||
<div>
|
||||
<h1>LektorenPlan</h1>
|
||||
<p>Gottesdienste, Dienste und Menschen klug zusammenbringen.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="auth-church">
|
||||
{{churchGlyph "gothic" "#C2A14D"}}
|
||||
</div>
|
||||
<div class="auth-quote">
|
||||
<span class="quote-mark">„</span>
|
||||
<p>Jeder Sonntag braucht Menschen, die das Wort tragen und die Gemeinschaft begleiten.</p>
|
||||
<span class="quote-source">Pfarreiengemeinschaft Bad Godesberg</span>
|
||||
</div>
|
||||
<div class="auth-badges">
|
||||
<span class="badge badge-gold">Kalender</span>
|
||||
<span class="badge badge-green">Planung</span>
|
||||
<span class="badge badge-burgundy">Statistik</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="auth-form-panel">
|
||||
<div class="auth-form-head">
|
||||
<span class="eyebrow">Willkommen zurück</span>
|
||||
<h2>Anmelden</h2>
|
||||
<p>Bitte melden Sie sich mit Ihrem Konto an. Administratoren, Redakteure und Leser sehen jeweils die ihnen freigegebenen Mandanten.</p>
|
||||
</div>
|
||||
<form method="post" action="/login" class="form-stack" autocomplete="on">
|
||||
<input type="hidden" name="next" value="{{.Data.Next}}">
|
||||
<label class="field">
|
||||
<span class="field-label">Benutzername</span>
|
||||
<input type="text" name="username" required autofocus autocomplete="username" placeholder="z. B. admin">
|
||||
</label>
|
||||
<label class="field">
|
||||
<span class="field-label">Passwort</span>
|
||||
<input type="password" name="password" required autocomplete="current-password" placeholder="••••••••">
|
||||
</label>
|
||||
<button class="btn btn-primary btn-block" type="submit">Anmelden</button>
|
||||
</form>
|
||||
{{if .DemoMode}}
|
||||
<div class="demo-accounts">
|
||||
<span class="demo-accounts-title">Demo-Zugänge</span>
|
||||
<div class="demo-account-grid">
|
||||
<div><strong>admin</strong><span>admin123 · Verwaltung</span></div>
|
||||
<div><strong>editor</strong><span>editor123 · Redaktion</span></div>
|
||||
<div><strong>reader</strong><span>reader123 · Lesen</span></div>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="auth-note">
|
||||
<span class="dot"></span>
|
||||
<span>Sitzungen sind serverseitig gespeichert, Passwörter mit bcrypt geschützt.</span>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,24 @@
|
||||
{{define "content"}}
|
||||
<div class="error-page card">
|
||||
<div class="error-code">◎</div>
|
||||
<div>
|
||||
<span class="eyebrow">Keine Pfarrei ausgewählt</span>
|
||||
<h2>Noch kein Mandant freigegeben</h2>
|
||||
{{if .Data.IsAdmin}}
|
||||
<p>Legen Sie unter „Mandanten“ die erste Pfarrei oder Planungsgruppe an und weisen Sie anschließend Kirchen, Personen und Konten zu.</p>
|
||||
<div class="form-actions">
|
||||
<a class="btn btn-primary" href="/admin/tenants">{{icon "plus"}} Mandant anlegen</a>
|
||||
<a class="btn btn-ghost" href="/admin/users">{{icon "shield"}} Konten verwalten</a>
|
||||
</div>
|
||||
{{else}}
|
||||
<p>Ihr Konto ist noch keinem Mandanten zugeordnet. Bitte wenden Sie sich an die Administration, damit Ihre Pfarrei freigegeben wird.</p>
|
||||
<div class="form-actions">
|
||||
<form method="post" action="/logout">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<button class="btn btn-primary" type="submit">Abmelden</button>
|
||||
</form>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,168 @@
|
||||
{{define "content"}}
|
||||
{{$person := .Data.Person}}
|
||||
<div class="page-stack">
|
||||
<section class="detail-hero card">
|
||||
<div class="detail-hero-main">
|
||||
<span class="avatar large">{{$person.Initials}}</span>
|
||||
<div>
|
||||
<span class="eyebrow">{{if .Data.IsNew}}Neue Person{{else}}Teammitglied{{end}}</span>
|
||||
<h2>{{if $person.FullName}}{{$person.FullName}}{{else}}Neue Person{{end}}</h2>
|
||||
<p class="detail-place">{{$person.RoleLabel}}{{if not $person.Active}} · inaktiv{{end}}</p>
|
||||
<div class="badge-row">
|
||||
{{if .Data.IsNew}}<span class="badge badge-gold">noch nicht gespeichert</span>{{else}}
|
||||
<span class="badge badge-green">{{$person.RoleLabel}}</span>
|
||||
{{if .Data.Stats.Total}}<span class="badge badge-neutral">{{.Data.Stats.Total}} Einsätze im Jahr</span>{{end}}
|
||||
{{if gt .Data.UpcomingCount 0}}<span class="badge badge-gold">{{.Data.UpcomingCount}} kommende Dienste</span>{{end}}
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="detail-hero-actions">
|
||||
<a class="btn btn-ghost btn-small" href="/team">{{icon "users"}} Zum Team</a>
|
||||
{{if and .Data.CanEdit (not .Data.IsNew)}}
|
||||
<form method="post" action="/team/person/{{$person.ID}}/delete" data-confirm="Person mit allen Einteilungen und Abwesenheiten löschen?">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<button class="btn btn-danger btn-small" type="submit">{{icon "trash"}} Löschen</button>
|
||||
</form>
|
||||
{{end}}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="detail-grid">
|
||||
<div class="page-stack">
|
||||
<section class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Stammdaten</span><h3>Person bearbeiten</h3></div></div>
|
||||
{{if .Data.CanEdit}}
|
||||
<form method="post" action="/team/person/{{$person.ID}}/save" class="form-stack">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<div class="form-row">
|
||||
<label class="field"><span class="field-label">Vorname</span><input type="text" name="first_name" value="{{$person.FirstName}}"></label>
|
||||
<label class="field"><span class="field-label">Nachname</span><input type="text" name="last_name" value="{{$person.LastName}}"></label>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label class="field"><span class="field-label">E-Mail</span><input type="email" name="email" value="{{$person.Email}}"></label>
|
||||
<label class="field"><span class="field-label">Telefon</span><input type="text" name="phone" value="{{$person.Phone}}"></label>
|
||||
</div>
|
||||
<div class="field-group">
|
||||
<span class="field-label">Dienste</span>
|
||||
<div class="checkbox-row">
|
||||
<label class="check"><input type="checkbox" name="role_lector" value="1" {{if roleChecked $person "lector"}}checked{{end}}><span>Lektor</span></label>
|
||||
<label class="check"><input type="checkbox" name="role_helper" value="1" {{if roleChecked $person "helper"}}checked{{end}}><span>Kommunionhelfer</span></label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field-group">
|
||||
<span class="field-label">Bevorzugte Kirchen</span>
|
||||
<div class="checkbox-grid">
|
||||
{{range .Data.Churches}}
|
||||
<label class="check"><input type="checkbox" name="preferred_churches" value="{{.ID}}" {{if containsString $person.PreferredChurchIDs .ID}}checked{{end}}><span>{{.Name}}</span></label>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
<div class="field-group">
|
||||
<span class="field-label">Bevorzugte Einsatztage</span>
|
||||
<div class="weekday-grid">
|
||||
{{range .Data.Weekdays}}
|
||||
<label class="weekday-check"><input type="checkbox" name="preferred_weekdays" value="{{.Number}}" {{if containsInt $person.PreferredWeekdays .Number}}checked{{end}}><span>{{.Short}}</span></label>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
<label class="field"><span class="field-label">Bevorzugte Gottesdienste <small>Komma-getrennt, z. B. Familienmesse, Vesper</small></span><input type="text" name="preferred_titles" value="{{join $person.PreferredServiceTitles ", "}}"></label>
|
||||
<div class="form-row">
|
||||
<label class="field"><span class="field-label">Monatslimit <small>0 = kein Limit</small></span><input type="number" name="max_per_month" min="0" max="30" value="{{$person.MaxPerMonth}}"></label>
|
||||
<label class="field"><span class="field-label">Status</span>
|
||||
<label class="check standalone"><input type="checkbox" name="active" value="1" {{if $person.Active}}checked{{end}}><span>aktiv und planbar</span></label>
|
||||
</label>
|
||||
</div>
|
||||
<label class="field"><span class="field-label">Notizen</span><textarea name="notes" rows="3">{{$person.Notes}}</textarea></label>
|
||||
<button class="btn btn-primary" type="submit">{{if .Data.IsNew}}Person anlegen{{else}}Person speichern{{end}}</button>
|
||||
</form>
|
||||
{{else}}
|
||||
<dl class="detail-list">
|
||||
<dt>Name</dt><dd>{{$person.FullName}}</dd>
|
||||
<dt>Dienste</dt><dd>{{$person.RoleLabel}}</dd>
|
||||
{{if $person.Email}}<dt>E-Mail</dt><dd>{{$person.Email}}</dd>{{end}}
|
||||
{{if $person.Phone}}<dt>Telefon</dt><dd>{{$person.Phone}}</dd>{{end}}
|
||||
<dt>Monatslimit</dt><dd>{{if gt $person.MaxPerMonth 0}}{{$person.MaxPerMonth}}{{else}}kein Limit{{end}}</dd>
|
||||
{{if $person.Notes}}<dt>Notizen</dt><dd>{{$person.Notes}}</dd>{{end}}
|
||||
</dl>
|
||||
<p class="empty-note">Ihr Konto hat nur lesenden Zugriff.</p>
|
||||
{{end}}
|
||||
</section>
|
||||
|
||||
{{if not .Data.IsNew}}
|
||||
<section class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Historie</span><h3>Einteilungen</h3></div><span class="count-pill">{{.Data.TotalCount}}</span></div>
|
||||
<div class="table-scroll">
|
||||
<table class="data-table">
|
||||
<thead><tr><th>Datum</th><th>Gottesdienst</th><th>Kirche</th><th>Rolle</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Data.Assignments}}
|
||||
<tr>
|
||||
<td><strong>{{mediumDate .Service.Date}}</strong><br><small>{{timeLabel .Service.TimeMinutes}}</small></td>
|
||||
<td>{{.Service.Title}}{{if .Assignment.Locked}} <span class="badge badge-gold">gesperrt</span>{{end}}</td>
|
||||
<td>{{if .Church.Name}}{{.Church.Name}}{{else}}—{{end}}</td>
|
||||
<td><span class="badge {{if eq (printf "%s" .Assignment.Role) "lector"}}badge-green{{else}}badge-gold{{end}}">{{roleTitle .Assignment.Role}}</span></td>
|
||||
<td><a class="icon-button" href="/services/{{.Service.ID}}" title="Gottesdienst öffnen">{{icon "right"}}</a></td>
|
||||
</tr>
|
||||
{{else}}
|
||||
<tr><td colspan="5"><span class="empty-note">Noch keine Einteilungen.</span></td></tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
{{end}}
|
||||
</div>
|
||||
|
||||
<aside class="page-stack">
|
||||
{{if not .Data.IsNew}}
|
||||
<section class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Auswertung</span><h3>Jahr {{.Data.Year}}</h3></div></div>
|
||||
<div class="person-stats large">
|
||||
<div><strong>{{.Data.Stats.Total}}</strong><span>Einsätze</span></div>
|
||||
<div><strong>{{.Data.Stats.Lectors}}</strong><span>Lektor</span></div>
|
||||
<div><strong>{{.Data.Stats.Helpers}}</strong><span>Helfer</span></div>
|
||||
<div><strong>{{.Data.Stats.SundayCount}}</strong><span>Sonntage</span></div>
|
||||
</div>
|
||||
<dl class="detail-list tight">
|
||||
<dt>Präferenztreffer</dt><dd>{{percent .Data.Stats.PreferenceRate}}</dd>
|
||||
<dt>Letzter Einsatz</dt><dd>{{if .Data.Stats.LastAssignment}}{{mediumDate (derefTime .Data.Stats.LastAssignment)}}{{else}}noch keiner{{end}}</dd>
|
||||
<dt>Monatslimit</dt><dd>{{if gt $person.MaxPerMonth 0}}{{$person.MaxPerMonth}} Einsätze{{else}}kein Limit{{end}}</dd>
|
||||
</dl>
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
<section class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Nicht verfügbar</span><h3>Abwesenheiten</h3></div><span class="count-pill">{{len .Data.Absences}}</span></div>
|
||||
{{if .Data.CanEdit}}
|
||||
<form method="post" action="/team/person/{{$person.ID}}/absence" class="form-stack compact">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<div class="form-row">
|
||||
<label class="field"><span class="field-label">Von</span><input type="date" name="start" required></label>
|
||||
<label class="field"><span class="field-label">Bis</span><input type="date" name="end" required></label>
|
||||
</div>
|
||||
<label class="field"><span class="field-label">Grund <small>optional</small></span><input type="text" name="reason" placeholder="z. B. Urlaub"></label>
|
||||
<button class="btn btn-secondary btn-small" type="submit">{{icon "plus"}} Abwesenheit eintragen</button>
|
||||
</form>
|
||||
{{end}}
|
||||
<div class="compact-list">
|
||||
{{range .Data.Absences}}
|
||||
<div class="compact-row">
|
||||
<div><strong>{{shortDate .Start}} – {{shortDate .End}}</strong><small>{{if .Reason}}{{.Reason}}{{else}}ohne Angabe{{end}}</small></div>
|
||||
{{if $.Data.CanEdit}}
|
||||
<form method="post" action="/team/person/{{$person.ID}}/absence/delete" data-confirm="Abwesenheit löschen?">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
<input type="hidden" name="id" value="{{.ID}}">
|
||||
<button class="icon-button danger" type="submit" title="Abwesenheit löschen">{{icon "trash"}}</button>
|
||||
</form>
|
||||
{{end}}
|
||||
</div>
|
||||
{{else}}
|
||||
<p class="empty-note">Keine Abwesenheiten hinterlegt.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
</section>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,164 @@
|
||||
{{define "content"}}
|
||||
<div class="page-stack">
|
||||
<section class="toolbar card">
|
||||
<div class="toolbar-group range-nav">
|
||||
<a class="icon-button" href="/plan?start={{.Data.PrevStart}}&end={{.Data.PrevEnd}}" title="Vorheriger Monat">{{icon "left"}}</a>
|
||||
<form class="range-form" method="get" action="/plan">
|
||||
<label class="field field-inline"><span>Von</span><input type="date" name="start" value="{{.Data.Start}}"></label>
|
||||
<label class="field field-inline"><span>Bis</span><input type="date" name="end" value="{{.Data.End}}"></label>
|
||||
<button class="btn btn-secondary btn-small" type="submit">Anzeigen</button>
|
||||
</form>
|
||||
<a class="icon-button" href="/plan?start={{.Data.NextStart}}&end={{.Data.NextEnd}}" title="Nächster Monat">{{icon "right"}}</a>
|
||||
</div>
|
||||
<div class="toolbar-group">
|
||||
<a class="chip" href="/plan">Dieser Monat</a>
|
||||
<a class="chip" href="/plan?start={{.Data.PresetFourStart}}&end={{.Data.PresetFourEnd}}">Nächste 4 Wochen</a>
|
||||
<a class="chip" href="/statistics?start={{.Data.Start}}&end={{.Data.End}}">{{icon "chart"}} Statistik</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="range-banner">
|
||||
<div>
|
||||
<span class="eyebrow">Planungszeitraum</span>
|
||||
<h2>{{rangeLong .Data.Range}}</h2>
|
||||
<p>{{dayCount .Data.Range}} Tage · {{.Data.Stats.ServiceCount}} Gottesdienste · {{.Data.Stats.OpenSlots}} offene Dienste</p>
|
||||
</div>
|
||||
<div class="range-actions">
|
||||
{{if .Data.CanEdit}}
|
||||
<form method="post" action="/plan/generate" 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}}">
|
||||
<button class="btn btn-secondary btn-small" type="submit">{{icon "plus"}} Termine erzeugen</button>
|
||||
</form>
|
||||
<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}}">
|
||||
<button class="btn btn-primary btn-small" type="submit">{{icon "sparkles"}} Offene Dienste besetzen</button>
|
||||
</form>
|
||||
{{end}}
|
||||
<a class="btn btn-ghost btn-small" href="/pdf?variant=compact&start={{.Data.Start}}&end={{.Data.End}}" target="_blank" rel="noopener">{{icon "printer"}} Kompaktliste</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="stat-strip">
|
||||
<article class="mini-stat">
|
||||
<span class="mini-stat-label">Gottesdienste</span>
|
||||
<strong>{{.Data.Stats.ServiceCount}}</strong>
|
||||
<small>{{percent .Data.Stats.CoverageRate}} besetzt</small>
|
||||
</article>
|
||||
<article class="mini-stat">
|
||||
<span class="mini-stat-label">Einteilungen</span>
|
||||
<strong>{{.Data.Stats.AssignmentCount}}</strong>
|
||||
<small>von {{.Data.Stats.RequiredSlots}} benötigten Diensten</small>
|
||||
</article>
|
||||
<article class="mini-stat {{if gt .Data.Stats.OpenSlots 0}}warn{{end}}">
|
||||
<span class="mini-stat-label">Offen</span>
|
||||
<strong>{{.Data.Stats.OpenSlots}}</strong>
|
||||
<small>{{plural .Data.Stats.OpenSlots "Dienst" "Dienste"}}</small>
|
||||
</article>
|
||||
<article class="mini-stat">
|
||||
<span class="mini-stat-label">Aktive Personen</span>
|
||||
<strong>{{.Data.Stats.ActivePeople}}</strong>
|
||||
<small>{{preferencePct .Data.Stats}} Präferenztreffer</small>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<div class="plan-legend">
|
||||
<div class="filter-chips" role="group" aria-label="Tage filtern">
|
||||
<button class="chip active" type="button" data-plan-filter="all">Alle Tage</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="feasts">Sonn- & Feiertage</button>
|
||||
</div>
|
||||
<div class="legend-items">
|
||||
<span><i class="swatch sunday"></i>Sonntag</span>
|
||||
<span><i class="swatch feast"></i>Hochfest</span>
|
||||
<span><i class="swatch open"></i>Offener Dienst</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section class="calendar-card" data-plan-table>
|
||||
<div class="table-scroll">
|
||||
<table class="calendar-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="col-date">Tag</th>
|
||||
<th class="col-liturgy">Liturgie & Lesungen</th>
|
||||
{{range .Data.Churches}}
|
||||
<th class="col-church">
|
||||
<span class="church-head" title="{{.Name}} · {{.Address}}">
|
||||
{{churchGlyph .Symbol .ColorHex}}
|
||||
<span class="church-head-text"><strong>{{.ShortName}}</strong><small>{{.Name}}</small></span>
|
||||
</span>
|
||||
</th>
|
||||
{{end}}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{{range $row := .Data.Rows}}
|
||||
<tr class="plan-row {{if .IsHighFeast}}is-highfeast{{else if .IsSunday}}is-sunday{{else if .IsObligation}}is-obligation{{else if .IsFeast}}is-feast{{end}}"
|
||||
data-plan-row
|
||||
data-has-services="{{if .HasServices}}true{{else}}false{{end}}"
|
||||
data-open="{{.OpenSlots}}"
|
||||
data-special="{{if .IsSpecialDay}}true{{else}}false{{end}}">
|
||||
<td class="date-cell">
|
||||
<div class="date-number">{{dayNumber .Date}}</div>
|
||||
<div class="date-meta"><span>{{shortWeekday .Date}}</span><span>{{shortMonth .Date}}</span></div>
|
||||
{{if .LiturgicalDay}}<span class="liturgical-bar" style="background:{{liturgicalColor .LiturgicalDay}}"></span>{{end}}
|
||||
</td>
|
||||
<td class="liturgy-cell">
|
||||
{{if .LiturgicalDay}}
|
||||
<div class="liturgy-title">
|
||||
{{feastGlyph .LiturgicalDay.Symbol}}
|
||||
<strong>{{.LiturgicalDay.DisplayTitle}}</strong>
|
||||
</div>
|
||||
<div class="liturgy-meta">
|
||||
{{if .LiturgicalDay.BadgeText}}<span class="badge badge-rank rank-{{.LiturgicalDay.Rank.ShortLabel}}">{{.LiturgicalDay.BadgeText}}</span>{{end}}
|
||||
<span class="badge badge-color" style="--badge-color:{{liturgicalColor .LiturgicalDay}}">{{.LiturgicalDay.Color.Label}}</span>
|
||||
{{if .LiturgicalDay.IsObligation}}<span class="badge badge-burgundy">geboten</span>{{end}}
|
||||
</div>
|
||||
{{if not .LiturgicalDay.Readings.IsEmpty}}
|
||||
<div class="readings" title="{{.LiturgicalDay.Readings.FullLabel}}">{{.LiturgicalDay.Readings.ShortLabel}}</div>
|
||||
{{end}}
|
||||
{{if .LiturgicalDay.Remark}}<div class="liturgy-remark">{{.LiturgicalDay.Remark}}</div>{{end}}
|
||||
{{else}}
|
||||
<span class="muted">—</span>
|
||||
{{end}}
|
||||
</td>
|
||||
{{range $.Data.Churches}}
|
||||
{{$church := .}}
|
||||
<td class="church-cell">
|
||||
{{$services := $row.ServicesForChurch $church.ID}}
|
||||
{{if $services}}
|
||||
<div class="service-stack">
|
||||
{{range $services}}
|
||||
<a class="service-card {{if .IsFullyStaffed}}staffed{{else}}open{{end}}" href="/services/{{.Service.ID}}?start={{$.Data.Start}}&end={{$.Data.End}}">
|
||||
<span class="service-time">{{timeLabel .Service.TimeMinutes}}</span>
|
||||
<span class="service-title">{{.Service.Title}}{{if eq (printf "%s" .Service.Kind) "special"}}<span class="service-kind">Sonder</span>{{end}}</span>
|
||||
{{if .Service.Location}}<span class="service-location">{{deref .Service.Location}}</span>{{end}}
|
||||
<span class="service-people">
|
||||
{{range .Assignments}}
|
||||
{{$person := index $.Data.People .PersonID}}
|
||||
<span class="person-chip role-{{roleShort .Role}}" title="{{roleTitle .Role}}{{if $person}} · {{$person.FullName}}{{end}}">{{if $person}}{{$person.AbbreviatedName}}{{else}}?{{end}}</span>
|
||||
{{end}}
|
||||
</span>
|
||||
{{if not .IsFullyStaffed}}<span class="open-badge">{{plural .OpenSlots "Platz offen" "Plätze offen"}}</span>{{end}}
|
||||
</a>
|
||||
{{end}}
|
||||
</div>
|
||||
{{else}}
|
||||
<span class="empty-cell">—</span>
|
||||
{{end}}
|
||||
</td>
|
||||
{{end}}
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
<p class="table-note">Klicken Sie auf einen Gottesdienst, um Einteilungen zu ändern oder Vorschläge zu sehen. Kirchennamen erscheinen als Tooltip.</p>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,200 @@
|
||||
{{define "content"}}
|
||||
{{$service := .Data.Service.Service}}
|
||||
<div class="page-stack">
|
||||
<section class="detail-hero card">
|
||||
<div class="detail-hero-main">
|
||||
<div class="detail-church">
|
||||
{{churchGlyph .Data.Church.Symbol .Data.Church.ColorHex}}
|
||||
</div>
|
||||
<div>
|
||||
<span class="eyebrow">{{longDate $service.Date}} · {{timeLabel $service.TimeMinutes}}</span>
|
||||
<h2>{{$service.Title}}</h2>
|
||||
<p class="detail-place">{{$service.PlaceName .Data.Church}}{{if $service.Location}} · außerhalb der Kirche{{end}}</p>
|
||||
<div class="badge-row">
|
||||
<span class="badge {{if eq (printf "%s" $service.Kind) "special"}}badge-burgundy{{else}}badge-green{{end}}">{{$service.Kind.Title}}</span>
|
||||
{{if $service.Locked}}<span class="badge badge-gold">Termin gesperrt</span>{{end}}
|
||||
<span class="badge badge-neutral">{{plural $service.LectorsNeeded "Lektor" "Lektoren"}}</span>
|
||||
<span class="badge badge-neutral">{{plural $service.HelpersNeeded "Kommunionhelfer" "Kommunionhelfer"}}</span>
|
||||
{{if eq .Data.LectorOpen 0}}{{if eq .Data.HelperOpen 0}}<span class="badge badge-green">vollständig besetzt</span>{{end}}{{end}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="detail-hero-actions">
|
||||
<a class="btn btn-ghost btn-small" href="/plan?start={{.Data.Start}}&end={{.Data.End}}">{{icon "calendar"}} Zum Plan</a>
|
||||
{{if and .Data.CanEdit (eq (printf "%s" $service.Kind) "special")}}
|
||||
<form method="post" action="/services/{{$service.ID}}/delete" data-confirm="Diesen Sondergottesdienst wirklich löschen?">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<button class="btn btn-danger btn-small" type="submit">{{icon "trash"}} Löschen</button>
|
||||
</form>
|
||||
{{end}}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="detail-grid">
|
||||
<div class="page-stack">
|
||||
<section class="card">
|
||||
<div class="card-head">
|
||||
<div><span class="eyebrow">Besetzung</span><h3>Lektoren</h3></div>
|
||||
<span class="count-pill {{if gt .Data.LectorOpen 0}}warn{{end}}">{{len .Data.LectorAssigned}} / {{$service.LectorsNeeded}}</span>
|
||||
</div>
|
||||
<div class="assignment-list">
|
||||
{{range .Data.LectorAssigned}}
|
||||
{{$person := index $.Data.People .PersonID}}
|
||||
<div class="assignment-row">
|
||||
<span class="avatar small">{{if $person}}{{$person.Initials}}{{else}}?{{end}}</span>
|
||||
<span class="assignment-person"><strong>{{if $person}}{{$person.FullName}}{{else}}Unbekannt{{end}}</strong><small>{{if $person}}{{$person.RoleLabel}}{{else}}—{{end}}</small></span>
|
||||
{{if .Locked}}<span class="badge badge-gold">gesperrt</span>{{end}}
|
||||
{{if $.Data.CanEdit}}
|
||||
<div class="assignment-actions">
|
||||
<form method="post" action="/services/{{$service.ID}}/lock">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
<input type="hidden" name="assignment_id" value="{{.ID}}">
|
||||
<button class="icon-button" type="submit" title="{{if .Locked}}Sperre lösen{{else}}Einteilung sperren{{end}}">{{if .Locked}}🔒{{else}}🔓{{end}}</button>
|
||||
</form>
|
||||
<form method="post" action="/services/{{$service.ID}}/unassign" data-confirm="Einteilung entfernen?">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
<input type="hidden" name="assignment_id" value="{{.ID}}">
|
||||
<button class="icon-button danger" type="submit" title="Einteilung entfernen">{{icon "trash"}}</button>
|
||||
</form>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
{{if not .Data.LectorAssigned}}<p class="empty-note">Noch kein Lektor eingeteilt.</p>{{end}}
|
||||
</div>
|
||||
{{if and .Data.CanEdit (gt .Data.LectorOpen 0)}}
|
||||
<div class="candidate-block">
|
||||
<span class="field-caption">Vorschläge für Lektoren</span>
|
||||
{{range .Data.LectorCandidates}}
|
||||
<div class="candidate {{if .Blocked}}blocked{{end}}">
|
||||
<div class="candidate-main">
|
||||
<span class="avatar small">{{.Person.Initials}}</span>
|
||||
<div><strong>{{.Person.FullName}}</strong><small>{{.TotalAssignments}} Einsätze im Zeitraum · Score {{formatFloat .Score}}</small></div>
|
||||
</div>
|
||||
<div class="candidate-tags">
|
||||
{{if .Preferred}}<span class="badge badge-green">Präferenz</span>{{end}}
|
||||
{{range .Warnings}}<span class="badge badge-burgundy">{{.}}</span>{{end}}
|
||||
</div>
|
||||
<form method="post" action="/services/{{$service.ID}}/assign" class="candidate-form">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
<input type="hidden" name="role" value="lector">
|
||||
<input type="hidden" name="person_id" value="{{.Person.ID}}">
|
||||
<label class="check-inline"><input type="checkbox" name="locked" value="1"> sperren</label>
|
||||
<button class="btn btn-secondary btn-tiny" type="submit" {{if .Blocked}}disabled{{end}}>Einteilen</button>
|
||||
</form>
|
||||
</div>
|
||||
{{else}}
|
||||
<p class="empty-note">Keine passenden Vorschläge. Bitte Rollen, Abwesenheiten oder Monatslimits prüfen.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-head">
|
||||
<div><span class="eyebrow">Besetzung</span><h3>Kommunionhelfer</h3></div>
|
||||
<span class="count-pill {{if gt .Data.HelperOpen 0}}warn{{end}}">{{len .Data.HelperAssigned}} / {{$service.HelpersNeeded}}</span>
|
||||
</div>
|
||||
<div class="assignment-list">
|
||||
{{range .Data.HelperAssigned}}
|
||||
{{$person := index $.Data.People .PersonID}}
|
||||
<div class="assignment-row">
|
||||
<span class="avatar small">{{if $person}}{{$person.Initials}}{{else}}?{{end}}</span>
|
||||
<span class="assignment-person"><strong>{{if $person}}{{$person.FullName}}{{else}}Unbekannt{{end}}</strong><small>{{if $person}}{{$person.RoleLabel}}{{else}}—{{end}}</small></span>
|
||||
{{if .Locked}}<span class="badge badge-gold">gesperrt</span>{{end}}
|
||||
{{if $.Data.CanEdit}}
|
||||
<div class="assignment-actions">
|
||||
<form method="post" action="/services/{{$service.ID}}/lock">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
<input type="hidden" name="assignment_id" value="{{.ID}}">
|
||||
<button class="icon-button" type="submit" title="{{if .Locked}}Sperre lösen{{else}}Einteilung sperren{{end}}">{{if .Locked}}🔒{{else}}🔓{{end}}</button>
|
||||
</form>
|
||||
<form method="post" action="/services/{{$service.ID}}/unassign" data-confirm="Einteilung entfernen?">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
<input type="hidden" name="assignment_id" value="{{.ID}}">
|
||||
<button class="icon-button danger" type="submit" title="Einteilung entfernen">{{icon "trash"}}</button>
|
||||
</form>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
{{if not .Data.HelperAssigned}}<p class="empty-note">Noch kein Kommunionhelfer eingeteilt.</p>{{end}}
|
||||
</div>
|
||||
{{if and .Data.CanEdit (gt .Data.HelperOpen 0)}}
|
||||
<div class="candidate-block">
|
||||
<span class="field-caption">Vorschläge für Kommunionhelfer</span>
|
||||
{{range .Data.HelperCandidates}}
|
||||
<div class="candidate {{if .Blocked}}blocked{{end}}">
|
||||
<div class="candidate-main">
|
||||
<span class="avatar small">{{.Person.Initials}}</span>
|
||||
<div><strong>{{.Person.FullName}}</strong><small>{{.TotalAssignments}} Einsätze im Zeitraum · Score {{formatFloat .Score}}</small></div>
|
||||
</div>
|
||||
<div class="candidate-tags">
|
||||
{{if .Preferred}}<span class="badge badge-green">Präferenz</span>{{end}}
|
||||
{{range .Warnings}}<span class="badge badge-burgundy">{{.}}</span>{{end}}
|
||||
</div>
|
||||
<form method="post" action="/services/{{$service.ID}}/assign" class="candidate-form">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
<input type="hidden" name="role" value="helper">
|
||||
<input type="hidden" name="person_id" value="{{.Person.ID}}">
|
||||
<label class="check-inline"><input type="checkbox" name="locked" value="1"> sperren</label>
|
||||
<button class="btn btn-secondary btn-tiny" type="submit" {{if .Blocked}}disabled{{end}}>Einteilen</button>
|
||||
</form>
|
||||
</div>
|
||||
{{else}}
|
||||
<p class="empty-note">Keine passenden Vorschläge. Bitte Rollen, Abwesenheiten oder Monatslimits prüfen.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<aside class="page-stack">
|
||||
<section class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Details</span><h3>Gottesdienst</h3></div></div>
|
||||
{{if .Data.CanEdit}}
|
||||
<form method="post" action="/services/{{$service.ID}}/save" class="form-stack">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<input type="hidden" name="start" value="{{.Data.Start}}">
|
||||
<input type="hidden" name="end" value="{{.Data.End}}">
|
||||
<label class="field"><span class="field-label">Titel</span><input type="text" name="title" value="{{$service.Title}}" required></label>
|
||||
<div class="form-row">
|
||||
<label class="field"><span class="field-label">Datum</span><input type="date" name="date" value="{{isoDate $service.Date}}" required></label>
|
||||
<label class="field"><span class="field-label">Uhrzeit</span><input type="time" name="time" value="{{timeLabel $service.TimeMinutes}}" required></label>
|
||||
</div>
|
||||
<label class="field"><span class="field-label">Kirche</span>
|
||||
<select name="church_id">
|
||||
{{range .Data.Churches}}<option value="{{.ID}}" {{if eq .ID $service.ChurchID}}selected{{end}}>{{.Name}}</option>{{end}}
|
||||
</select>
|
||||
</label>
|
||||
<label class="field"><span class="field-label">Freitext-Ort <small>optional</small></span><input type="text" name="location" value="{{deref $service.Location}}" placeholder="z. B. Open-Air im Park"></label>
|
||||
<div class="form-row">
|
||||
<label class="field"><span class="field-label">Lektoren</span><input type="number" name="lectors" min="0" max="6" value="{{$service.LectorsNeeded}}"></label>
|
||||
<label class="field"><span class="field-label">Kommunionhelfer</span><input type="number" name="helpers" min="0" max="6" value="{{$service.HelpersNeeded}}"></label>
|
||||
</div>
|
||||
<label class="field"><span class="field-label">Notizen</span><textarea name="notes" rows="3">{{$service.Notes}}</textarea></label>
|
||||
<label class="check"><input type="checkbox" name="locked" value="1" {{if $service.Locked}}checked{{end}}><span>Termin bei automatischer Planung nicht verändern</span></label>
|
||||
<button class="btn btn-primary btn-block" type="submit">Gottesdienst speichern</button>
|
||||
</form>
|
||||
{{else}}
|
||||
<dl class="detail-list">
|
||||
<dt>Datum</dt><dd>{{longDate $service.Date}}</dd>
|
||||
<dt>Uhrzeit</dt><dd>{{timeLabel $service.TimeMinutes}}</dd>
|
||||
<dt>Kirche</dt><dd>{{.Data.Church.Name}}</dd>
|
||||
{{if $service.Location}}<dt>Ort</dt><dd>{{deref $service.Location}}</dd>{{end}}
|
||||
<dt>Bedarf</dt><dd>{{$service.LectorsNeeded}} Lektoren · {{$service.HelpersNeeded}} Kommunionhelfer</dd>
|
||||
{{if $service.Notes}}<dt>Notizen</dt><dd>{{$service.Notes}}</dd>{{end}}
|
||||
</dl>
|
||||
<p class="empty-note">Ihr Konto hat nur lesenden Zugriff.</p>
|
||||
{{end}}
|
||||
</section>
|
||||
|
||||
<section class="card side-note">
|
||||
<span class="eyebrow">Hinweis</span>
|
||||
<p>Gesperrte Einteilungen bleiben bei „Offene Dienste besetzen“ unverändert. Vorschläge berücksichtigen Abwesenheiten, Monatslimits, Vorlieben und die Fairness im gewählten Zeitraum.</p>
|
||||
<a class="text-link" href="/team">Team und Abwesenheiten pflegen {{icon "right"}}</a>
|
||||
</section>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,190 @@
|
||||
{{define "content"}}
|
||||
<div class="page-stack">
|
||||
<section class="page-intro">
|
||||
<div>
|
||||
<span class="eyebrow">Wiederkehrende Ordnung</span>
|
||||
<h2>Gottesdienste, Ausnahmen und Sondertermine</h2>
|
||||
<p>Die Gottesdienstordnung bildet die Grundlage für die automatische Terminerzeugung. Ausnahmen pausieren einzelne Termine, Sondergottesdienste ergänzen den Plan außerhalb des Regelbetriebs.</p>
|
||||
</div>
|
||||
<div class="intro-stats">
|
||||
<div><strong>{{len .Data.Templates}}</strong><span>Vorlagen</span></div>
|
||||
<div><strong>{{len .Data.Exceptions}}</strong><span>Ausnahmen</span></div>
|
||||
<div><strong>{{len .Data.Specials}}</strong><span>Sondertermine</span></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="church-overview">
|
||||
{{range .Data.Churches}}
|
||||
{{$church := .}}
|
||||
{{$templates := index $.Data.TemplatesByChurch .ID}}
|
||||
<article class="church-card">
|
||||
<header class="church-card-head" title="{{.Address}}">
|
||||
{{churchGlyph .Symbol .ColorHex}}
|
||||
<div><h3>{{.Name}}</h3><p>{{if .ShortName}}{{.ShortName}} · {{end}}{{.Address}}</p></div>
|
||||
<span class="count-pill">{{len $templates}}</span>
|
||||
</header>
|
||||
<div class="template-list">
|
||||
{{range $templates}}
|
||||
<div class="template-row">
|
||||
<div class="template-when"><strong>{{weekdayNumberName .Weekday}}</strong><span>{{timeLabel .TimeMinutes}}</span></div>
|
||||
<div class="template-main">
|
||||
<strong>{{.Title}}</strong>
|
||||
<small>{{.RequirementLabel}} · gültig ab {{mediumDate .ValidFrom}}{{if .ValidTo}} bis {{mediumDate (derefTime .ValidTo)}}{{end}}</small>
|
||||
</div>
|
||||
<div class="template-actions">
|
||||
{{if .Active}}<span class="badge badge-green">aktiv</span>{{else}}<span class="badge badge-neutral">inaktiv</span>{{end}}
|
||||
{{if $.Data.CanEdit}}
|
||||
<a class="icon-button" href="/services?edit={{.ID}}" title="Vorlage bearbeiten">{{icon "settings"}}</a>
|
||||
<form method="post" action="/templates/delete" data-confirm="Vorlage wirklich löschen? Bereits erzeugte Termine bleiben bestehen.">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
<input type="hidden" name="id" value="{{.ID}}">
|
||||
<button class="icon-button danger" type="submit" title="Vorlage löschen">{{icon "trash"}}</button>
|
||||
</form>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
{{else}}
|
||||
<p class="empty-note">Noch keine regelmäßigen Gottesdienste hinterlegt.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
</article>
|
||||
{{end}}
|
||||
</section>
|
||||
|
||||
<div class="two-column">
|
||||
<section class="card">
|
||||
<div class="card-head">
|
||||
<div>
|
||||
<span class="eyebrow">{{if .Data.EditingTemplate}}Bearbeiten{{else}}Neu anlegen{{end}}</span>
|
||||
<h3>{{if .Data.EditingTemplate}}Vorlage bearbeiten{{else}}Regelmäßigen Gottesdienst hinzufügen{{end}}</h3>
|
||||
</div>
|
||||
{{if .Data.EditingTemplate}}<a class="text-link" href="/services">Abbrechen</a>{{end}}
|
||||
</div>
|
||||
{{if .Data.CanEdit}}
|
||||
<form method="post" action="/templates/save" class="form-stack">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<input type="hidden" name="id" value="{{if .Data.EditingTemplate}}{{.Data.EditingTemplate.ID}}{{end}}">
|
||||
<div class="form-row">
|
||||
<label class="field"><span class="field-label">Kirche</span>
|
||||
<select name="church_id" required>
|
||||
{{range .Data.Churches}}<option value="{{.ID}}" {{if and $.Data.EditingTemplate (eq .ID $.Data.EditingTemplate.ChurchID)}}selected{{end}}>{{.Name}}</option>{{end}}
|
||||
</select>
|
||||
</label>
|
||||
<label class="field"><span class="field-label">Wochentag</span>
|
||||
<select name="weekday">
|
||||
{{$selectedWeekday := 1}}{{if .Data.EditingTemplate}}{{$selectedWeekday = .Data.EditingTemplate.Weekday}}{{end}}
|
||||
{{range seq 1 7}}<option value="{{.}}" {{if eq . $selectedWeekday}}selected{{end}}>{{weekdayNumberName .}}</option>{{end}}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label class="field"><span class="field-label">Uhrzeit</span><input type="time" name="time" value="{{if .Data.EditingTemplate}}{{timeLabel .Data.EditingTemplate.TimeMinutes}}{{else}}10:00{{end}}" required></label>
|
||||
<label class="field"><span class="field-label">Titel</span><input type="text" name="title" value="{{if .Data.EditingTemplate}}{{.Data.EditingTemplate.Title}}{{end}}" placeholder="z. B. Sonntagsmesse" required></label>
|
||||
</div>
|
||||
<div class="form-row three">
|
||||
<label class="field"><span class="field-label">Lektoren</span><input type="number" name="lectors" min="0" max="6" value="{{if .Data.EditingTemplate}}{{.Data.EditingTemplate.LectorsNeeded}}{{else}}1{{end}}"></label>
|
||||
<label class="field"><span class="field-label">Kommunionhelfer</span><input type="number" name="helpers" min="0" max="6" value="{{if .Data.EditingTemplate}}{{.Data.EditingTemplate.HelpersNeeded}}{{else}}1{{end}}"></label>
|
||||
<label class="field"><span class="field-label">Sortierung</span><input type="number" name="sort_index" min="0" value="0" disabled title="Wird über Wochentag und Uhrzeit bestimmt"></label>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label class="field"><span class="field-label">Gültig ab</span><input type="date" name="valid_from" value="{{if .Data.EditingTemplate}}{{isoDate .Data.EditingTemplate.ValidFrom}}{{else}}{{.Data.Start}}{{end}}" required></label>
|
||||
<label class="field"><span class="field-label">Gültig bis <small>optional</small></span><input type="date" name="valid_to" value="{{if .Data.EditingTemplate}}{{isoDatePtr .Data.EditingTemplate.ValidTo}}{{end}}"></label>
|
||||
</div>
|
||||
<label class="field"><span class="field-label">Notizen</span><textarea name="notes" rows="2">{{if .Data.EditingTemplate}}{{.Data.EditingTemplate.Notes}}{{end}}</textarea></label>
|
||||
<label class="check"><input type="checkbox" name="active" value="1" {{if .Data.EditingTemplate}}{{if .Data.EditingTemplate.Active}}checked{{end}}{{else}}checked{{end}}><span>Vorlage ist aktiv und wird bei der Terminerzeugung berücksichtigt</span></label>
|
||||
<button class="btn btn-primary" type="submit">Vorlage speichern</button>
|
||||
</form>
|
||||
{{else}}<p class="empty-note">Nur Redakteure und Administratoren können die Gottesdienstordnung ändern.</p>{{end}}
|
||||
</section>
|
||||
|
||||
<div class="page-stack">
|
||||
<section class="card">
|
||||
<div class="card-head">
|
||||
<div><span class="eyebrow">Pausen</span><h3>Ausnahmen</h3></div>
|
||||
<span class="count-pill">{{len .Data.Exceptions}}</span>
|
||||
</div>
|
||||
{{if .Data.CanEdit}}
|
||||
<form method="post" action="/exceptions/save" class="form-stack compact">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<input type="hidden" name="id" value="{{if .Data.EditingException}}{{.Data.EditingException.ID}}{{end}}">
|
||||
<label class="field"><span class="field-label">Vorlage</span>
|
||||
<select name="template_id" required>
|
||||
{{range .Data.Templates}}<option value="{{.ID}}" {{if and $.Data.EditingException (eq .ID $.Data.EditingException.TemplateID)}}selected{{end}}>{{weekdayNumberName .Weekday}} {{timeLabel .TimeMinutes}} · {{.Title}}</option>{{end}}
|
||||
</select>
|
||||
</label>
|
||||
<div class="form-row">
|
||||
<label class="field"><span class="field-label">Datum</span><input type="date" name="date" value="{{if .Data.EditingException}}{{isoDate .Data.EditingException.Date}}{{else}}{{.Data.Start}}{{end}}" required></label>
|
||||
<label class="field"><span class="field-label">Grund</span><input type="text" name="reason" value="{{if .Data.EditingException}}{{.Data.EditingException.Reason}}{{end}}" placeholder="z. B. Ferien"></label>
|
||||
</div>
|
||||
<button class="btn btn-secondary" type="submit">Ausnahme speichern</button>
|
||||
</form>
|
||||
{{end}}
|
||||
<div class="compact-list">
|
||||
{{range .Data.Exceptions}}
|
||||
{{$template := index $.Data.TemplateByID .TemplateID}}
|
||||
<div class="compact-row">
|
||||
<div><strong>{{mediumDate .Date}}</strong><small>{{$template.Title}} · {{weekdayNumberName $template.Weekday}} {{timeLabel $template.TimeMinutes}}{{if .Reason}} · {{.Reason}}{{end}}</small></div>
|
||||
{{if $.Data.CanEdit}}
|
||||
<div class="row-actions">
|
||||
<a class="icon-button" href="/services?edit_exception={{.ID}}" title="Ausnahme bearbeiten">{{icon "settings"}}</a>
|
||||
<form method="post" action="/exceptions/delete" data-confirm="Ausnahme löschen?">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
<input type="hidden" name="id" value="{{.ID}}">
|
||||
<button class="icon-button danger" type="submit" title="Ausnahme löschen">{{icon "trash"}}</button>
|
||||
</form>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
{{else}}
|
||||
<p class="empty-note">Keine Ausnahmen hinterlegt.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-head">
|
||||
<div><span class="eyebrow">Außer der Reihe</span><h3>Sondergottesdienste</h3></div>
|
||||
<span class="count-pill">{{len .Data.Specials}}</span>
|
||||
</div>
|
||||
{{if .Data.CanEdit}}
|
||||
<form method="post" action="/services/new" class="form-stack compact">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<input type="hidden" name="id" value="{{if .Data.EditingSpecial}}{{.Data.EditingSpecial.ID}}{{end}}">
|
||||
<div class="form-row">
|
||||
<label class="field"><span class="field-label">Datum</span><input type="date" name="date" value="{{if .Data.EditingSpecial}}{{isoDate .Data.EditingSpecial.Date}}{{else}}{{.Data.Start}}{{end}}" required></label>
|
||||
<label class="field"><span class="field-label">Uhrzeit</span><input type="time" name="time" value="{{if .Data.EditingSpecial}}{{timeLabel .Data.EditingSpecial.TimeMinutes}}{{else}}18:00{{end}}" required></label>
|
||||
</div>
|
||||
<label class="field"><span class="field-label">Kirche</span>
|
||||
<select name="church_id">
|
||||
{{range .Data.Churches}}<option value="{{.ID}}" {{if $.Data.EditingSpecial}}{{if eq .ID $.Data.EditingSpecial.ChurchID}}selected{{end}}{{end}}>{{.Name}}</option>{{end}}
|
||||
</select>
|
||||
</label>
|
||||
<label class="field"><span class="field-label">Titel</span><input type="text" name="title" value="{{if .Data.EditingSpecial}}{{.Data.EditingSpecial.Title}}{{end}}" placeholder="z. B. Open-Air-Gottesdienst" required></label>
|
||||
<label class="field"><span class="field-label">Freitext-Ort <small>optional</small></span><input type="text" name="location" value="{{if .Data.EditingSpecial}}{{deref .Data.EditingSpecial.Location}}{{end}}" placeholder="z. B. Rheinaue, Bühne"></label>
|
||||
<div class="form-row">
|
||||
<label class="field"><span class="field-label">Lektoren</span><input type="number" name="lectors" min="0" max="6" value="{{if .Data.EditingSpecial}}{{.Data.EditingSpecial.LectorsNeeded}}{{else}}1{{end}}"></label>
|
||||
<label class="field"><span class="field-label">Kommunionhelfer</span><input type="number" name="helpers" min="0" max="6" value="{{if .Data.EditingSpecial}}{{.Data.EditingSpecial.HelpersNeeded}}{{else}}1{{end}}"></label>
|
||||
</div>
|
||||
<label class="field"><span class="field-label">Notizen</span><textarea name="notes" rows="2">{{if .Data.EditingSpecial}}{{.Data.EditingSpecial.Notes}}{{end}}</textarea></label>
|
||||
<button class="btn btn-secondary" type="submit">Sondergottesdienst speichern</button>
|
||||
</form>
|
||||
{{end}}
|
||||
<div class="compact-list">
|
||||
{{range .Data.Specials}}
|
||||
{{$church := index $.Data.ChurchByID .ChurchID}}
|
||||
<div class="compact-row">
|
||||
<div><strong>{{mediumDate .Date}} · {{timeLabel .TimeMinutes}}</strong><small>{{.Title}} · {{if .Location}}{{deref .Location}}{{else}}{{$church.Name}}{{end}}</small></div>
|
||||
<div class="row-actions">
|
||||
<a class="icon-button" href="/services/{{.ID}}" title="Details öffnen">{{icon "right"}}</a>
|
||||
{{if $.Data.CanEdit}}<a class="icon-button" href="/services?edit_special={{.ID}}" title="Sondergottesdienst bearbeiten">{{icon "settings"}}</a>{{end}}
|
||||
</div>
|
||||
</div>
|
||||
{{else}}
|
||||
<p class="empty-note">Keine Sondergottesdienste hinterlegt.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,108 @@
|
||||
{{define "content"}}
|
||||
<div class="page-stack settings-page">
|
||||
<section class="page-intro">
|
||||
<div>
|
||||
<span class="eyebrow">Konfiguration</span>
|
||||
<h2>Kalender, Planung & Datenhaltung</h2>
|
||||
<p>Passen Sie die liturgische Quelle und die Gewichtung der automatischen Planung an. Änderungen gelten für den aktiven Mandanten {{if .Tenant}}{{.Tenant.Name}}{{end}}.</p>
|
||||
</div>
|
||||
<div class="range-actions">
|
||||
<a class="btn btn-secondary btn-small" href="/liturgy">{{icon "book"}} Kalender ansehen</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<form method="post" action="/settings/save" class="page-stack">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<section class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Liturgie</span><h3>Kalenderquelle</h3></div></div>
|
||||
<div class="settings-grid">
|
||||
<div class="settings-copy">
|
||||
<h4>Online-Aktualisierung</h4>
|
||||
<p>Beim täglichen Start wird der aktuelle Jahrgang von www.eucharistiefeier.de geladen. Bei fehlender Verbindung bleibt der gespeicherte Bestand erhalten; die lokale Berechnung dient als Rückfallebene.</p>
|
||||
<label class="check"><input type="checkbox" name="auto_sync" value="1" {{if .Data.AutoSync}}checked{{end}} {{if not .Data.CanEdit}}disabled{{end}}><span>Liturgischen Kalender automatisch aktualisieren</span></label>
|
||||
</div>
|
||||
<div class="settings-fields">
|
||||
<label class="field"><span class="field-label">Bistum / Erzbistum</span>
|
||||
<select name="diocese" {{if not .Data.CanEdit}}disabled{{end}}>
|
||||
{{$diocese := .Data.Diocese}}
|
||||
{{range dioceses}}<option value="{{.Key}}" {{if eq .Key $diocese}}selected{{end}}>{{.Label}}</option>{{end}}
|
||||
</select>
|
||||
</label>
|
||||
<div class="inline-meta"><span>Letzte Aktualisierung</span><strong>{{if .Data.LastSync}}{{.Data.LastSync}}{{else}}noch nicht{{end}}</strong></div>
|
||||
<div class="source-note">{{icon "external"}} Daten von www.eucharistiefeier.de</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Planung</span><h3>Regeln und Gewichtung</h3></div></div>
|
||||
<div class="settings-grid">
|
||||
<div class="settings-copy">
|
||||
<h4>Harte und weiche Regeln</h4>
|
||||
<p>Abwesenheiten, Monatslimits und bereits besetzte Termine sind immer harte Ausschlüsse. Die folgenden Optionen steuern, wie der Planer innerhalb der verbleibenden Möglichkeiten entscheidet.</p>
|
||||
<label class="check"><input type="checkbox" name="respect_weekdays" value="1" {{if eq (index .Data.Settings "planner.respectPreferredWeekdays") "1"}}checked{{end}} {{if not .Data.CanEdit}}disabled{{end}}><span>Bevorzugte Einsatztage als Ausschluss behandeln</span></label>
|
||||
<label class="check"><input type="checkbox" name="allow_double_roles" value="1" {{if eq (index .Data.Settings "planner.allowDoubleRoles") "1"}}checked{{end}} {{if not .Data.CanEdit}}disabled{{end}}><span>Doppelrolle am selben Tag erlauben</span></label>
|
||||
<label class="check"><input type="checkbox" name="replace_existing" value="1" {{if eq (index .Data.Settings "planner.replaceExisting") "1"}}checked{{end}} {{if not .Data.CanEdit}}disabled{{end}}><span>Bei automatischer Planung bestehende, ungesperrte Einteilungen ersetzen</span></label>
|
||||
</div>
|
||||
<div class="settings-fields">
|
||||
<div class="weight-grid">
|
||||
<label class="field"><span class="field-label">Kirchenpräferenz</span><input type="number" min="0" max="30" step="0.5" name="weight_church" value="{{index .Data.Settings "planner.weightChurch"}}" {{if not .Data.CanEdit}}disabled{{end}}></label>
|
||||
<label class="field"><span class="field-label">Gottesdienstpräferenz</span><input type="number" min="0" max="30" step="0.5" name="weight_service" value="{{index .Data.Settings "planner.weightService"}}" {{if not .Data.CanEdit}}disabled{{end}}></label>
|
||||
<label class="field"><span class="field-label">Fairness</span><input type="number" min="0" max="10" step="0.1" name="weight_fairness" value="{{index .Data.Settings "planner.weightFairness"}}" {{if not .Data.CanEdit}}disabled{{end}}></label>
|
||||
<label class="field"><span class="field-label">Doppelrolle</span><input type="number" min="0" max="30" step="0.5" name="weight_dual" value="{{index .Data.Settings "planner.weightDualRole"}}" {{if not .Data.CanEdit}}disabled{{end}}></label>
|
||||
</div>
|
||||
<label class="field narrow"><span class="field-label">Maximale Einsätze pro Person und Tag</span><input type="number" min="1" max="4" name="max_per_day" value="{{index .Data.Settings "planner.maxPerDay"}}" {{if not .Data.CanEdit}}disabled{{end}}></label>
|
||||
</div>
|
||||
</div>
|
||||
{{if .Data.CanEdit}}<div class="card-foot"><button class="btn btn-primary" type="submit">Einstellungen speichern</button></div>{{end}}
|
||||
</section>
|
||||
</form>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Bestand</span><h3>Datenhaltung</h3></div></div>
|
||||
<div class="data-summary">
|
||||
<div><strong>{{index .Data.Counts "churches"}}</strong><span>Kirchen</span></div>
|
||||
<div><strong>{{index .Data.Counts "people"}}</strong><span>Personen</span></div>
|
||||
<div><strong>{{index .Data.Counts "templates"}}</strong><span>Vorlagen</span></div>
|
||||
<div><strong>{{index .Data.Counts "services"}}</strong><span>Gottesdienste</span></div>
|
||||
<div><strong>{{index .Data.Counts "assignments"}}</strong><span>Einteilungen</span></div>
|
||||
</div>
|
||||
<div class="settings-grid">
|
||||
<div class="settings-copy">
|
||||
<h4>Datenbank</h4>
|
||||
<p class="mono">{{.Data.Database}}</p>
|
||||
<p>SQLite mit WAL-Journal. Für eine Sicherung genügt eine Kopie der Datenbankdatei im laufenden Betrieb nicht; nutzen Sie die Exportfunktion oder sichern Sie die Datei bei gestopptem Dienst.</p>
|
||||
<a class="text-link" href="/exchange">{{icon "exchange"}} Daten exportieren</a>
|
||||
</div>
|
||||
<div class="settings-fields danger-zone">
|
||||
{{if .Data.DemoReset}}
|
||||
<div class="danger-block">
|
||||
<div><h4>Demo-Daten zurücksetzen</h4><p>Alle Planungsdaten dieses Mandanten werden gelöscht und mit dem Demo-Bestand neu aufgebaut.</p></div>
|
||||
<form method="post" action="/settings/demo/reset" data-confirm="Demo-Daten wirklich zurücksetzen? Alle Änderungen in diesem Mandanten gehen verloren.">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<button class="btn btn-secondary btn-small" type="submit" {{if not .Data.CanEdit}}disabled{{end}}>Demo zurücksetzen</button>
|
||||
</form>
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="danger-block">
|
||||
<div><h4>Alle Planungsdaten löschen</h4><p>Kirchen, Personen, Vorlagen, Gottesdienste, Einteilungen und mandantenbezogene Einstellungen werden entfernt. Konten und liturgische Daten bleiben bestehen.</p></div>
|
||||
<form method="post" action="/settings/data/delete" class="delete-form" data-confirm="Wirklich alle Planungsdaten dieses Mandanten löschen?">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<label class="field"><span class="field-label">Zur Bestätigung „loeschen“ eingeben</span><input type="text" name="confirm" pattern="loeschen" required {{if not .Data.CanEdit}}disabled{{end}}></label>
|
||||
<button class="btn btn-danger btn-small" type="submit" {{if not .Data.CanEdit}}disabled{{end}}>{{icon "trash"}} Endgültig löschen</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card about-card">
|
||||
<div class="about-mark">{{icon "church"}}</div>
|
||||
<div>
|
||||
<span class="eyebrow">Über LektorenPlan Web</span>
|
||||
<h3>Version {{.Version}}</h3>
|
||||
<p>Go-Server mit SQLite, mandantenfähig für Administratoren, Redakteure und Leser. Liturgische Daten von www.eucharistiefeier.de. Die macOS-App bleibt unverändert nutzbar.</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,118 @@
|
||||
{{define "content"}}
|
||||
<div class="page-stack">
|
||||
<section class="toolbar card">
|
||||
<div class="toolbar-group range-nav">
|
||||
<a class="icon-button" href="/statistics?start={{.Data.PrevStart}}&end={{.Data.PrevEnd}}" title="Vorheriger Monat">{{icon "left"}}</a>
|
||||
<form class="range-form" method="get" action="/statistics">
|
||||
<label class="field field-inline"><span>Von</span><input type="date" name="start" value="{{.Data.Start}}"></label>
|
||||
<label class="field field-inline"><span>Bis</span><input type="date" name="end" value="{{.Data.End}}"></label>
|
||||
<button class="btn btn-secondary btn-small" type="submit">Auswerten</button>
|
||||
</form>
|
||||
<a class="icon-button" href="/statistics?start={{.Data.NextStart}}&end={{.Data.NextEnd}}" title="Nächster Monat">{{icon "right"}}</a>
|
||||
</div>
|
||||
<div class="toolbar-group">
|
||||
<a class="chip" href="/statistics?start={{.Data.MonthStart}}&end={{.Data.MonthEnd}}">Monat</a>
|
||||
<a class="chip" href="/statistics?start={{.Data.QuarterStart}}&end={{.Data.QuarterEnd}}">Quartal</a>
|
||||
<a class="chip" href="/statistics?start={{.Data.YearStart}}&end={{.Data.YearEnd}}">Jahr</a>
|
||||
<a class="chip" href="/statistics?start={{.Data.ChurchYearStart}}&end={{.Data.ChurchYearEnd}}">Kirchenjahr</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="range-banner">
|
||||
<div>
|
||||
<span class="eyebrow">Auswertung</span>
|
||||
<h2>{{rangeLong .Data.Stats.Range}}</h2>
|
||||
<p>{{dayCount .Data.Stats.Range}} Tage · {{.Data.Stats.ServiceCount}} Gottesdienste · {{.Data.Stats.ActivePeople}} aktive Personen</p>
|
||||
</div>
|
||||
<div class="range-actions">
|
||||
<a class="btn btn-ghost btn-small" href="/plan?start={{.Data.Start}}&end={{.Data.End}}">{{icon "calendar"}} Zum Plan</a>
|
||||
<a class="btn btn-secondary btn-small" href="/pdf?variant=plan&start={{.Data.Start}}&end={{.Data.End}}" target="_blank" rel="noopener">{{icon "printer"}} PDF öffnen</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="stat-strip">
|
||||
<article class="mini-stat"><span class="mini-stat-label">Besetzungsquote</span><strong>{{percent .Data.Stats.CoverageRate}}</strong><small>{{.Data.Stats.AssignmentCount}} von {{.Data.Stats.RequiredSlots}} Diensten</small></article>
|
||||
<article class="mini-stat {{if gt .Data.Stats.OpenSlots 0}}warn{{end}}"><span class="mini-stat-label">Offene Dienste</span><strong>{{.Data.Stats.OpenSlots}}</strong><small>über alle Kirchen</small></article>
|
||||
<article class="mini-stat"><span class="mini-stat-label">Durchschnitt</span><strong>{{.Data.Average}}</strong><small>Einsätze je aktiver Person</small></article>
|
||||
<article class="mini-stat"><span class="mini-stat-label">Präferenztreffer</span><strong>{{preferencePct .Data.Stats}}</strong><small>{{.Data.Stats.PreferenceHits}} von {{.Data.Stats.PreferenceEligible}} bewertbaren Einsätzen</small></article>
|
||||
<article class="mini-stat"><span class="mini-stat-label">Abwesenheitstage</span><strong>{{.Data.Stats.AbsenceDays}}</strong><small>im gewählten Zeitraum</small></article>
|
||||
</section>
|
||||
|
||||
<div class="stats-grid">
|
||||
<section class="card span-2">
|
||||
<div class="card-head"><div><span class="eyebrow">Verlauf</span><h3>Einsätze nach Monat</h3></div><span class="count-pill">{{len .Data.Months}} Monate</span></div>
|
||||
<div class="month-chart">
|
||||
{{range .Data.Months}}
|
||||
<div class="month-bar-wrap" title="{{.Label}}: {{.Count}} Einsätze">
|
||||
<span class="month-count">{{.Count}}</span>
|
||||
<div class="month-bar-track"><div class="month-bar" style="height:{{if $.Data.MaxMonth}}{{percentage (ratio .Count $.Data.MaxMonth)}}{{else}}0%{{end}}"></div></div>
|
||||
<span class="month-label">{{.Label}}</span>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Fairness</span><h3>Verteilung</h3></div></div>
|
||||
<div class="fairness-box">
|
||||
<div><span>Minimum</span><strong>{{.Data.MinAssignments}}</strong></div>
|
||||
<div><span>Maximum</span><strong>{{.Data.MaxAssignments}}</strong></div>
|
||||
<div><span>Spannweite</span><strong>{{.Data.Span}}</strong></div>
|
||||
<div><span>Durchschnitt</span><strong>{{.Data.Average}}</strong></div>
|
||||
</div>
|
||||
<p class="empty-note">Die Spannweite zeigt, wie gleichmäßig die Einsätze auf aktive Personen verteilt sind. Präferenzen und Monatslimits können bewusst Abweichungen erzeugen.</p>
|
||||
</section>
|
||||
|
||||
<section class="card span-2">
|
||||
<div class="card-head"><div><span class="eyebrow">Einsatzhäufigkeit</span><h3>Personen</h3></div><span class="count-pill">{{len .Data.Stats.PersonStats}}</span></div>
|
||||
<div class="table-scroll">
|
||||
<table class="data-table compact-table">
|
||||
<thead><tr><th>Person</th><th>Gesamt</th><th>Lektor</th><th>Helfer</th><th>Sonntage</th><th>Präferenz</th><th>Verteilung</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Data.Stats.PersonStats}}
|
||||
<tr class="{{if not .Person.Active}}muted-row{{end}}">
|
||||
<td><span class="person-inline"><span class="avatar tiny">{{.Person.Initials}}</span><span><strong>{{.Person.FullName}}</strong><small>{{.Person.RoleLabel}}</small></span></span></td>
|
||||
<td><strong>{{.Total}}</strong></td>
|
||||
<td>{{.Lectors}}</td>
|
||||
<td>{{.Helpers}}</td>
|
||||
<td>{{.SundayCount}}</td>
|
||||
<td>{{percent .PreferenceRate}}</td>
|
||||
<td class="bar-cell"><div class="inline-bar"><span style="width:{{percentage (ratio .Total $.Data.MaxAssignments)}}"></span></div></td>
|
||||
</tr>
|
||||
{{else}}
|
||||
<tr><td colspan="7"><span class="empty-note">Keine Personen vorhanden.</span></td></tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card span-2">
|
||||
<div class="card-head"><div><span class="eyebrow">Orte</span><h3>Verteilung auf Kirchen</h3></div></div>
|
||||
<div class="church-stat-list">
|
||||
{{range .Data.Stats.ChurchStats}}
|
||||
<div class="church-stat-row" title="{{.Church.Name}}">
|
||||
<span class="church-stat-icon">{{churchGlyph .Church.Symbol .Church.ColorHex}}</span>
|
||||
<div class="church-stat-main">
|
||||
<div class="church-stat-head"><strong>{{.Church.Name}}</strong><span>{{plural .Assignments "Einsatz" "Einsätze"}} · {{plural .Services "Gottesdienst" "Gottesdienste"}}</span></div>
|
||||
<div class="inline-bar tall"><span style="width:{{percentage (ratio .Assignments $.Data.MaxChurch)}};background:{{.Church.ColorHex}}"></span></div>
|
||||
</div>
|
||||
<div class="church-stat-meta"><strong>{{.Assignments}}</strong><span>{{if gt .OpenSlots 0}}{{.OpenSlots}} offen{{else}}vollständig{{end}}</span></div>
|
||||
</div>
|
||||
{{else}}
|
||||
<p class="empty-note">Keine Kirchen vorhanden.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Sonntage</span><h3>Sonntagsdienste</h3></div></div>
|
||||
<div class="big-number-block">
|
||||
<strong>{{.Data.Stats.SundayFilled}}</strong>
|
||||
<span>besetzte Dienste</span>
|
||||
<small>bei {{.Data.Stats.SundayServiceCount}} Sonntagsgottesdiensten</small>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,92 @@
|
||||
{{define "content"}}
|
||||
<div class="page-stack">
|
||||
<section class="page-intro">
|
||||
<div>
|
||||
<span class="eyebrow">Menschen & Verfügbarkeit</span>
|
||||
<h2>Das Planungsteam</h2>
|
||||
<p>Rollen, Kontaktdaten, bevorzugte Kirchen und Gottesdienste, Monatslimits und Abwesenheiten bilden die Grundlage für faire und nachvollziehbare Einteilungen.</p>
|
||||
</div>
|
||||
<div class="intro-actions">
|
||||
<a class="btn btn-primary" href="/team/person/new">{{icon "plus"}} Neue Person</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="stat-strip four">
|
||||
<article class="mini-stat"><span class="mini-stat-label">Personen</span><strong>{{len .Data.People}}</strong><small>{{.Data.ActiveCount}} aktiv</small></article>
|
||||
<article class="mini-stat"><span class="mini-stat-label">Lektoren</span><strong>{{.Data.LectorCount}}</strong><small>mit Lektoratsdienst</small></article>
|
||||
<article class="mini-stat"><span class="mini-stat-label">Kommunionhelfer</span><strong>{{.Data.HelperCount}}</strong><small>mit Helferdienst</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>
|
||||
|
||||
<div class="team-layout">
|
||||
<section class="card">
|
||||
<div class="card-head">
|
||||
<div><span class="eyebrow">Übersicht</span><h3>Team im Jahr {{.Data.Year}}</h3></div>
|
||||
<label class="search-field">
|
||||
{{icon "users"}}
|
||||
<input type="search" placeholder="Person suchen …" data-person-search>
|
||||
</label>
|
||||
</div>
|
||||
<div class="team-grid" data-person-grid>
|
||||
{{range .Data.People}}
|
||||
{{$stat := index $.Data.Stats .ID}}
|
||||
{{$absences := index $.Data.AbsencesByPerson .ID}}
|
||||
<article class="person-card {{if not .Active}}inactive{{end}}" data-person-name="{{lower .FullName}}">
|
||||
<div class="person-card-head">
|
||||
<span class="avatar">{{.Initials}}</span>
|
||||
<div class="person-card-name">
|
||||
<h4>{{.FullName}}</h4>
|
||||
<span>{{.RoleLabel}}{{if not .Active}} · inaktiv{{end}}</span>
|
||||
</div>
|
||||
<a class="icon-button" href="/team/person/{{.ID}}" title="Person bearbeiten">{{icon "right"}}</a>
|
||||
</div>
|
||||
<div class="person-stats">
|
||||
<div><strong>{{$stat.Total}}</strong><span>Einsätze</span></div>
|
||||
<div><strong>{{$stat.Lectors}}</strong><span>Lektor</span></div>
|
||||
<div><strong>{{$stat.Helpers}}</strong><span>Helfer</span></div>
|
||||
<div><strong>{{len $absences}}</strong><span>Abwesen.</span></div>
|
||||
</div>
|
||||
<div class="person-details">
|
||||
{{if .Email}}<a href="mailto:{{.Email}}">{{.Email}}</a>{{end}}
|
||||
{{if .Phone}}<span>{{.Phone}}</span>{{end}}
|
||||
{{if or .Email .Phone}}{{else}}<span class="muted">Keine Kontaktdaten</span>{{end}}
|
||||
</div>
|
||||
{{if .HasPreference}}
|
||||
<div class="preference-tags">
|
||||
{{range .PreferredChurchIDs}}
|
||||
{{$church := index $.Data.ChurchByID .}}
|
||||
{{if $church}}<span class="badge badge-neutral">{{$church.ShortName}}</span>{{end}}
|
||||
{{end}}
|
||||
{{range .PreferredWeekdays}}<span class="badge badge-gold">{{weekdayNumberName .}}</span>{{end}}
|
||||
{{range .PreferredServiceTitles}}<span class="badge badge-green">{{.}}</span>{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="person-foot">
|
||||
<span>Limit: {{if gt .MaxPerMonth 0}}{{.MaxPerMonth}} / Monat{{else}}kein Limit{{end}}</span>
|
||||
{{if $stat.LastAssignment}}<span>zuletzt {{mediumDate (derefTime $stat.LastAssignment)}}</span>{{end}}
|
||||
</div>
|
||||
</article>
|
||||
{{else}}
|
||||
<p class="empty-note">Noch keine Personen angelegt. Legen Sie die erste Person über „Neue Person“ an.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
<p class="empty-note search-empty" data-search-empty hidden>Keine Person passt zur Suche.</p>
|
||||
</section>
|
||||
|
||||
<aside class="card">
|
||||
<div class="card-head"><div><span class="eyebrow">Kalender</span><h3>Abwesenheiten</h3></div><span class="count-pill">{{len .Data.Absences}}</span></div>
|
||||
<div class="absence-list">
|
||||
{{range .Data.Absences}}
|
||||
{{$person := index $.Data.PeopleByID .PersonID}}
|
||||
<a class="absence-row" href="/team/person/{{.PersonID}}">
|
||||
<span class="absence-dates"><strong>{{shortDate .Start}}</strong><small>bis {{shortDate .End}}</small></span>
|
||||
<span class="absence-person"><strong>{{$person.FullName}}</strong><small>{{if .Reason}}{{.Reason}}{{else}}ohne Angabe{{end}}</small></span>
|
||||
</a>
|
||||
{{else}}
|
||||
<p class="empty-note">Keine Abwesenheiten eingetragen.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
Reference in new issue
Block a user