Web Variante in Go V0.1

This commit is contained in:
concierge committed 2026-11-12 20:00:33 +01:00
1 parent f9e3e94629
commit 692b9b6ef8
60 files changed
+13140

No files matched your search

+424
View File
@@ -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
View File
@@ -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")
}
+522
View File
@@ -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
}
+239
View File
@@ -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
}
+149
View File
@@ -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})
}
+496
View File
@@ -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
}
+472
View File
@@ -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 = &copy
}
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))
}
+124
View File
@@ -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
}
+122
View File
@@ -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")
}
}
+251
View File
@@ -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)
}