Gastansicht, Verbesserungen bei Planung
This commit is contained in:
1 parent
b3afa3ef32
commit
c08d43e7dd
38 files changed
+3845
-219
No files matched your search
@@ -0,0 +1,325 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
// ReaderContact is one reader account together with the person it represents.
|
||||
// The e-mail address is only filled when the requesting session holds the data
|
||||
// key for that person, i.e. after the owner shared it.
|
||||
type ReaderContact struct {
|
||||
UserID string
|
||||
Person domain.Person
|
||||
}
|
||||
|
||||
// ReaderDirectory lists the active reader accounts linked to a tenant. The
|
||||
// contacts are hydrated with the current request's keyring, so addresses that
|
||||
// were not shared remain empty and locked.
|
||||
func (s *Store) ReaderDirectory(ctx context.Context, tenantID string) ([]ReaderContact, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT u.id, u.linked_person_id
|
||||
FROM users u
|
||||
JOIN people p ON p.tenant_id=u.linked_tenant_id AND p.id=u.linked_person_id
|
||||
WHERE u.active=1 AND u.role='reader' AND u.linked_tenant_id=?
|
||||
ORDER BY p.last_name COLLATE NOCASE, p.first_name COLLATE NOCASE, u.id`, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
type readerRow struct {
|
||||
userID string
|
||||
personID string
|
||||
}
|
||||
var ids []readerRow
|
||||
for rows.Next() {
|
||||
var row readerRow
|
||||
if err := rows.Scan(&row.userID, &row.personID); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, row)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
out := make([]ReaderContact, 0, len(ids))
|
||||
for _, row := range ids {
|
||||
person, err := s.Person(ctx, tenantID, row.personID)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, ReaderContact{UserID: row.userID, Person: *person})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ReaderForPerson returns the active reader account linked to a person.
|
||||
func (s *Store) ReaderForPerson(ctx context.Context, tenantID, personID string) (string, bool) {
|
||||
var userID string
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT id FROM users
|
||||
WHERE active=1 AND role='reader' AND linked_tenant_id=? AND linked_person_id=?
|
||||
ORDER BY id LIMIT 1`, tenantID, personID).Scan(&userID)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
return userID, true
|
||||
}
|
||||
|
||||
// ContactSharesForOwner lists the reader accounts that may see the owner's
|
||||
// e-mail address.
|
||||
func (s *Store) ContactSharesForOwner(ctx context.Context, tenantID, ownerPersonID string) (map[string]bool, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT viewer_user_id FROM contact_shares
|
||||
WHERE tenant_id=? AND owner_person_id=?`, tenantID, ownerPersonID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[string]bool{}
|
||||
for rows.Next() {
|
||||
var userID string
|
||||
if err := rows.Scan(&userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[userID] = true
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ContactSharesForViewer lists the persons whose e-mail addresses were shared
|
||||
// with one reader account.
|
||||
func (s *Store) ContactSharesForViewer(ctx context.Context, tenantID, viewerUserID string) ([]string, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT owner_person_id FROM contact_shares
|
||||
WHERE tenant_id=? AND viewer_user_id=? ORDER BY owner_person_id`, tenantID, viewerUserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []string
|
||||
for rows.Next() {
|
||||
var personID string
|
||||
if err := rows.Scan(&personID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, personID)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) contactShareViewers(ctx context.Context, tenantID, ownerPersonID string) ([]string, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT viewer_user_id FROM contact_shares
|
||||
WHERE tenant_id=? AND owner_person_id=? ORDER BY viewer_user_id`, tenantID, ownerPersonID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []string
|
||||
for rows.Next() {
|
||||
var userID string
|
||||
if err := rows.Scan(&userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, userID)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ContactShareExists reports whether ownerPersonID shared the address with the
|
||||
// given account.
|
||||
func (s *Store) ContactShareExists(ctx context.Context, tenantID, ownerPersonID, viewerUserID string) bool {
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM contact_shares
|
||||
WHERE tenant_id=? AND owner_person_id=? AND viewer_user_id=?`,
|
||||
tenantID, ownerPersonID, viewerUserID).Scan(&count)
|
||||
return err == nil && count > 0
|
||||
}
|
||||
|
||||
// SetContactShares replaces the viewer list of one owner. Newly selected
|
||||
// readers receive the encrypted person scope; removed readers lose their
|
||||
// wrapper immediately. The returned lists contain the actual changes.
|
||||
func (s *Store) SetContactShares(ctx context.Context, keyring *Keyring, tenantID, ownerUserID, ownerPersonID string, viewerUserIDs []string) (added, removed []string, err error) {
|
||||
// Refuse before touching the consent table when the session cannot grant
|
||||
// the encrypted scope; otherwise a failed save would leave an announced
|
||||
// share without a usable key.
|
||||
if s.SecretIsInitialized(ctx, tenantID) && keyring == nil {
|
||||
return nil, nil, errKeyLocked
|
||||
}
|
||||
current, err := s.ContactSharesForOwner(ctx, tenantID, ownerPersonID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
wanted := map[string]bool{}
|
||||
for _, raw := range viewerUserIDs {
|
||||
userID := strings.TrimSpace(raw)
|
||||
if userID == "" || userID == ownerUserID || wanted[userID] {
|
||||
continue
|
||||
}
|
||||
var count int
|
||||
if err := s.db.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM users
|
||||
WHERE id=? AND active=1 AND role='reader' AND linked_tenant_id=?
|
||||
AND linked_person_id<>'' AND linked_person_id<>?`,
|
||||
userID, tenantID, ownerPersonID).Scan(&count); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if count == 0 {
|
||||
return nil, nil, errors.New("Ein ausgewähltes Konto ist kein aktiver Leserzugang dieses Mandanten")
|
||||
}
|
||||
wanted[userID] = true
|
||||
}
|
||||
for userID := range current {
|
||||
if !wanted[userID] {
|
||||
removed = append(removed, userID)
|
||||
}
|
||||
}
|
||||
for userID := range wanted {
|
||||
if !current[userID] {
|
||||
added = append(added, userID)
|
||||
}
|
||||
}
|
||||
sort.Strings(added)
|
||||
sort.Strings(removed)
|
||||
|
||||
if err := s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
for _, userID := range removed {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM contact_shares
|
||||
WHERE tenant_id=? AND owner_person_id=? AND viewer_user_id=?`,
|
||||
tenantID, ownerPersonID, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, userID := range added {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO contact_shares(tenant_id, owner_person_id, viewer_user_id, granted_at)
|
||||
VALUES(?, ?, ?, ?)
|
||||
ON CONFLICT DO NOTHING`,
|
||||
tenantID, ownerPersonID, userID, time.Now().UTC().Format(time.RFC3339)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// A pending swap is only possible while both sides still release
|
||||
// their addresses. Revoking a share cancels affected requests so the
|
||||
// plan never keeps a swap-requested mark for an impossible swap.
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE swap_requests SET status=?, responded_at=?
|
||||
WHERE tenant_id=? AND status=? AND NOT (
|
||||
EXISTS (
|
||||
SELECT 1 FROM contact_shares a
|
||||
WHERE a.tenant_id=swap_requests.tenant_id
|
||||
AND a.owner_person_id=swap_requests.target_person_id
|
||||
AND a.viewer_user_id=swap_requests.requester_user_id
|
||||
) AND EXISTS (
|
||||
SELECT 1 FROM contact_shares b
|
||||
WHERE b.tenant_id=swap_requests.tenant_id
|
||||
AND b.owner_person_id=swap_requests.requester_person_id
|
||||
AND b.viewer_user_id=swap_requests.target_user_id
|
||||
)
|
||||
)`, SwapCancelled, time.Now().UTC().Format(time.RFC3339), tenantID, SwapPending); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if s.SecretIsInitialized(ctx, tenantID) {
|
||||
scope := KeyScope{Type: ScopePerson, TenantID: tenantID, ID: ownerPersonID}
|
||||
if len(added) > 0 {
|
||||
dek, err := s.ensureScope(ctx, keyring, scope)
|
||||
if err != nil {
|
||||
return added, removed, err
|
||||
}
|
||||
if err := s.grantScopeDEK(ctx, keyring, scope, dek, added); err != nil {
|
||||
return added, removed, err
|
||||
}
|
||||
}
|
||||
for _, userID := range removed {
|
||||
if _, err := s.db.ExecContext(ctx, `
|
||||
DELETE FROM key_wrappers
|
||||
WHERE scope_type=? AND tenant_id=? AND scope_id=? AND user_id=?`,
|
||||
ScopePerson, tenantID, ownerPersonID, userID); err != nil {
|
||||
return added, removed, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return added, removed, nil
|
||||
}
|
||||
|
||||
// readerRosterHash fingerprints the current reader accounts of a tenant. The
|
||||
// owner's own account is excluded.
|
||||
func (s *Store) readerRosterHash(ctx context.Context, tenantID, ownerUserID string) (string, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, linked_person_id FROM users
|
||||
WHERE active=1 AND role='reader' AND linked_tenant_id=? AND id<>?
|
||||
ORDER BY id`, tenantID, ownerUserID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer rows.Close()
|
||||
hash := sha256.New()
|
||||
for rows.Next() {
|
||||
var userID, personID string
|
||||
if err := rows.Scan(&userID, &personID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
hash.Write([]byte(userID + "|" + personID + "\n"))
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(hash.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// ContactRosterChanged reports whether the reader directory changed since the
|
||||
// owner last reviewed the sharing list. known is false before the first save.
|
||||
func (s *Store) ContactRosterChanged(ctx context.Context, tenantID, ownerUserID, ownerPersonID string) (changed, known bool, err error) {
|
||||
current, err := s.readerRosterHash(ctx, tenantID, ownerUserID)
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
var stored string
|
||||
err = s.db.QueryRowContext(ctx, `
|
||||
SELECT roster_hash FROM contact_reviews
|
||||
WHERE tenant_id=? AND owner_person_id=?`, tenantID, ownerPersonID).Scan(&stored)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return false, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
return stored != current, true, nil
|
||||
}
|
||||
|
||||
// MarkContactRosterReviewed stores the current reader directory fingerprint.
|
||||
func (s *Store) MarkContactRosterReviewed(ctx context.Context, tenantID, ownerUserID, ownerPersonID string) error {
|
||||
hash, err := s.readerRosterHash(ctx, tenantID, ownerUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, `
|
||||
INSERT INTO contact_reviews(tenant_id, owner_person_id, roster_hash, reviewed_at)
|
||||
VALUES(?, ?, ?, ?)
|
||||
ON CONFLICT(tenant_id, owner_person_id) DO UPDATE SET
|
||||
roster_hash=excluded.roster_hash, reviewed_at=excluded.reviewed_at`,
|
||||
tenantID, ownerPersonID, hash, time.Now().UTC().Format(time.RFC3339))
|
||||
return err
|
||||
}
|
||||
+89
-8
@@ -135,14 +135,17 @@ CREATE TABLE IF NOT EXISTS churches (
|
||||
CREATE TABLE IF NOT EXISTS people (
|
||||
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
id TEXT NOT NULL,
|
||||
short_code TEXT NOT NULL DEFAULT '',
|
||||
first_name TEXT NOT NULL,
|
||||
last_name TEXT NOT NULL,
|
||||
roles TEXT NOT NULL,
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
preferred_church_ids TEXT NOT NULL DEFAULT '[]',
|
||||
preferred_weekdays TEXT NOT NULL DEFAULT '[]',
|
||||
preferred_weekday_periods TEXT NOT NULL DEFAULT '[]',
|
||||
preferred_service_titles TEXT NOT NULL DEFAULT '[]',
|
||||
max_per_month INTEGER NOT NULL DEFAULT 6,
|
||||
allow_beyond_preferences INTEGER NOT NULL DEFAULT 0,
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (tenant_id, id)
|
||||
@@ -215,6 +218,7 @@ CREATE TABLE IF NOT EXISTS assignments (
|
||||
person_id TEXT NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
locked INTEGER NOT NULL DEFAULT 0,
|
||||
beyond_preferences INTEGER NOT NULL DEFAULT 0,
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
PRIMARY KEY (tenant_id, id),
|
||||
@@ -315,6 +319,41 @@ CREATE TABLE IF NOT EXISTS secret_state (
|
||||
tenant_id TEXT PRIMARY KEY REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
initialized_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS contact_shares (
|
||||
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
owner_person_id TEXT NOT NULL,
|
||||
viewer_user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
granted_at TEXT NOT NULL,
|
||||
PRIMARY KEY (tenant_id, owner_person_id, viewer_user_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_contact_shares_viewer ON contact_shares(viewer_user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS contact_reviews (
|
||||
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
owner_person_id TEXT NOT NULL,
|
||||
roster_hash TEXT NOT NULL,
|
||||
reviewed_at TEXT NOT NULL,
|
||||
PRIMARY KEY (tenant_id, owner_person_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS swap_requests (
|
||||
id TEXT PRIMARY KEY,
|
||||
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
requester_user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
requester_person_id TEXT NOT NULL,
|
||||
target_user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
target_person_id TEXT NOT NULL,
|
||||
offered_assignment_id TEXT NOT NULL,
|
||||
wanted_assignment_id TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
created_at TEXT NOT NULL,
|
||||
responded_at TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_swap_requests_tenant ON swap_requests(tenant_id, status);
|
||||
CREATE INDEX IF NOT EXISTS idx_swap_requests_requester ON swap_requests(requester_user_id, status);
|
||||
CREATE INDEX IF NOT EXISTS idx_swap_requests_target ON swap_requests(target_user_id, status);
|
||||
`
|
||||
|
||||
func (s *Store) migrate(ctx context.Context) error {
|
||||
@@ -344,8 +383,41 @@ func (s *Store) migrate(ctx context.Context) error {
|
||||
return fmt.Errorf("add users.%s: %w", column.name, err)
|
||||
}
|
||||
}
|
||||
// People gained a guest label, weekday time periods and permission to be
|
||||
// planned beyond their preferences. Assignments record when that happened.
|
||||
peopleColumns := []struct {
|
||||
name string
|
||||
definition string
|
||||
}{
|
||||
{"short_code", "TEXT NOT NULL DEFAULT ''"},
|
||||
{"preferred_weekday_periods", "TEXT NOT NULL DEFAULT '[]'"},
|
||||
{"allow_beyond_preferences", "INTEGER NOT NULL DEFAULT 0"},
|
||||
}
|
||||
for _, column := range peopleColumns {
|
||||
exists, err := s.hasColumn(ctx, "people", column.name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("inspect people table: %w", err)
|
||||
}
|
||||
if exists {
|
||||
continue
|
||||
}
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
"ALTER TABLE people ADD COLUMN "+column.name+" "+column.definition); err != nil {
|
||||
return fmt.Errorf("add people.%s: %w", column.name, err)
|
||||
}
|
||||
}
|
||||
hasBeyond, err := s.hasColumn(ctx, "assignments", "beyond_preferences")
|
||||
if err != nil {
|
||||
return fmt.Errorf("inspect assignments table: %w", err)
|
||||
}
|
||||
if !hasBeyond {
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
"ALTER TABLE assignments ADD COLUMN beyond_preferences INTEGER NOT NULL DEFAULT 0"); err != nil {
|
||||
return fmt.Errorf("add assignments.beyond_preferences: %w", err)
|
||||
}
|
||||
}
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
"INSERT INTO schema_meta(key, value) VALUES('schemaVersion', '5') "+
|
||||
"INSERT INTO schema_meta(key, value) VALUES('schemaVersion', '7') "+
|
||||
"ON CONFLICT(key) DO UPDATE SET value=excluded.value"); err != nil {
|
||||
return fmt.Errorf("record schema version: %w", err)
|
||||
}
|
||||
@@ -365,7 +437,8 @@ func (s *Store) migrate(ctx context.Context) error {
|
||||
}
|
||||
}
|
||||
// Editors and linked readers hold key material; administrators never do.
|
||||
// Readers may only keep the scope of their linked person.
|
||||
// Readers keep their own person scope plus every scope that another reader
|
||||
// has explicitly shared with them.
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
"DELETE FROM key_wrappers WHERE user_id IN (SELECT id FROM users WHERE role='admin')"); err != nil {
|
||||
return fmt.Errorf("prune administrator key wrappers: %w", err)
|
||||
@@ -376,15 +449,23 @@ func (s *Store) migrate(ctx context.Context) error {
|
||||
}
|
||||
if _, err := s.db.ExecContext(ctx, `
|
||||
DELETE FROM key_wrappers WHERE user_id IN (
|
||||
SELECT u.id FROM users u WHERE u.role='reader' AND (
|
||||
u.linked_tenant_id='' OR u.linked_person_id='' OR NOT (
|
||||
key_wrappers.scope_type='person'
|
||||
AND key_wrappers.tenant_id=u.linked_tenant_id
|
||||
AND key_wrappers.scope_id=u.linked_person_id
|
||||
SELECT id FROM users WHERE role='reader'
|
||||
) AND NOT EXISTS (
|
||||
SELECT 1 FROM users u
|
||||
WHERE u.id=key_wrappers.user_id AND u.role='reader' AND u.active=1
|
||||
AND key_wrappers.scope_type='person'
|
||||
AND key_wrappers.tenant_id=u.linked_tenant_id
|
||||
AND (
|
||||
key_wrappers.scope_id=u.linked_person_id
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM contact_shares cs
|
||||
WHERE cs.tenant_id=key_wrappers.tenant_id
|
||||
AND cs.owner_person_id=key_wrappers.scope_id
|
||||
AND cs.viewer_user_id=u.id
|
||||
)
|
||||
)
|
||||
)`); err != nil {
|
||||
return fmt.Errorf("prune unlinked reader key wrappers: %w", err)
|
||||
return fmt.Errorf("prune reader key wrappers: %w", err)
|
||||
}
|
||||
// Dispatch logs used to contain the full recipient address. Remove that
|
||||
// plaintext now that addresses are stored encrypted.
|
||||
|
||||
+35
-10
@@ -14,8 +14,8 @@ import (
|
||||
|
||||
// KeyScope identifies one encrypted data scope. Tenant scopes hold the SMTP
|
||||
// credentials, person scopes hold e-mail addresses. Editors hold the person
|
||||
// scopes of their tenants; a reader only holds the scope of the person linked
|
||||
// to their account.
|
||||
// scopes of their tenants; a reader holds the scope of the person linked to
|
||||
// their account and the scopes that other readers have shared with them.
|
||||
type KeyScope struct {
|
||||
Type string
|
||||
TenantID string
|
||||
@@ -62,6 +62,14 @@ func (k *Keyring) remember(scope KeyScope, dek []byte) {
|
||||
k.deks[scope.String()] = append([]byte{}, dek...)
|
||||
}
|
||||
|
||||
// Forget drops a cached data key. It is used when a reader revokes access to
|
||||
// their e-mail address so an already open session loses the key immediately.
|
||||
func (k *Keyring) Forget(scope KeyScope) {
|
||||
k.mu.Lock()
|
||||
defer k.mu.Unlock()
|
||||
delete(k.deks, scope.String())
|
||||
}
|
||||
|
||||
type keyringContextKey struct{}
|
||||
|
||||
// WithKeyring attaches an unlocked keyring to a request context.
|
||||
@@ -407,6 +415,12 @@ func (s *Store) ReconcileTenant(ctx context.Context, keyring *Keyring, tenantID
|
||||
if linked := s.linkedReaderForPerson(ctx, tenantID, personID); linked != "" {
|
||||
recipients = append(recipients, linked)
|
||||
}
|
||||
shared, err := s.contactShareViewers(ctx, tenantID, personID)
|
||||
if err != nil {
|
||||
rememberError(err)
|
||||
} else {
|
||||
recipients = append(recipients, shared...)
|
||||
}
|
||||
if err := s.grantScope(ctx, keyring, scope, recipients); err != nil {
|
||||
rememberError(err)
|
||||
}
|
||||
@@ -663,9 +677,10 @@ func (s *Store) SetSecret(ctx context.Context, tenantID, scopeType, scopeID, key
|
||||
}
|
||||
|
||||
// EnsurePersonScope creates the person scope if needed and grants it to all
|
||||
// active editors plus the linked reader. It works with an editor keyring and
|
||||
// with a reader keyring that already holds the person's data key; the latter
|
||||
// lets a reader refresh editor access after a new editor was created.
|
||||
// active editors, the linked reader and every reader the owner shared their
|
||||
// address with. It works with an editor keyring and with a reader keyring that
|
||||
// already holds the person's data key; the latter lets a reader refresh access
|
||||
// after a new editor was created.
|
||||
func (s *Store) EnsurePersonScope(ctx context.Context, keyring *Keyring, tenantID, personID string) error {
|
||||
if keyring == nil || !s.SecretIsInitialized(ctx, tenantID) {
|
||||
return nil
|
||||
@@ -681,6 +696,11 @@ func (s *Store) EnsurePersonScope(ctx context.Context, keyring *Keyring, tenantI
|
||||
if linked := s.linkedReaderForPerson(ctx, tenantID, personID); linked != "" {
|
||||
recipients = append(recipients, linked)
|
||||
}
|
||||
shared, err := s.contactShareViewers(ctx, tenantID, personID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
recipients = append(recipients, shared...)
|
||||
return s.grantScope(ctx, keyring, scope, recipients)
|
||||
}
|
||||
|
||||
@@ -785,9 +805,9 @@ func (s *Store) DeleteUserKeys(ctx context.Context, userID string) error {
|
||||
}
|
||||
|
||||
// PruneUserWrappers enforces the key access policy. Editors keep the scopes of
|
||||
// their tenant memberships. A reader may hold exactly one wrapper: the person
|
||||
// scope of the account they are linked to. Administrators never hold key
|
||||
// material.
|
||||
// their tenant memberships. A reader keeps the person scope they are linked to
|
||||
// plus every person scope that its owner has shared with the account.
|
||||
// Administrators never hold key material.
|
||||
func (s *Store) PruneUserWrappers(ctx context.Context, userID string) error {
|
||||
var role, linkedTenantID, linkedPersonID string
|
||||
var active int
|
||||
@@ -826,8 +846,13 @@ func (s *Store) PruneUserWrappers(ctx context.Context, userID string) error {
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, `
|
||||
DELETE FROM key_wrappers WHERE user_id=? AND NOT (
|
||||
scope_type='person' AND tenant_id=? AND scope_id=?
|
||||
)`, userID, linkedTenantID, linkedPersonID)
|
||||
scope_type='person' AND tenant_id=? AND (
|
||||
scope_id=? OR scope_id IN (
|
||||
SELECT owner_person_id FROM contact_shares
|
||||
WHERE tenant_id=? AND viewer_user_id=?
|
||||
)
|
||||
)
|
||||
)`, userID, linkedTenantID, linkedPersonID, linkedTenantID, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
+60
-15
@@ -49,6 +49,25 @@ func encodeInts(values []int) string {
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func encodeWeekdayPeriods(values []domain.WeekdayPeriodPreference) string {
|
||||
if values == nil {
|
||||
values = []domain.WeekdayPeriodPreference{}
|
||||
}
|
||||
data, err := json.Marshal(values)
|
||||
if err != nil {
|
||||
return "[]"
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func decodeWeekdayPeriods(value string) []domain.WeekdayPeriodPreference {
|
||||
var out []domain.WeekdayPeriodPreference
|
||||
if err := json.Unmarshal([]byte(value), &out); err != nil {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Churches lists a tenant's churches.
|
||||
func (s *Store) Churches(ctx context.Context, tenantID string) ([]domain.Church, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
@@ -152,8 +171,9 @@ func (s *Store) DeleteChurch(ctx context.Context, tenantID, id string) error {
|
||||
// People lists a tenant's volunteers.
|
||||
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, preferred_church_ids,
|
||||
preferred_weekdays, preferred_service_titles, max_per_month, active, notes
|
||||
SELECT id, short_code, first_name, last_name, roles, email, preferred_church_ids,
|
||||
preferred_weekdays, preferred_weekday_periods, preferred_service_titles,
|
||||
max_per_month, allow_beyond_preferences, active, notes
|
||||
FROM people WHERE tenant_id=? ORDER BY last_name COLLATE NOCASE, first_name COLLATE NOCASE`, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -183,8 +203,9 @@ func (s *Store) People(ctx context.Context, tenantID string) ([]domain.Person, e
|
||||
// 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, preferred_church_ids,
|
||||
preferred_weekdays, preferred_service_titles, max_per_month, active, notes
|
||||
SELECT id, short_code, first_name, last_name, roles, email, preferred_church_ids,
|
||||
preferred_weekdays, preferred_weekday_periods, preferred_service_titles,
|
||||
max_per_month, allow_beyond_preferences, active, notes
|
||||
FROM people WHERE tenant_id=? AND id=?`, tenantID, id)
|
||||
person, err := scanPerson(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
@@ -218,11 +239,11 @@ func (s *Store) hydratePersonContacts(ctx context.Context, tenantID string, pers
|
||||
|
||||
func scanPerson(row rowScanner) (*domain.Person, error) {
|
||||
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, &churches, &weekdays, &titles,
|
||||
&person.MaxPerMonth, &active, &person.Notes); err != nil {
|
||||
var roles, churches, weekdays, periods, titles string
|
||||
var allowBeyond, active int
|
||||
if err := row.Scan(&person.ID, &person.ShortCode, &person.FirstName, &person.LastName, &roles,
|
||||
&person.Email, &churches, &weekdays, &periods, &titles,
|
||||
&person.MaxPerMonth, &allowBeyond, &active, &person.Notes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, raw := range decodeStrings(roles) {
|
||||
@@ -233,7 +254,9 @@ func scanPerson(row rowScanner) (*domain.Person, error) {
|
||||
}
|
||||
person.PreferredChurchIDs = decodeStrings(churches)
|
||||
person.PreferredWeekdays = decodeInts(weekdays)
|
||||
person.PreferredWeekdayPeriods = decodeWeekdayPeriods(periods)
|
||||
person.PreferredServiceTitles = decodeStrings(titles)
|
||||
person.AllowBeyondPreferences = allowBeyond != 0
|
||||
person.Active = active != 0
|
||||
return &person, nil
|
||||
}
|
||||
@@ -285,21 +308,28 @@ func (s *Store) UpsertPerson(ctx context.Context, tenantID string, person domain
|
||||
email = ""
|
||||
}
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO people(tenant_id, id, first_name, last_name, roles, email,
|
||||
preferred_church_ids, preferred_weekdays, preferred_service_titles,
|
||||
max_per_month, active, notes)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
INSERT INTO people(tenant_id, id, short_code, first_name, last_name, roles, email,
|
||||
preferred_church_ids, preferred_weekdays, preferred_weekday_periods,
|
||||
preferred_service_titles, max_per_month, allow_beyond_preferences, active, notes)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(tenant_id, id) DO UPDATE SET
|
||||
short_code=excluded.short_code,
|
||||
first_name=excluded.first_name, last_name=excluded.last_name, roles=excluded.roles,
|
||||
email=CASE WHEN ? THEN excluded.email ELSE people.email END,
|
||||
preferred_church_ids=excluded.preferred_church_ids,
|
||||
preferred_weekdays=excluded.preferred_weekdays,
|
||||
preferred_weekday_periods=excluded.preferred_weekday_periods,
|
||||
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),
|
||||
max_per_month=excluded.max_per_month,
|
||||
allow_beyond_preferences=excluded.allow_beyond_preferences,
|
||||
active=excluded.active, notes=excluded.notes`,
|
||||
tenantID, person.ID, strings.TrimSpace(person.ShortCode),
|
||||
person.FirstName, person.LastName, encodeStrings(roleStrings),
|
||||
email, encodeStrings(person.PreferredChurchIDs),
|
||||
encodeInts(person.PreferredWeekdays),
|
||||
encodeWeekdayPeriods(person.PreferredWeekdayPeriods),
|
||||
encodeStrings(person.PreferredServiceTitles), person.MaxPerMonth,
|
||||
boolInt(person.AllowBeyondPreferences),
|
||||
boolInt(person.Active), person.Notes, boolInt(updateLegacyContact))
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -360,6 +390,21 @@ func (s *Store) DeletePerson(ctx context.Context, tenantID, id string) error {
|
||||
ScopePerson, tenantID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"DELETE FROM contact_shares WHERE tenant_id=? AND (owner_person_id=? OR viewer_user_id IN ("+
|
||||
"SELECT id FROM users WHERE linked_tenant_id=? AND linked_person_id=?))",
|
||||
tenantID, id, tenantID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"DELETE FROM contact_reviews WHERE tenant_id=? AND owner_person_id=?", tenantID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"DELETE FROM swap_requests WHERE tenant_id=? AND (requester_person_id=? OR target_person_id=?)",
|
||||
tenantID, id, id); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.ExecContext(ctx, "DELETE FROM people WHERE tenant_id=? AND id=?", tenantID, id)
|
||||
return err
|
||||
})
|
||||
|
||||
+21
-14
@@ -270,7 +270,8 @@ func (s *Store) DeleteGeneratedServices(ctx context.Context, tenantID string, r
|
||||
// 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
|
||||
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))
|
||||
@@ -292,7 +293,7 @@ func (s *Store) AssignmentsForServices(ctx context.Context, tenantID string, ser
|
||||
for _, id := range serviceIDs {
|
||||
args = append(args, id)
|
||||
}
|
||||
query := "SELECT id, service_id, person_id, role, locked, note, created_at FROM assignments " +
|
||||
query := "SELECT id, service_id, person_id, role, locked, beyond_preferences, note, created_at FROM assignments " +
|
||||
"WHERE tenant_id=? AND service_id IN (" + placeholders + ")"
|
||||
rows, err := s.db.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
@@ -305,7 +306,7 @@ func (s *Store) AssignmentsForServices(ctx context.Context, tenantID string, ser
|
||||
// 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
|
||||
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
|
||||
@@ -326,13 +327,14 @@ func scanAssignments(rows *sql.Rows) ([]domain.Assignment, error) {
|
||||
for rows.Next() {
|
||||
var assignment domain.Assignment
|
||||
var role, created string
|
||||
var locked int
|
||||
var locked, beyond int
|
||||
if err := rows.Scan(&assignment.ID, &assignment.ServiceID, &assignment.PersonID,
|
||||
&role, &locked, &assignment.Note, &created); err != nil {
|
||||
&role, &locked, &beyond, &assignment.Note, &created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
assignment.Role = domain.Role(role)
|
||||
assignment.Locked = locked != 0
|
||||
assignment.BeyondPreferences = beyond != 0
|
||||
assignment.CreatedAt = parseTime(created)
|
||||
out = append(out, assignment)
|
||||
}
|
||||
@@ -351,14 +353,16 @@ func (s *Store) UpsertAssignment(ctx context.Context, tenantID string, assignmen
|
||||
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(?, ?, ?, ?, ?, ?, ?, ?)
|
||||
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, note=excluded.note`,
|
||||
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), assignment.Note,
|
||||
assignment.CreatedAt.Format(time.RFC3339))
|
||||
string(assignment.Role), boolInt(assignment.Locked), boolInt(assignment.BeyondPreferences),
|
||||
assignment.Note, assignment.CreatedAt.Format(time.RFC3339))
|
||||
if err != nil && isUniqueViolation(err) {
|
||||
return ErrConflict
|
||||
}
|
||||
@@ -399,13 +403,16 @@ func (s *Store) SavePlan(ctx context.Context, tenantID string, assignments []dom
|
||||
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(?, ?, ?, ?, ?, ?, ?, ?)
|
||||
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, note=excluded.note`,
|
||||
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), assignment.Note,
|
||||
string(assignment.Role), boolInt(assignment.Locked),
|
||||
boolInt(assignment.BeyondPreferences), assignment.Note,
|
||||
assignment.CreatedAt.Format(time.RFC3339)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,442 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
// Swap request states.
|
||||
const (
|
||||
SwapPending = "pending"
|
||||
SwapAccepted = "accepted"
|
||||
SwapDeclined = "declined"
|
||||
SwapCancelled = "cancelled"
|
||||
)
|
||||
|
||||
// SwapRequest is one proposed exchange of two assignments.
|
||||
type SwapRequest struct {
|
||||
ID string
|
||||
TenantID string
|
||||
RequesterUserID string
|
||||
RequesterPersonID string
|
||||
TargetUserID string
|
||||
TargetPersonID string
|
||||
OfferedAssignmentID string
|
||||
WantedAssignmentID string
|
||||
Status string
|
||||
TokenHash string
|
||||
CreatedAt time.Time
|
||||
RespondedAt time.Time
|
||||
}
|
||||
|
||||
// SwapAssignmentInfo bundles an assignment with its service.
|
||||
type SwapAssignmentInfo struct {
|
||||
Assignment domain.Assignment
|
||||
Service domain.ServiceOccurrence
|
||||
}
|
||||
|
||||
func swapTokenHash(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// SwapTokenMatches reports whether a plaintext e-mail token belongs to the
|
||||
// stored request.
|
||||
func SwapTokenMatches(request *SwapRequest, token string) bool {
|
||||
if request == nil || request.TokenHash == "" || token == "" {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare([]byte(request.TokenHash), []byte(swapTokenHash(token))) == 1
|
||||
}
|
||||
|
||||
func newSwapToken() (string, error) {
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(raw), nil
|
||||
}
|
||||
|
||||
func scanSwapRequest(row rowScanner) (*SwapRequest, error) {
|
||||
var request SwapRequest
|
||||
var created, responded string
|
||||
if err := row.Scan(&request.ID, &request.TenantID, &request.RequesterUserID,
|
||||
&request.RequesterPersonID, &request.TargetUserID, &request.TargetPersonID,
|
||||
&request.OfferedAssignmentID, &request.WantedAssignmentID, &request.Status,
|
||||
&request.TokenHash, &created, &responded); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request.CreatedAt = parseTime(created)
|
||||
request.RespondedAt = parseTime(responded)
|
||||
return &request, nil
|
||||
}
|
||||
|
||||
const swapRequestColumns = `id, tenant_id, requester_user_id, requester_person_id,
|
||||
target_user_id, target_person_id, offered_assignment_id, wanted_assignment_id,
|
||||
status, token_hash, created_at, responded_at`
|
||||
|
||||
// SwapRequestByToken loads a request by its unhashed e-mail token.
|
||||
func (s *Store) SwapRequestByToken(ctx context.Context, tenantID, token string) (*SwapRequest, error) {
|
||||
row := s.db.QueryRowContext(ctx, `SELECT `+swapRequestColumns+`
|
||||
FROM swap_requests WHERE tenant_id=? AND token_hash=?`,
|
||||
tenantID, swapTokenHash(strings.TrimSpace(token)))
|
||||
request, err := scanSwapRequest(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return request, err
|
||||
}
|
||||
|
||||
// SwapRequestByID loads one request of a tenant.
|
||||
func (s *Store) SwapRequestByID(ctx context.Context, tenantID, id string) (*SwapRequest, error) {
|
||||
row := s.db.QueryRowContext(ctx, `SELECT `+swapRequestColumns+`
|
||||
FROM swap_requests WHERE tenant_id=? AND id=?`, tenantID, id)
|
||||
request, err := scanSwapRequest(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return request, err
|
||||
}
|
||||
|
||||
// swapAssignmentInfo loads one assignment together with its service.
|
||||
func (s *Store) SwapAssignmentInfo(ctx context.Context, tenantID, assignmentID string) (*SwapAssignmentInfo, error) {
|
||||
row := s.db.QueryRowContext(ctx, `
|
||||
SELECT a.id, a.service_id, a.person_id, a.role, a.locked, a.note, a.created_at,
|
||||
s.id, s.church_id, s.location, s.template_id, s.date, s.time_minutes,
|
||||
s.title, s.lectors_needed, s.helpers_needed, s.kind, s.notes,
|
||||
s.locked, s.created_at
|
||||
FROM assignments a
|
||||
JOIN services s ON s.tenant_id=a.tenant_id AND s.id=a.service_id
|
||||
WHERE a.tenant_id=? AND a.id=?`, tenantID, assignmentID)
|
||||
var info SwapAssignmentInfo
|
||||
var role, aCreated, date, kind, sCreated, location string
|
||||
var templateID sql.NullString
|
||||
var aLocked, sLocked int
|
||||
if err := row.Scan(&info.Assignment.ID, &info.Assignment.ServiceID,
|
||||
&info.Assignment.PersonID, &role, &aLocked, &info.Assignment.Note, &aCreated,
|
||||
&info.Service.ID, &info.Service.ChurchID, &location, &templateID, &date,
|
||||
&info.Service.TimeMinutes, &info.Service.Title, &info.Service.LectorsNeeded,
|
||||
&info.Service.HelpersNeeded, &kind, &info.Service.Notes, &sLocked, &sCreated); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
info.Assignment.Role = domain.Role(role)
|
||||
info.Assignment.Locked = aLocked != 0
|
||||
info.Assignment.CreatedAt = parseTime(aCreated)
|
||||
if location != "" {
|
||||
info.Service.Location = &location
|
||||
}
|
||||
if templateID.Valid && templateID.String != "" {
|
||||
value := templateID.String
|
||||
info.Service.TemplateID = &value
|
||||
}
|
||||
info.Service.Date = domain.MustDate(date)
|
||||
info.Service.Kind = domain.ServiceKind(kind)
|
||||
info.Service.Locked = sLocked != 0
|
||||
info.Service.CreatedAt = parseTime(sCreated)
|
||||
return &info, nil
|
||||
}
|
||||
|
||||
func (s *Store) personAbsentOn(ctx context.Context, tenantID, personID string, date time.Time) bool {
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM absences
|
||||
WHERE tenant_id=? AND person_id=? AND start_date<=? AND end_date>=?`,
|
||||
tenantID, personID, domain.Key(date), domain.Key(date)).Scan(&count)
|
||||
return err == nil && count > 0
|
||||
}
|
||||
|
||||
func (s *Store) assignmentConflict(ctx context.Context, tenantID, serviceID, personID string, role domain.Role, excludeID string) bool {
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM assignments
|
||||
WHERE tenant_id=? AND service_id=? AND person_id=? AND role=? AND id<>?`,
|
||||
tenantID, serviceID, personID, string(role), excludeID).Scan(&count)
|
||||
return err == nil && count > 0
|
||||
}
|
||||
|
||||
func (s *Store) pendingSwapForAssignment(ctx context.Context, tenantID, assignmentID, excludeRequestID string) bool {
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM swap_requests
|
||||
WHERE tenant_id=? AND status=? AND id<>?
|
||||
AND (offered_assignment_id=? OR wanted_assignment_id=?)`,
|
||||
tenantID, SwapPending, excludeRequestID, assignmentID, assignmentID).Scan(&count)
|
||||
return err == nil && count > 0
|
||||
}
|
||||
|
||||
// swapConsentExists verifies the mutual address release that makes both the
|
||||
// request and the response e-mail possible.
|
||||
func (s *Store) swapConsentExists(ctx context.Context, tenantID, requesterUserID, requesterPersonID, targetUserID, targetPersonID string) bool {
|
||||
return s.ContactShareExists(ctx, tenantID, targetPersonID, requesterUserID) &&
|
||||
s.ContactShareExists(ctx, tenantID, requesterPersonID, targetUserID)
|
||||
}
|
||||
|
||||
// validateSwapPair checks every planning and privacy precondition for a swap.
|
||||
// excludeRequestID is the request currently being answered, if any.
|
||||
func (s *Store) validateSwapPair(ctx context.Context, tenantID, requesterPersonID, targetPersonID, offeredID, wantedID, excludeRequestID string) (*SwapAssignmentInfo, *SwapAssignmentInfo, error) {
|
||||
if requesterPersonID == "" || targetPersonID == "" || offeredID == "" || wantedID == "" {
|
||||
return nil, nil, errors.New("Für den Tausch fehlen Angaben")
|
||||
}
|
||||
if requesterPersonID == targetPersonID {
|
||||
return nil, nil, errors.New("Ein Tausch mit sich selbst ist nicht möglich")
|
||||
}
|
||||
offered, err := s.SwapAssignmentInfo(ctx, tenantID, offeredID)
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("Der angebotene Einsatz wurde nicht gefunden")
|
||||
}
|
||||
wanted, err := s.SwapAssignmentInfo(ctx, tenantID, wantedID)
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("Der gewünschte Einsatz wurde nicht gefunden")
|
||||
}
|
||||
if offered.Assignment.PersonID != requesterPersonID {
|
||||
return nil, nil, errors.New("Der angebotene Einsatz gehört nicht mehr zu Ihnen")
|
||||
}
|
||||
if wanted.Assignment.PersonID != targetPersonID {
|
||||
return nil, nil, errors.New("Der gewünschte Einsatz gehört nicht mehr zur angefragten Person")
|
||||
}
|
||||
if offered.Assignment.Role != wanted.Assignment.Role {
|
||||
return nil, nil, errors.New("Es können nur Einsätze derselben Rolle getauscht werden")
|
||||
}
|
||||
today := domain.Today()
|
||||
if offered.Service.Date.Before(today) || wanted.Service.Date.Before(today) {
|
||||
return nil, nil, errors.New("Vergangene Einsätze können nicht getauscht werden")
|
||||
}
|
||||
if offered.Service.Locked || offered.Assignment.Locked || wanted.Service.Locked || wanted.Assignment.Locked {
|
||||
return nil, nil, errors.New("Gesperrte Einsätze können nicht getauscht werden")
|
||||
}
|
||||
if s.personAbsentOn(ctx, tenantID, targetPersonID, offered.Service.Date) {
|
||||
return nil, nil, errors.New("Die angefragte Person ist am angebotenen Termin als abwesend eingetragen")
|
||||
}
|
||||
if s.personAbsentOn(ctx, tenantID, requesterPersonID, wanted.Service.Date) {
|
||||
return nil, nil, errors.New("Sie sind am gewünschten Termin als abwesend eingetragen")
|
||||
}
|
||||
if s.assignmentConflict(ctx, tenantID, wanted.Service.ID, requesterPersonID, wanted.Assignment.Role, wanted.Assignment.ID) {
|
||||
return nil, nil, errors.New("Sie sind für diesen Gottesdienst bereits in derselben Rolle eingeteilt")
|
||||
}
|
||||
if s.assignmentConflict(ctx, tenantID, offered.Service.ID, targetPersonID, offered.Assignment.Role, offered.Assignment.ID) {
|
||||
return nil, nil, errors.New("Die angefragte Person ist für diesen Gottesdienst bereits in derselben Rolle eingeteilt")
|
||||
}
|
||||
if s.pendingSwapForAssignment(ctx, tenantID, offered.Assignment.ID, excludeRequestID) ||
|
||||
s.pendingSwapForAssignment(ctx, tenantID, wanted.Assignment.ID, excludeRequestID) {
|
||||
return nil, nil, errors.New("Für einen der beiden Einsätze liegt bereits eine offene Tauschanfrage vor")
|
||||
}
|
||||
return offered, wanted, nil
|
||||
}
|
||||
|
||||
// SwapOptions lists the requester's future assignments that can be offered for
|
||||
// the wanted assignment of the target person.
|
||||
func (s *Store) SwapOptions(ctx context.Context, tenantID, requesterPersonID, targetPersonID, wantedAssignmentID string) ([]SwapAssignmentInfo, error) {
|
||||
wanted, err := s.SwapAssignmentInfo(ctx, tenantID, wantedAssignmentID)
|
||||
if err != nil {
|
||||
return nil, errors.New("Der gewünschte Einsatz wurde nicht gefunden")
|
||||
}
|
||||
if wanted.Assignment.PersonID != targetPersonID {
|
||||
return nil, errors.New("Der gewünschte Einsatz gehört nicht mehr zur angefragten Person")
|
||||
}
|
||||
if wanted.Service.Date.Before(domain.Today()) {
|
||||
return nil, errors.New("Vergangene Einsätze können nicht getauscht werden")
|
||||
}
|
||||
if wanted.Service.Locked || wanted.Assignment.Locked {
|
||||
return nil, errors.New("Gesperrte Einsätze können nicht getauscht werden")
|
||||
}
|
||||
assignments, err := s.AssignmentsForPerson(ctx, tenantID, requesterPersonID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]SwapAssignmentInfo, 0, len(assignments))
|
||||
for _, assignment := range assignments {
|
||||
if assignment.Role != wanted.Assignment.Role || assignment.ID == wanted.Assignment.ID {
|
||||
continue
|
||||
}
|
||||
service, err := s.Service(ctx, tenantID, assignment.ServiceID)
|
||||
if err != nil || service.Date.Before(domain.Today()) {
|
||||
continue
|
||||
}
|
||||
offered, _, err := s.validateSwapPair(ctx, tenantID, requesterPersonID,
|
||||
targetPersonID, assignment.ID, wantedAssignmentID, "")
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, *offered)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CreateSwapRequest validates a proposed exchange, stores it and returns the
|
||||
// plaintext e-mail token. Only the token hash is persisted.
|
||||
func (s *Store) CreateSwapRequest(ctx context.Context, tenantID, requesterUserID, requesterPersonID, targetUserID, targetPersonID, offeredID, wantedID string) (*SwapRequest, string, error) {
|
||||
if !s.swapConsentExists(ctx, tenantID, requesterUserID, requesterPersonID, targetUserID, targetPersonID) {
|
||||
return nil, "", errors.New("Für eine Tauschanfrage müssen beide Seiten ihre E-Mail-Adresse gegenseitig freigegeben haben")
|
||||
}
|
||||
if _, _, err := s.validateSwapPair(ctx, tenantID, requesterPersonID, targetPersonID, offeredID, wantedID, ""); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
token, err := newSwapToken()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
request := &SwapRequest{
|
||||
ID: domain.NewID(), TenantID: tenantID,
|
||||
RequesterUserID: requesterUserID, RequesterPersonID: requesterPersonID,
|
||||
TargetUserID: targetUserID, TargetPersonID: targetPersonID,
|
||||
OfferedAssignmentID: offeredID, WantedAssignmentID: wantedID,
|
||||
Status: SwapPending, TokenHash: swapTokenHash(token), CreatedAt: now,
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, `
|
||||
INSERT INTO swap_requests(id, tenant_id, requester_user_id, requester_person_id,
|
||||
target_user_id, target_person_id, offered_assignment_id, wanted_assignment_id,
|
||||
status, token_hash, created_at, responded_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '')`,
|
||||
request.ID, request.TenantID, request.RequesterUserID, request.RequesterPersonID,
|
||||
request.TargetUserID, request.TargetPersonID, request.OfferedAssignmentID,
|
||||
request.WantedAssignmentID, request.Status, request.TokenHash,
|
||||
request.CreatedAt.Format(time.RFC3339))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return request, token, nil
|
||||
}
|
||||
|
||||
// RespondSwapRequest accepts or declines a request on behalf of the target
|
||||
// account. Accepting swaps both assignments atomically and revalidates every
|
||||
// planning rule first.
|
||||
func (s *Store) RespondSwapRequest(ctx context.Context, tenantID, token, targetUserID string, accept bool) (*SwapRequest, error) {
|
||||
request, err := s.SwapRequestByToken(ctx, tenantID, token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if request.TargetUserID != targetUserID {
|
||||
return nil, errors.New("Diese Tauschanfrage richtet sich an ein anderes Konto")
|
||||
}
|
||||
if request.Status != SwapPending {
|
||||
return nil, errors.New("Diese Tauschanfrage wurde bereits beantwortet")
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
if !accept {
|
||||
result, err := s.db.ExecContext(ctx, `
|
||||
UPDATE swap_requests SET status=?, responded_at=?
|
||||
WHERE tenant_id=? AND id=? AND status=?`,
|
||||
SwapDeclined, now.Format(time.RFC3339), tenantID, request.ID, SwapPending)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if affected, _ := result.RowsAffected(); affected == 0 {
|
||||
return nil, errors.New("Diese Tauschanfrage wurde bereits beantwortet")
|
||||
}
|
||||
request.Status = SwapDeclined
|
||||
request.RespondedAt = now
|
||||
return request, nil
|
||||
}
|
||||
|
||||
offered, wanted, err := s.validateSwapPair(ctx, tenantID, request.RequesterPersonID,
|
||||
request.TargetPersonID, request.OfferedAssignmentID, request.WantedAssignmentID, request.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !s.swapConsentExists(ctx, tenantID, request.RequesterUserID, request.RequesterPersonID,
|
||||
request.TargetUserID, request.TargetPersonID) {
|
||||
return nil, errors.New("Die gegenseitige E-Mail-Freigabe wurde inzwischen entzogen; der Tausch kann nicht angenommen werden")
|
||||
}
|
||||
tempPerson := "swap-tmp-" + request.ID
|
||||
err = s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
update := func(personID, assignmentID, expected string) error {
|
||||
result, err := tx.ExecContext(ctx, `
|
||||
UPDATE assignments SET person_id=?
|
||||
WHERE tenant_id=? AND id=? AND person_id=?`,
|
||||
personID, tenantID, assignmentID, expected)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected, _ := result.RowsAffected(); affected != 1 {
|
||||
return errors.New("Die Einteilung hat sich inzwischen geändert")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := update(tempPerson, offered.Assignment.ID, request.RequesterPersonID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := update(request.RequesterPersonID, wanted.Assignment.ID, request.TargetPersonID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := update(request.TargetPersonID, offered.Assignment.ID, tempPerson); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := tx.ExecContext(ctx, `
|
||||
UPDATE swap_requests SET status=?, responded_at=?
|
||||
WHERE tenant_id=? AND id=? AND status=?`,
|
||||
SwapAccepted, now.Format(time.RFC3339), tenantID, request.ID, SwapPending)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected, _ := result.RowsAffected(); affected != 1 {
|
||||
return errors.New("Diese Tauschanfrage wurde bereits beantwortet")
|
||||
}
|
||||
// Competing requests for the same assignments can no longer be
|
||||
// fulfilled after this swap.
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
UPDATE swap_requests SET status=?, responded_at=?
|
||||
WHERE tenant_id=? AND status=? AND id<>?
|
||||
AND (offered_assignment_id IN (?, ?) OR wanted_assignment_id IN (?, ?))`,
|
||||
SwapCancelled, now.Format(time.RFC3339), tenantID, SwapPending, request.ID,
|
||||
offered.Assignment.ID, wanted.Assignment.ID,
|
||||
offered.Assignment.ID, wanted.Assignment.ID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request.Status = SwapAccepted
|
||||
request.RespondedAt = now
|
||||
return request, nil
|
||||
}
|
||||
|
||||
// PendingSwapAssignmentIDs maps assignment IDs of open swap requests to the
|
||||
// request ID so the plan and service views can mark them.
|
||||
func (s *Store) PendingSwapAssignmentIDs(ctx context.Context, tenantID string) (map[string]string, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, offered_assignment_id, wanted_assignment_id
|
||||
FROM swap_requests WHERE tenant_id=? AND status=?`,
|
||||
tenantID, SwapPending)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[string]string{}
|
||||
for rows.Next() {
|
||||
var id, offered, wanted string
|
||||
if err := rows.Scan(&id, &offered, &wanted); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[offered] = id
|
||||
out[wanted] = id
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// SwapStatusLabel returns the German label of a request state.
|
||||
func SwapStatusLabel(status string) string {
|
||||
switch status {
|
||||
case SwapAccepted:
|
||||
return "angenommen"
|
||||
case SwapDeclined:
|
||||
return "abgelehnt"
|
||||
case SwapCancelled:
|
||||
return "abgebrochen"
|
||||
default:
|
||||
return "offen"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user