Files
LektorenPlan/web/store/services.go
T

498 lines
18 KiB
Go

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()
}
// LatestServiceDate returns the last date with planning data, if any.
func (s *Store) LatestServiceDate(ctx context.Context, tenantID string) (*time.Time, error) {
var value sql.NullString
err := s.db.QueryRowContext(ctx,
"SELECT MAX(date) FROM services WHERE tenant_id=?", tenantID).Scan(&value)
if err != nil {
return nil, err
}
if !value.Valid || value.String == "" {
return nil, nil
}
date, ok := domain.DateFromKey(value.String)
if !ok {
return nil, nil
}
return &date, nil
}
// 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.beyond_preferences,
a.note, a.created_at
FROM assignments a JOIN services s ON s.tenant_id=a.tenant_id AND s.id=a.service_id
WHERE a.tenant_id=? AND s.date >= ? AND s.date <= ?
ORDER BY s.date, s.time_minutes`, tenantID, domain.Key(r.Start), domain.Key(r.End))
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, beyond_preferences, note, created_at FROM assignments " +
"WHERE tenant_id=? AND service_id IN (" + placeholders + ")"
rows, err := s.db.QueryContext(ctx, query, args...)
if err != nil {
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, beyond_preferences, note, created_at
FROM assignments WHERE tenant_id=? AND person_id=? ORDER BY created_at`, tenantID, personID)
if err != nil {
return nil, err
}
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, beyond int
if err := rows.Scan(&assignment.ID, &assignment.ServiceID, &assignment.PersonID,
&role, &locked, &beyond, &assignment.Note, &created); err != nil {
return nil, err
}
assignment.Role = domain.Role(role)
assignment.Locked = locked != 0
assignment.BeyondPreferences = beyond != 0
assignment.CreatedAt = parseTime(created)
out = append(out, assignment)
}
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,
beyond_preferences, note, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(tenant_id, id) DO UPDATE SET
service_id=excluded.service_id, person_id=excluded.person_id,
role=excluded.role, locked=excluded.locked,
beyond_preferences=excluded.beyond_preferences, note=excluded.note`,
tenantID, assignment.ID, assignment.ServiceID, assignment.PersonID,
string(assignment.Role), boolInt(assignment.Locked), boolInt(assignment.BeyondPreferences),
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,
beyond_preferences, note, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(tenant_id, id) DO UPDATE SET
service_id=excluded.service_id, person_id=excluded.person_id,
role=excluded.role, locked=excluded.locked,
beyond_preferences=excluded.beyond_preferences, note=excluded.note`,
tenantID, assignment.ID, assignment.ServiceID, assignment.PersonID,
string(assignment.Role), boolInt(assignment.Locked),
boolInt(assignment.BeyondPreferences), 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))
}