Files
paliad/internal/services/note_service.go
m b34500ad31 feat(t-paliad-051): split paliad.users.role into job_title + global_role
Conflation: paliad.users.role was simultaneously job title (display only)
and global permission ('role=admin' checks across Go/SQL/JS). m wanted
to set his real job title ('Counsel Knowledge Lawyer') without losing
admin access — the t-paliad-050 admin-team UI even rejected role='admin'
on edit, so any UI-driven update silently demoted m.

Per m's three-axis principle ("firm roles are not project roles are not
tool roles"), this lands TWO orthogonal columns:

* paliad.users.job_title — free text, NULL allowed, display only.
  NEVER gates anything in code or SQL.
* paliad.users.global_role — CHECK ('standard'|'global_admin'),
  default 'standard'. The only thing that gates ops.

Migration 023:
* Drops NOT NULL + 'associate' default off the legacy role column
* Promotes role='admin' rows to global_role='global_admin'; clears
  their role text; sets m's job_title='Counsel Knowledge Lawyer'
* Renames role -> job_title with CHECK (job_title IS NULL OR <> '')
* Replaces can_see_project body with global_role='global_admin'
* CASCADE-rebuilds every RLS policy under canonical English names —
  with the historic u.role IN ('partner','admin') gates simplified
  to u.global_role='global_admin' only (job_title NEVER gates)

Code surface:
* internal/models/models.go: User.Role -> User.JobTitle (*string) +
  User.GlobalRole (string)
* internal/services/user_service.go: bootstrap (first row promoted to
  global_admin via pg_advisory_xact_lock(7346298141), unchanged constant);
  UpdateProfile drops role, accepts job_title only; AdminUpdateUser adds
  global_role with last-admin demotion guard (ErrLastGlobalAdmin);
  IsAdmin reads global_role
* Other services (dashboard/agenda/appointment/project/deadline/
  department/party/note/checklist_instance): pass user.GlobalRole into
  visibility predicates; partner-or-admin gates simplified to
  global_admin only
* Handlers: drop now-impossible ErrAdminBootstrapOnly cases;
  admin_users handles ErrLastGlobalAdmin -> 409
* department_service: SQL u.role -> u.job_title, DepartmentMember.Role
  -> JobTitle (*string)

Frontend:
* /api/me + Me interfaces ship {job_title, global_role}
* Onboarding form: 'Berufsbezeichnung / Job title' (job_title)
* Settings + admin-team forms: same renames + i18n updates
* Admin-team: new 'Berechtigung / Permission' column with
  'Standard'|'Global Admin' badge + dropdown editor; last-admin
  demotion guard at the UI layer
* Sidebar admin-section reveal: me.global_role==='global_admin'
* deadlines/deadlines-detail/projects-detail/notes: partner-as-permission
  gates dropped, only global_admin grants those operations

Tests:
* user_service_test: bootstrap promotes first user to global_admin,
  subsequent default to standard; AdminUpdateUser refuses to demote
  the last global_admin; IsAdmin reads global_role

Migration applied to ydb 2026-04-27. Live state verified:
* m: job_title='Counsel Knowledge Lawyer', global_role='global_admin'
* tester: job_title=NULL, global_role='global_admin'
* 29 stub colleagues: job_title='associate', global_role='standard'
2026-04-27 14:59:03 +02:00

338 lines
10 KiB
Go

package services
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"mgit.msbls.de/m/patholo/internal/models"
)
// NoteService reads and writes paliad.notes — polymorphic notes anchored
// to exactly one of { Project, Deadline, Appointment, ProjectEvent }. Visibility
// follows the parent row.
//
// Edit: only the author (created_by) may edit their own note.
// Delete: author, or partner/admin.
type NoteService struct {
db *sqlx.DB
projects *ProjectService
appointment *AppointmentService
}
func NewNoteService(db *sqlx.DB, projects *ProjectService, appointment *AppointmentService) *NoteService {
return &NoteService{db: db, projects: projects, appointment: appointment}
}
const notizColumns = `n.id, n.project_id, n.deadline_id, n.appointment_id, n.project_event_id,
n.content, n.created_by, n.created_at, n.updated_at,
u.display_name AS author_name,
u.email AS author_email`
const notizSelect = `SELECT ` + notizColumns + `
FROM paliad.notes n
LEFT JOIN paliad.users u ON u.id = n.created_by`
// CreateNotizInput is the POST payload.
type CreateNotizInput struct {
Content string `json:"content"`
}
// UpdateNotizInput is the PATCH payload.
type UpdateNotizInput struct {
Content *string `json:"content,omitempty"`
}
// ListForProjekt returns all notes attached directly to the given Project.
func (s *NoteService) ListForProjekt(ctx context.Context, userID, projektID uuid.UUID) ([]models.Note, error) {
if _, err := s.projects.GetByID(ctx, userID, projektID); err != nil {
return nil, err
}
return s.list(ctx, `n.project_id = $1`, projektID)
}
// ListForFrist returns all notes attached to a specific Deadline.
func (s *NoteService) ListForFrist(ctx context.Context, userID, fristID uuid.UUID) ([]models.Note, error) {
projektID, err := s.fristProjectID(ctx, fristID)
if err != nil {
return nil, err
}
if _, err := s.projects.GetByID(ctx, userID, projektID); err != nil {
return nil, err
}
return s.list(ctx, `n.deadline_id = $1`, fristID)
}
// ListForTermin returns all notes attached to a specific Appointment.
func (s *NoteService) ListForTermin(ctx context.Context, userID, terminID uuid.UUID) ([]models.Note, error) {
if _, err := s.appointment.GetByID(ctx, userID, terminID); err != nil {
return nil, err
}
return s.list(ctx, `n.appointment_id = $1`, terminID)
}
// ListForProjectEvent returns all notes attached to a specific projekt_event row.
func (s *NoteService) ListForProjectEvent(ctx context.Context, userID, eventID uuid.UUID) ([]models.Note, error) {
projektID, err := s.eventProjectID(ctx, eventID)
if err != nil {
return nil, err
}
if _, err := s.projects.GetByID(ctx, userID, projektID); err != nil {
return nil, err
}
return s.list(ctx, `n.project_event_id = $1`, eventID)
}
// CreateForProjekt inserts a note attached directly to a Project.
func (s *NoteService) CreateForProjekt(ctx context.Context, userID, projektID uuid.UUID, input CreateNotizInput) (*models.Note, error) {
if _, err := s.projects.GetByID(ctx, userID, projektID); err != nil {
return nil, err
}
content, err := validateContent(input.Content)
if err != nil {
return nil, err
}
id, err := s.insertWithAudit(ctx, userID, content, noteParent{ProjectID: &projektID}, &projektID, "project")
if err != nil {
return nil, err
}
return s.getByIDUnchecked(ctx, id)
}
// CreateForFrist inserts a note attached to a Deadline.
func (s *NoteService) CreateForFrist(ctx context.Context, userID, fristID uuid.UUID, input CreateNotizInput) (*models.Note, error) {
projektID, err := s.fristProjectID(ctx, fristID)
if err != nil {
return nil, err
}
if _, err := s.projects.GetByID(ctx, userID, projektID); err != nil {
return nil, err
}
content, err := validateContent(input.Content)
if err != nil {
return nil, err
}
id, err := s.insertWithAudit(ctx, userID, content, noteParent{DeadlineID: &fristID}, &projektID, "deadline")
if err != nil {
return nil, err
}
return s.getByIDUnchecked(ctx, id)
}
// CreateForTermin inserts a note attached to a Appointment. Personal Appointment
// notes skip the audit trail; Project-attached Appointment notes append events.
func (s *NoteService) CreateForTermin(ctx context.Context, userID, terminID uuid.UUID, input CreateNotizInput) (*models.Note, error) {
t, err := s.appointment.GetByID(ctx, userID, terminID)
if err != nil {
return nil, err
}
content, err := validateContent(input.Content)
if err != nil {
return nil, err
}
id, err := s.insertWithAudit(ctx, userID, content, noteParent{AppointmentID: &terminID}, t.ProjectID, "appointment")
if err != nil {
return nil, err
}
return s.getByIDUnchecked(ctx, id)
}
// GetByID returns a single note, visibility-checked.
func (s *NoteService) GetByID(ctx context.Context, userID, id uuid.UUID) (*models.Note, error) {
n, err := s.getByIDUnchecked(ctx, id)
if err != nil {
return nil, err
}
if err := s.requireVisible(ctx, userID, n); err != nil {
return nil, err
}
return n, nil
}
// Update edits a note's content. Only the original author may edit.
func (s *NoteService) Update(ctx context.Context, userID, id uuid.UUID, input UpdateNotizInput) (*models.Note, error) {
current, err := s.GetByID(ctx, userID, id)
if err != nil {
return nil, err
}
if current.CreatedBy == nil || *current.CreatedBy != userID {
return nil, fmt.Errorf("%w: only the author can edit a Note", ErrForbidden)
}
if input.Content == nil {
return current, nil
}
content, err := validateContent(*input.Content)
if err != nil {
return nil, err
}
_, err = s.db.ExecContext(ctx,
`UPDATE paliad.notes SET content = $1, updated_at = NOW() WHERE id = $2`,
content, id)
if err != nil {
return nil, fmt.Errorf("update note: %w", err)
}
return s.getByIDUnchecked(ctx, id)
}
// Delete removes a note. Author, partner, or admin only.
func (s *NoteService) Delete(ctx context.Context, userID, id uuid.UUID) error {
current, err := s.GetByID(ctx, userID, id)
if err != nil {
return err
}
isAuthor := current.CreatedBy != nil && *current.CreatedBy == userID
if !isAuthor {
user, err := s.projects.Users().GetByID(ctx, userID)
if err != nil {
return err
}
if user.GlobalRole != "global_admin" {
return fmt.Errorf("%w: only the author or a partner/admin can delete a Note", ErrForbidden)
}
}
if _, err := s.db.ExecContext(ctx,
`DELETE FROM paliad.notes WHERE id = $1`, id); err != nil {
return fmt.Errorf("delete note: %w", err)
}
return nil
}
// --- internals -------------------------------------------------------------
type noteParent struct {
ProjectID *uuid.UUID
DeadlineID *uuid.UUID
AppointmentID *uuid.UUID
ProjectEventID *uuid.UUID
}
func (s *NoteService) list(ctx context.Context, where string, arg any) ([]models.Note, error) {
query := notizSelect + ` WHERE ` + where + ` ORDER BY n.created_at DESC`
rows := []models.Note{}
if err := s.db.SelectContext(ctx, &rows, query, arg); err != nil {
return nil, fmt.Errorf("list notes: %w", err)
}
return rows, nil
}
// insertWithAudit inserts one notes row and, when an owning Project exists,
// appends a project_events audit row in the same transaction.
func (s *NoteService) insertWithAudit(ctx context.Context, userID uuid.UUID, content string, parent noteParent, projektAuditID *uuid.UUID, parentLabel string) (uuid.UUID, error) {
id := uuid.New()
now := time.Now().UTC()
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return uuid.Nil, fmt.Errorf("begin tx: %w", err)
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx,
`INSERT INTO paliad.notes
(id, project_id, deadline_id, appointment_id, project_event_id,
content, created_by, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $8)`,
id, parent.ProjectID, parent.DeadlineID, parent.AppointmentID, parent.ProjectEventID,
content, userID, now,
); err != nil {
return uuid.Nil, fmt.Errorf("insert note: %w", err)
}
if projektAuditID != nil {
title := "Note added"
desc := fmt.Sprintf("Note zu %s hinzugef\u00fcgt", parentLabel)
descPtr := &desc
if err := insertProjectEvent(ctx, tx, *projektAuditID, userID, "note_created", title, descPtr); err != nil {
return uuid.Nil, err
}
}
if err := tx.Commit(); err != nil {
return uuid.Nil, fmt.Errorf("commit insert note: %w", err)
}
return id, nil
}
// getByIDUnchecked fetches a note without a visibility check.
func (s *NoteService) getByIDUnchecked(ctx context.Context, id uuid.UUID) (*models.Note, error) {
var n models.Note
err := s.db.GetContext(ctx, &n, notizSelect+` WHERE n.id = $1`, id)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotVisible
}
if err != nil {
return nil, fmt.Errorf("fetch note: %w", err)
}
return &n, nil
}
// requireVisible re-runs the parent-visibility check.
func (s *NoteService) requireVisible(ctx context.Context, userID uuid.UUID, n *models.Note) error {
switch {
case n.ProjectID != nil:
_, err := s.projects.GetByID(ctx, userID, *n.ProjectID)
return err
case n.DeadlineID != nil:
projektID, err := s.fristProjectID(ctx, *n.DeadlineID)
if err != nil {
return err
}
_, err = s.projects.GetByID(ctx, userID, projektID)
return err
case n.AppointmentID != nil:
_, err := s.appointment.GetByID(ctx, userID, *n.AppointmentID)
return err
case n.ProjectEventID != nil:
projektID, err := s.eventProjectID(ctx, *n.ProjectEventID)
if err != nil {
return err
}
_, err = s.projects.GetByID(ctx, userID, projektID)
return err
default:
return ErrNotVisible
}
}
func (s *NoteService) fristProjectID(ctx context.Context, fristID uuid.UUID) (uuid.UUID, error) {
var projektID uuid.UUID
err := s.db.GetContext(ctx, &projektID,
`SELECT project_id FROM paliad.deadlines WHERE id = $1`, fristID)
if errors.Is(err, sql.ErrNoRows) {
return uuid.Nil, ErrNotVisible
}
if err != nil {
return uuid.Nil, fmt.Errorf("lookup deadline parent: %w", err)
}
return projektID, nil
}
func (s *NoteService) eventProjectID(ctx context.Context, eventID uuid.UUID) (uuid.UUID, error) {
var projektID uuid.UUID
err := s.db.GetContext(ctx, &projektID,
`SELECT project_id FROM paliad.project_events WHERE id = $1`, eventID)
if errors.Is(err, sql.ErrNoRows) {
return uuid.Nil, ErrNotVisible
}
if err != nil {
return uuid.Nil, fmt.Errorf("lookup event parent: %w", err)
}
return projektID, nil
}
func validateContent(raw string) (string, error) {
content := strings.TrimSpace(raw)
if content == "" {
return "", fmt.Errorf("%w: content is required", ErrInvalidInput)
}
if len(content) > 10000 {
return "", fmt.Errorf("%w: content exceeds 10000 characters", ErrInvalidInput)
}
return content, nil
}