package store import ( "context" "errors" "fmt" "time" "github.com/jackc/pgx/v5" ) // Abteilung ist Stammdatum für den Fragebogen (Feld A.abteilung). type Abteilung struct { ID string AccountID string Name string CreatedAt time.Time } // CreateAbteilung legt eine Abteilung für einen Mandanten an. func (s *Store) CreateAbteilung(ctx context.Context, accountID, name string) (Abteilung, error) { var a Abteilung err := s.db(ctx).QueryRow(ctx, ` INSERT INTO abteilung (account_id, name) VALUES ($1, $2) RETURNING id, account_id, name, created_at `, accountID, name).Scan(&a.ID, &a.AccountID, &a.Name, &a.CreatedAt) if err != nil { return Abteilung{}, fmt.Errorf("store: create abteilung: %w", err) } return a, nil } // ListAbteilungenForAccount liefert alle Abteilungen eines Mandanten, // alphabetisch — als Auswahlliste für den Fragebogen. func (s *Store) ListAbteilungenForAccount(ctx context.Context, accountID string) ([]Abteilung, error) { rows, err := s.db(ctx).Query(ctx, ` SELECT id, account_id, name, created_at FROM abteilung WHERE account_id = $1 ORDER BY name `, accountID) if err != nil { return nil, fmt.Errorf("store: list abteilungen: %w", err) } defer rows.Close() var out []Abteilung for rows.Next() { var a Abteilung if err := rows.Scan(&a.ID, &a.AccountID, &a.Name, &a.CreatedAt); err != nil { return nil, fmt.Errorf("store: scan abteilung: %w", err) } out = append(out, a) } if err := rows.Err(); err != nil { return nil, fmt.Errorf("store: list abteilungen: %w", err) } return out, nil } // GetAbteilung liest eine Abteilung anhand ihrer ID. func (s *Store) GetAbteilung(ctx context.Context, id string) (Abteilung, error) { var a Abteilung err := s.db(ctx).QueryRow(ctx, ` SELECT id, account_id, name, created_at FROM abteilung WHERE id = $1 `, id).Scan(&a.ID, &a.AccountID, &a.Name, &a.CreatedAt) if errors.Is(err, pgx.ErrNoRows) { return Abteilung{}, ErrNotFound } if err != nil { return Abteilung{}, fmt.Errorf("store: get abteilung: %w", err) } return a, nil } // DeleteAbteilung entfernt eine Abteilung (z. B. versehentlich doppelt // angelegt). func (s *Store) DeleteAbteilung(ctx context.Context, id string) error { tag, err := s.db(ctx).Exec(ctx, `DELETE FROM abteilung WHERE id = $1`, id) if err != nil { return fmt.Errorf("store: delete abteilung: %w", err) } if tag.RowsAffected() == 0 { return ErrNotFound } return nil }