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 }