Skip to content

Self-hosted project management for devs and their clients: tickets, time tracking, docs and meetings, with an AI assistant that cites its sources. AGPL-3.0.

feat(people): add the people directory model, rights and writes

Guido Boykee3d8a292304a
diff --git a/app/helpers/roles_helper.rb b/app/helpers/roles_helper.rb
index d26a9bd..710e233 100644
--- a/app/helpers/roles_helper.rb
+++ b/app/helpers/roles_helper.rb
@@ -44,6 +44,10 @@ module RolesHelper
},
'assistant' => {
'use_assistant' => I18n.t('views.helpers.roles.descriptions.assistant.use_assistant')
+ },
+ 'people' => {
+ 'view_people' => I18n.t('views.helpers.roles.descriptions.people.view_people'),
+ 'manage_people' => I18n.t('views.helpers.roles.descriptions.people.manage_people')
}
}
@@ -58,7 +62,8 @@ module RolesHelper
'tickets' => I18n.t('views.helpers.roles.categories.tickets'),
'meetings' => I18n.t('views.helpers.roles.categories.meetings'),
'users' => I18n.t('views.helpers.roles.categories.users'),
- 'assistant' => I18n.t('views.helpers.roles.categories.assistant')
+ 'assistant' => I18n.t('views.helpers.roles.categories.assistant'),
+ 'people' => I18n.t('views.helpers.roles.categories.people')
}
names[category] || category.humanize
diff --git a/app/javascript/lib/meetings/name_normalizer.js b/app/javascript/lib/meetings/name_normalizer.js
index c9e3502..3913a0b 100644
--- a/app/javascript/lib/meetings/name_normalizer.js
+++ b/app/javascript/lib/meetings/name_normalizer.js
@@ -1,5 +1,5 @@
// Name normalization for meeting participants — the JS half of a contract shared
-// with Ruby (MeetingParticipant.normalize_name). Both sides are exercised against
+// with Ruby (PersonName.normalize). Both sides are exercised against
// spec/fixtures/name_normalization_cases.json so they cannot drift.
//
// Rule (identical to Ruby): NFC -> trim + collapse inner whitespace -> downcase
diff --git a/app/models/admin/membership.rb b/app/models/admin/membership.rb
index be9b19a..7c1c114 100644
--- a/app/models/admin/membership.rb
+++ b/app/models/admin/membership.rb
@@ -58,6 +58,9 @@ module Admin
# Guard: spec/models/seat_event_recording_spec.rb asserts that EVERY model
# on this table includes it, so a third twin cannot reopen the gap.
include SeatEventRecording
+ # Same as ::Membership: removing a member keeps their person row and drops
+ # its link (person_link_release.rb).
+ include PersonLinkRelease
# Associations (without tenant restrictions)
belongs_to :organisation, class_name: 'Admin::Organisation'
diff --git a/app/models/admin/user.rb b/app/models/admin/user.rb
index 56fe6ce..708c9d9 100644
--- a/app/models/admin/user.rb
+++ b/app/models/admin/user.rb
@@ -234,8 +234,10 @@ module Admin
# spec/models/user_erasure_path_parity_spec.rb.
def soft_delete_and_anonymize!
ActiveRecord::Base.transaction do
- memberships.destroy_all
+ # BEFORE the memberships, as on ::User: removing a membership unlinks
+ # the person row, and erase_person_links! finds the rows by that link.
erase_personal_data!
+ memberships.destroy_all
update_columns(
anonymization_attributes.merge(
deleted_at: Time.current,
diff --git a/app/models/concerns/person_link_release.rb b/app/models/concerns/person_link_release.rb
new file mode 100644
index 0000000..656e035
--- /dev/null
+++ b/app/models/concerns/person_link_release.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+# Leaving an organisation keeps the person row of that organisation and drops
+# only its link to the account: the row still names the person (its own name
+# column), the member half of the directory just stops showing them as a
+# member. Deactivation keeps the link, it is reversible.
+#
+# A concern because two classes write the memberships table without sharing a
+# save cycle: ::Membership (RemoveMembershipService, the members page) and
+# Admin::Membership (the operator's removal, Admin::User erasure). Both include
+# it; spec/models/admin_twin_concern_parity_guard_spec.rb keeps it that way.
+#
+# update_all, without tenant: the person's own validations and tracking have
+# nothing to say about a link the membership took with it, and the callback may
+# run with any tenant set (or none, in the admin backend).
+module PersonLinkRelease
+ extend ActiveSupport::Concern
+
+ included do
+ after_destroy :release_person_link
+ end
+
+ private
+
+ def release_person_link
+ ActsAsTenant.without_tenant do
+ Person.where(organisation_id: organisation_id, user_id: user_id).update_all(user_id: nil, updated_at: Time.current)
+ end
+ end
+end
diff --git a/app/models/concerns/person_trackable.rb b/app/models/concerns/person_trackable.rb
new file mode 100644
index 0000000..8ced6cc
--- /dev/null
+++ b/app/models/concerns/person_trackable.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+# Side-effect chain map: docs/architektur/seiteneffekt_ketten.md
+#
+# Tracking for the people directory WITHOUT personal data. A person row holds
+# data about third parties (name, phone, notes), and activities outlive the row
+# (Trackable#track_deleted runs after the row's own activities are gone and
+# leaves one new row behind). So:
+#
+# * no activity carries a name or a value: the parameters are empty, and an
+# update keeps only the NAMES of the changed fields ("phone changed");
+# * a delete leaves exactly one anonymous person.deleted row ("X deleted a
+# person"), the audit trail;
+# * no activity fans out. skip_notifications is the default context, whoever
+# writes (actor, console, a later import): person.* has no entry in
+# notifications/constants.rb, and an unknown key would fall back to
+# system_message in the fanout. This differs from Trackable, where the actor
+# sets the context; a person write has nobody to tell, ever.
+module PersonTrackable
+ extend ActiveSupport::Concern
+
+ include Trackable
+
+ # The context every person activity carries unless a caller set its own; a
+ # caller's context is merged on top and cannot switch the flag off.
+ QUIET_CONTEXT = { 'skip_notifications' => true }.freeze
+
+ # Bookkeeping columns, never shown as "changed".
+ UNTRACKED_FIELDS = %w[lock_version normalized_name creator_id].freeze
+
+ def activity_context
+ (super || {}).to_h.transform_keys(&:to_s).merge(QUIET_CONTEXT)
+ end
+
+ private
+
+ def track_specific_changes(changed_attrs)
+ fields = changed_attrs.keys - UNTRACKED_FIELDS
+ return if fields.empty?
+
+ create_activity(action: 'updated', attribute_changes: fields.index_with { nil }, parameters: {})
+ end
+
+ def activity_parameters_for_create
+ {}
+ end
+
+ def activity_parameters_for_update
+ {}
+ end
+
+ def activity_parameters_for_delete
+ {}
+ end
+end
diff --git a/app/models/concerns/personal_data_erasure.rb b/app/models/concerns/personal_data_erasure.rb
index 72e3160..e240898 100644
--- a/app/models/concerns/personal_data_erasure.rb
+++ b/app/models/concerns/personal_data_erasure.rb
@@ -2,7 +2,8 @@
# Erases the personal records an account owns BEYOND the users row itself, for
# the account-erasure path: GDPR export archives, private meeting analyses,
-# private ticket posts, personal tasks, the account's own chat threads (via
+# private ticket posts, personal tasks, linked people directory rows, the
+# account's own chat threads (via
# PersonalChatErasure, which is included here so that both entry points get it
# through this ONE include) and, as access revocation, its personal access
# tokens.
@@ -37,6 +38,7 @@ module PersonalDataErasure
erase_private_posts!
erase_personal_tasks!
erase_personal_chats!
+ erase_person_links!
revoke_personal_access_tokens!
end
@@ -106,6 +108,18 @@ module PersonalDataErasure
end
end
+ # The people directory rows linked to this account, in every organisation:
+ # once the account is erased the row describes nobody the organisation still
+ # works with through Lalabase, and its fields (phone, notes) are personal
+ # data. Rows NOT linked to the account stay; they are the organisation's
+ # contacts, even when they carry the same name. destroy_all so each row
+ # leaves its anonymous person.deleted activity (PersonTrackable).
+ def erase_person_links!
+ ActsAsTenant.without_tenant do
+ Person.where(user_id: id).destroy_all
+ end
+ end
+
# Access revocation rather than erasure: a personal access token authenticates
# by its hash alone (PersonalAccessToken.authenticate joins no users), so a
# token surviving the erasure keeps answering the API for up to 90 days with
diff --git a/app/models/meeting_participant.rb b/app/models/meeting_participant.rb
index 9e24ccb..7d981c3 100644
--- a/app/models/meeting_participant.rb
+++ b/app/models/meeting_participant.rb
@@ -60,16 +60,11 @@ class MeetingParticipant < ApplicationRecord
where(user_id: nil).joins(:meeting).where(meetings: { project_id: project_ids })
}
- # Normalization contract (mirrored in name_normalizer.js): NFC -> trim + collapse
- # whitespace -> downcase -> umlaut transliteration. Accents other than umlauts
- # are only downcased. Pure function so the contract spec can call it directly.
+ # Normalization contract: PersonName.normalize, the one normalizer shared
+ # with the people directory (mirrored in name_normalizer.js). Pure function so
+ # the contract spec can call it directly.
def self.normalize_name(value)
- return '' if value.nil?
-
- s = value.to_s.unicode_normalize(:nfc)
- s = s.strip.gsub(/\s+/, ' ')
- s = s.downcase
- s.gsub('ä', 'ae').gsub('ö', 'oe').gsub('ü', 'ue').gsub('ß', 'ss')
+ PersonName.normalize(value)
end
# Distinct people across a set of meetings, deduped by normalized_name with the
diff --git a/app/models/membership.rb b/app/models/membership.rb
index eedd64f..50328df 100644
--- a/app/models/membership.rb
+++ b/app/models/membership.rb
@@ -32,6 +32,8 @@ class Membership < ApplicationRecord
# Registers its own commit callbacks -- read the concern before adding another
# one here, it explains why the method names have to stay distinct.
include SeatEventRecording
+ # Removing a member keeps their person row and drops its link.
+ include PersonLinkRelease
belongs_to :organisation
diff --git a/app/models/organisation.rb b/app/models/organisation.rb
index 19c84f0..7bdf0bd 100644
--- a/app/models/organisation.rb
+++ b/app/models/organisation.rb
@@ -109,6 +109,8 @@ class Organisation < ApplicationRecord
has_many :ai_usages, dependent: :destroy
has_many :codebase_import_files, dependent: :destroy
has_many :tags, dependent: :destroy
+ # The shared people directory (Person). Rails-driven cleanup like the rows above.
+ has_many :people, dependent: :destroy
has_many :personal_access_token_organisations, dependent: :destroy
# The one order for lists of organisations a person sees: by name ignoring case, then by id
diff --git a/app/models/permission.rb b/app/models/permission.rb
index 40a1569..8ffdfc8 100644
--- a/app/models/permission.rb
+++ b/app/models/permission.rb
@@ -92,6 +92,15 @@ class Permission < ApplicationRecord
# stays a decision, not a side effect. Grantable to billable: false roles.
assistant: %w[
use_assistant
+ ],
+ # The shared people directory of the organisation (Person). Its own category
+ # for the same reason as :assistant: customer roles are billable: false and
+ # must be able to keep the list, which an action under :projects would
+ # forbid. manage_people (create, edit, delete, link) implies view_people in
+ # PersonPolicy. No role gets either automatically; account admins need none.
+ people: %w[
+ view_people
+ manage_people
]
}.freeze
diff --git a/app/models/person.rb b/app/models/person.rb
new file mode 100644
index 0000000..edb921c
--- /dev/null
+++ b/app/models/person.rb
@@ -0,0 +1,62 @@
+# frozen_string_literal: true
+
+# One person in the shared people directory of an organisation: a contact
+# without a login, or the extra details of a member (user_id). Consultant and
+# customer read and write the same rows, so nothing here is private (no
+# internal notes, D1). A person who works for two customers is two rows, one
+# per organisation (D3).
+#
+# name is always filled, also for a linked row (copied at link time by
+# Actors::SavePerson), so removing the membership loses nothing
+# (PersonLinkRelease). Tracking keeps no personal data (PersonTrackable).
+# lock_version: both sides edit the same row; a stale save raises
+# ActiveRecord::StaleObjectError.
+class Person < ApplicationRecord
+ # Declared BEFORE acts_as_tenant on purpose: acts_as_tenant 1.0.1 checks the
+ # tenant of a reference only for associations declared before the call. The
+ # link is validated on top (user_must_be_active_member), because a user has
+ # no organisation_id of its own.
+ belongs_to :user, optional: true
+ belongs_to :creator, class_name: 'User', optional: true
+ belongs_to :updater, class_name: 'User', optional: true
+
+ acts_as_tenant(:organisation)
+
+ include PersonTrackable
+
+ MAX_NOTES_LENGTH = 10_000
+ MAX_FIELD_LENGTH = 255
+ TEXT_FIELDS = %i[name function department company email phone].freeze
+
+ before_validation :normalize_name_fields
+
+ validates :name, presence: true
+ validates :normalized_name, presence: true
+ validates(*TEXT_FIELDS, length: { maximum: MAX_FIELD_LENGTH })
+ validates :notes, length: { maximum: MAX_NOTES_LENGTH }
+ validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }, allow_blank: true
+ validates :user_id, uniqueness: { scope: :organisation_id }, allow_nil: true
+ validate :user_must_be_active_member, if: -> { user_id.present? && will_save_change_to_user_id? }
+
+ scope :linked, -> { where.not(user_id: nil) }
+ scope :unlinked, -> { where(user_id: nil) }
+ scope :ordered, -> { order(:normalized_name, :id) }
+
+ def linked?
+ user_id.present?
+ end
+
+ private
+
+ def normalize_name_fields
+ self.name = name.to_s.strip.gsub(/\s+/, ' ') if name
+ self.normalized_name = PersonName.normalize(name)
+ end
+
+ # Same rule as Actors::SaveMeeting for participants: only an active member of
+ # this organisation can be linked. A deactivated or foreign user is refused.
+ def user_must_be_active_member
+ member = Membership.where(organisation_id: organisation_id, user_id: user_id, active: true).exists?
+ errors.add(:user, :not_an_active_member) unless member
+ end
+end
diff --git a/app/models/person_name.rb b/app/models/person_name.rb
new file mode 100644
index 0000000..bed56fc
--- /dev/null
+++ b/app/models/person_name.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+# The ONE name normalizer, shared by meeting participants and the people
+# directory, so a person and a meeting participant with the same name match.
+# Contract (mirrored in name_normalizer.js, pinned by
+# spec/fixtures/name_normalization_cases.json): NFC -> trim + collapse
+# whitespace -> downcase -> umlaut transliteration. Accents other than umlauts
+# are only downcased.
+module PersonName
+ def self.normalize(value)
+ return '' if value.nil?
+
+ s = value.to_s.unicode_normalize(:nfc)
+ s = s.strip.gsub(/\s+/, ' ')
+ s = s.downcase
+ s.gsub('ä', 'ae').gsub('ö', 'oe').gsub('ü', 'ue').gsub('ß', 'ss')
+ end
+end
diff --git a/app/models/user/deletion_lifecycle.rb b/app/models/user/deletion_lifecycle.rb
index 44fb59f..90aca5d 100644
--- a/app/models/user/deletion_lifecycle.rb
+++ b/app/models/user/deletion_lifecycle.rb
@@ -155,11 +155,13 @@ class User < ApplicationRecord
# inconsistent, half-erased user that no later run can cleanly recover.
def soft_delete_and_anonymize!
transaction do
- memberships.destroy_all
# Export archives, private analyses, own chat threads: shared with
# Admin::User through PersonalDataErasure (see there for why each step is
- # explicit).
+ # explicit). BEFORE the memberships: removing a membership unlinks the
+ # person row (PersonLinkRelease), and erase_person_links! finds the rows
+ # by that link.
erase_personal_data!
+ memberships.destroy_all
# update_column, not update!: this row is about to be force-saved past
# validations by anonymize! (an erasure must never be blocked by
# validation), so validating here would let a legacy-invalid row abort
diff --git a/app/policies/person_policy.rb b/app/policies/person_policy.rb
new file mode 100644
index 0000000..a732e41
--- /dev/null
+++ b/app/policies/person_policy.rb
@@ -0,0 +1,98 @@
+# frozen_string_literal: true
+
+# The people directory of an organisation (Person). A right of its own
+# (Permission::CATEGORIES[:people]): account admins have it without a row,
+# every other role only when an admin grants it. manage_people (create, edit,
+# delete, link) implies view_people. Grantable to billable: false roles, so a
+# customer role can keep the list.
+#
+# Every predicate asks for an ACTIVE membership itself:
+# User#has_permission_in_organisation? reads the role and does not look at
+# membership.active (same reason as ChatPolicy.assistant_gate_open?).
+class PersonPolicy < ApplicationPolicy
+ class Scope < ApplicationPolicy::Scope
+ # The rows of this organisation, minus the rows linked to an active member
+ # the viewer may not see on the members page (MembershipPolicy::Scope). A
+ # row linked to a former or deactivated member is shown, as a contact: its
+ # data is the row's own. Nothing without the right.
+ def resolve
+ return scope.none unless organisation && PersonPolicy.view_allowed?(user, organisation)
+
+ people = scope.where(organisation: organisation)
+ return people if user.account_admin_in?(organisation)
+
+ active_member_ids = Membership.where(organisation: organisation, active: true).select(:user_id)
+ visible_member_ids = MembershipPolicy::Scope.new(user, Membership).resolve.select(:user_id)
+ people.where(user_id: nil)
+ .or(people.where.not(user_id: active_member_ids))
+ .or(people.where(user_id: visible_member_ids))
+ end
+ end
+
+ def self.view_allowed?(user, organisation)
+ return false unless user.active_member_of_organisation?(organisation)
+
+ user.account_admin_in?(organisation) ||
+ user.has_permission_in_organisation?(organisation, 'people', 'view_people') ||
+ user.has_permission_in_organisation?(organisation, 'people', 'manage_people')
+ end
+
+ def self.manage_allowed?(user, organisation)
+ return false unless user.active_member_of_organisation?(organisation)
+
+ user.account_admin_in?(organisation) ||
+ user.has_permission_in_organisation?(organisation, 'people', 'manage_people')
+ end
+
+ def index?
+ can_view?
+ end
+
+ def show?
+ can_view? && same_organisation? && visible_record?
+ end
+
+ def create?
+ can_manage?
+ end
+
+ def new?
+ create?
+ end
+
+ def update?
+ can_manage? && same_organisation? && visible_record?
+ end
+
+ def edit?
+ update?
+ end
+
+ def destroy?
+ update?
+ end
+
+ private
+
+ def can_view?
+ return false unless organisation
+
+ self.class.view_allowed?(user, organisation)
+ end
+
+ def can_manage?
+ return false unless organisation
+
+ self.class.manage_allowed?(user, organisation)
+ end
+
+ def same_organisation?
+ record.is_a?(Person) && record.organisation_id == organisation.id
+ end
+
+ # The record must be one the scope would list: a row linked to a member the
+ # viewer cannot see is not readable by id either.
+ def visible_record?
+ Scope.new(user, Person).resolve.exists?(id: record.id)
+ end
+end
diff --git a/app/services/actors/destroy_person.rb b/app/services/actors/destroy_person.rb
new file mode 100644
index 0000000..1039431
--- /dev/null
+++ b/app/services/actors/destroy_person.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+# app/services/actors/destroy_person.rb
+#
+# Deletes one row of the people directory. Rights are the caller's
+# (PersonPolicy). The row's activities go with it; PersonTrackable leaves one
+# anonymous person.deleted activity behind ("X deleted a person"), without a
+# name or any other data of the row (D6).
+module Actors
+ class DestroyPerson < BaseActor
+ def initialize(person:, current_user:)
+ super()
+ @person = person
+ @current_user = current_user
+ end
+
+ # A destroy leaves no surviving primary record.
+ def record
+ nil
+ end
+
+ def perform
+ @person.destroy!
+ end
+
+ private
+
+ attr_reader :current_user
+ end
+end
diff --git a/app/services/actors/save_person.rb b/app/services/actors/save_person.rb
new file mode 100644
index 0000000..459824b
--- /dev/null
+++ b/app/services/actors/save_person.rb
@@ -0,0 +1,77 @@
+# frozen_string_literal: true
+
+# app/services/actors/save_person.rb
+#
+# Creates or updates one row of the people directory (Person). Rights are the
+# caller's (PersonPolicy); this actor owns the write:
+#
+# * the member link: a raw user_id from the form is resolved through the
+# members the writer may see (MembershipPolicy::Scope, active only), never
+# assigned as given. Linking copies the member's name into the row, so the
+# row keeps a name when the link goes (PersonLinkRelease).
+# * creator on create, updater on every save;
+# * a stale save (lock_version, both sides edit the same row) raises
+# StaleObjectError, which BaseActor maps to code :stale_object; the
+# controller shows the form again with the current values.
+#
+# Tracking is PersonTrackable's: no personal data, no fanout.
+module Actors
+ class SavePerson < BaseActor
+ ATTRIBUTES = %i[name function department company email phone notes lock_version].freeze
+
+ def initialize(organisation:, params:, current_user:, id: nil)
+ super()
+ @organisation = organisation
+ @params = params.to_h.symbolize_keys
+ @current_user = current_user
+ @person = find_person(id)
+ end
+
+ def record
+ @person
+ end
+
+ def perform
+ raise ActorError.new(I18n.t('controllers.people.not_found'), code: :not_found) if @person.nil?
+
+ @person.assign_attributes(@params.slice(*ATTRIBUTES))
+ assign_link if @params.key?(:user_id)
+ @person.creator ||= @current_user if @person.new_record?
+ @person.updater = @current_user
+ @person.save!
+ end
+
+ private
+
+ attr_reader :current_user
+
+ # Tenant-bound lookup: an id of another organisation is no person at all.
+ def find_person(id)
+ return @organisation.people.build if id.blank?
+
+ Person.where(organisation: @organisation).find_by(id: id)
+ end
+
+ def assign_link
+ user_id = @params[:user_id].presence
+ return @person.user = nil if user_id.nil?
+ return if user_id == @person.user_id
+
+ user = linkable_users.find_by(id: user_id)
+ raise ActorError.new(I18n.t('controllers.people.link_not_allowed'), code: :validation_failed) unless user
+
+ @person.user = user
+ @person.name = user.display_name
+ end
+
+ # The members the writer may link: active, and visible to them on the
+ # members page.
+ def linkable_users
+ member_ids = ActsAsTenant.with_tenant(@organisation) do
+ MembershipPolicy::Scope.new(@current_user, Membership).resolve
+ .where(organisation: @organisation, active: true).select(:user_id)
+ end
+ User.where(id: member_ids)
+ end
+ end
+end
diff --git a/app/services/people/directory.rb b/app/services/people/directory.rb
new file mode 100644
index 0000000..2d9aea8
--- /dev/null
+++ b/app/services/people/directory.rb
@@ -0,0 +1,84 @@
+# frozen_string_literal: true
+
+# Read object for the people directory page (Organisations::PeopleController).
+#
+# Entry point: entries
+module People
+ # The people directory of one organisation as a viewer sees it: the members
+ # they may see on the members page, each with their person row if one exists,
+ # and the person rows without an active member behind them (contacts).
+ #
+ # * Member half: MembershipPolicy::Scope, active memberships only, the same
+ # reach as the members page. A member of a project the viewer cannot see is
+ # not listed, and neither is their person row (PersonPolicy::Scope).
+ # * Contact half: rows without a link, and rows linked to someone who is no
+ # longer an active member (name from the row itself).
+ # * Search: one normalized substring match (PersonName.normalize, so "Muller"
+ # finds nothing but "mueller" and "Müller" find each other) over name,
+ # function, department, company and email. In Ruby, because the member half
+ # reads its names from users; the list is sized for a few hundred rows per
+ # organisation. Pagination is a follow-up once an organisation passes that.
+ class Directory
+ KINDS = %w[all members contacts].freeze
+
+ Entry = Struct.new(:kind, :user, :person, :sort_name, keyword_init: true) do
+ def member?
+ kind == :member
+ end
+
+ # The name the row stands for in search and order. A view shows a
+ # member's name through viewer_display_name instead.
+ def plain_name
+ member? ? user.display_name : person.name
+ end
+ end
+
+ def initialize(viewer:, organisation:, query: nil, kind: 'all')
+ @viewer = viewer
+ @organisation = organisation
+ @query = PersonName.normalize(query)
+ @kind = KINDS.include?(kind.to_s) ? kind.to_s : 'all'
+ end
+
+ def entries
+ return [] unless PersonPolicy.view_allowed?(@viewer, @organisation)
+
+ ActsAsTenant.with_tenant(@organisation) do
+ list = []
+ list.concat(member_entries) unless @kind == 'contacts'
+ list.concat(contact_entries) unless @kind == 'members'
+ list.select! { |entry| matches?(entry) } if @query.present?
+ list.sort_by { |entry| [entry.sort_name, entry.person&.id.to_s, entry.user&.id.to_s] }
+ end
+ end
+
+ private
+
+ def member_entries
+ memberships = MembershipPolicy::Scope.new(@viewer, Membership).resolve
+ .where(organisation: @organisation, active: true)
+ .includes(user: { avatar_attachment: :blob })
+ users = memberships.filter_map(&:user)
+ linked = people.where(user_id: users.map(&:id)).index_by(&:user_id)
+ users.map do |user|
+ Entry.new(kind: :member, user: user, person: linked[user.id], sort_name: PersonName.normalize(user.display_name))
+ end
+ end
+
+ def contact_entries
+ active_member_ids = Membership.where(organisation: @organisation, active: true).select(:user_id)
+ rows = people.where(user_id: nil).or(people.where.not(user_id: active_member_ids))
+ rows.map { |person| Entry.new(kind: :contact, user: nil, person: person, sort_name: person.normalized_name) }
+ end
+
+ def people
+ @people ||= PersonPolicy::Scope.new(@viewer, Person).resolve
+ end
+
+ def matches?(entry)
+ haystack = [entry.plain_name, entry.person&.function, entry.person&.department, entry.person&.company,
+ entry.person&.email, entry.user&.email]
+ haystack.any? { |value| value.present? && PersonName.normalize(value).include?(@query) }
+ end
+ end
+end
diff --git a/app/services/user_data_exports/registry.rb b/app/services/user_data_exports/registry.rb
index 8e7a843..52aec8a 100644
--- a/app/services/user_data_exports/registry.rb
+++ b/app/services/user_data_exports/registry.rb
@@ -216,6 +216,13 @@ module UserDataExports
source(key: :chat_style_preferences, model: 'ChatStylePreference', tenant_scoped: true,
attributes: %w[technicality length created_at],
scope: ->(user) { ChatStylePreference.where(user: user) }),
+ # The people directory row linked to the account (at most one per
+ # organisation). creator_id/updater_id are authoring metadata on org
+ # content (as analysis_prompts); unlinked rows are data about third
+ # parties, whose requests go through the organisation as controller.
+ source(key: :people, model: 'Person', tenant_scoped: true,
+ attributes: %w[name function department company email phone notes created_at updated_at],
+ scope: ->(user) { Person.where(user_id: user.id) }),
source(key: :notification_subscriptions, model: 'NotificationSubscription', tenant_scoped: true,
attributes: %w[subscribable_type source created_at],
scope: ->(user) { NotificationSubscription.where(user: user) }),
diff --git a/app/views/organisations/roles/edit.html.erb b/app/views/organisations/roles/edit.html.erb
index f1d3217..cb39000 100644
--- a/app/views/organisations/roles/edit.html.erb
+++ b/app/views/organisations/roles/edit.html.erb
@@ -134,6 +134,7 @@
when 'tickets' then 'bi-ticket'
when 'users' then 'bi-people'
when 'assistant' then 'bi-chat-square-text'
+ when 'people' then 'bi-person-vcard'
else 'bi-list-check'
end %>
<i class="bi <%= category_icon %> text-xl mr-2"></i>
diff --git a/config/locales/models.de.yml b/config/locales/models.de.yml
index e8c7dab..c7521c9 100644
--- a/config/locales/models.de.yml
+++ b/config/locales/models.de.yml
@@ -2,6 +2,15 @@
de:
activerecord:
attributes:
+ person:
+ user: "Mitglied"
+ name: "Name"
+ function: "Funktion"
+ department: "Abteilung"
+ company: "Firma"
+ email: "E-Mail"
+ phone: "Telefon"
+ notes: "Notiz"
ticket_relation:
source_ticket: "Quell-Ticket"
target_ticket: "Ziel-Ticket"
@@ -67,6 +76,10 @@ de:
file: "PDF"
errors:
models:
+ person:
+ attributes:
+ user:
+ not_an_active_member: "muss ein aktives Mitglied dieser Organisation sein"
beuser:
last_active_admin: "Der letzte aktive Admin kann weder herabgestuft, deaktiviert noch gelöscht werden."
# Modellspezifisch, weil die Regel zu PriceTier gehört. Die beiden
diff --git a/config/locales/models.en.yml b/config/locales/models.en.yml
index 329309c..8cc4a6a 100644
--- a/config/locales/models.en.yml
+++ b/config/locales/models.en.yml
@@ -2,6 +2,15 @@
en:
activerecord:
attributes:
+ person:
+ user: "Member"
+ name: "Name"
+ function: "Function"
+ department: "Department"
+ company: "Company"
+ email: "Email"
+ phone: "Phone"
+ notes: "Note"
ticket_relation:
source_ticket: "Source ticket"
target_ticket: "Target ticket"
@@ -67,6 +76,10 @@ en:
file: "PDF"
errors:
models:
+ person:
+ attributes:
+ user:
+ not_an_active_member: "must be an active member of this organisation"
beuser:
last_active_admin: "The last active admin cannot be demoted, deactivated or deleted."
seat_event:
diff --git a/config/locales/views_extracted.de.yml b/config/locales/views_extracted.de.yml
index e78118c..d8f0e13 100644
--- a/config/locales/views_extracted.de.yml
+++ b/config/locales/views_extracted.de.yml
@@ -198,6 +198,10 @@ de:
Benutzer.
assistant:
use_assistant: Erlaubt die Nutzung des organisationsweiten KI-Assistenten.
+ people:
+ view_people: Erlaubt das Lesen der Personenliste der Organisation.
+ manage_people: Erlaubt das Anlegen, Bearbeiten und Löschen von Personen
+ in der Personenliste der Organisation.
none_available: Keine Beschreibung verfügbar
categories:
assistant: Assistent
@@ -206,6 +210,7 @@ de:
tickets: Tickets
meetings: Meetings
users: Benutzer
+ people: Personen
layouts:
docs:
title_with_page: "%{page} · Lalabase Docs"
diff --git a/config/locales/views_extracted.en.yml b/config/locales/views_extracted.en.yml
index 39f4713..5e6ae12 100644
--- a/config/locales/views_extracted.en.yml
+++ b/config/locales/views_extracted.en.yml
@@ -192,6 +192,10 @@ en:
view_user_full_name: Allows viewing full names of other users.
assistant:
use_assistant: Allows using the org-wide AI assistant.
+ people:
+ view_people: Allows reading the organisation's people directory.
+ manage_people: Allows adding, editing and deleting people in the
+ organisation's people directory.
none_available: No description available
categories:
assistant: Assistant
@@ -200,6 +204,7 @@ en:
tickets: Tickets
meetings: Meetings
users: Users
+ people: People
layouts:
docs:
title_with_page: "%{page} · Lalabase Docs"
diff --git a/db/migrate/20261026120000_create_people.rb b/db/migrate/20261026120000_create_people.rb
new file mode 100644
index 0000000..f73e87a
--- /dev/null
+++ b/db/migrate/20261026120000_create_people.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+# The shared people directory of an organisation: one row per person the
+# consultant and the customer keep track of together. A row may link to a member
+# (user_id); every row keeps its own name, so an unlink loses nothing.
+class CreatePeople < ActiveRecord::Migration[8.1]
+ def change
+ create_table :people, id: :uuid do |t|
+ t.references :organisation, type: :uuid, null: false, foreign_key: true, index: false
+ t.references :user, type: :uuid, null: true, foreign_key: { on_delete: :nullify }
+ t.string :name, null: false
+ t.string :normalized_name, null: false
+ t.string :function
+ t.string :department
+ t.string :company
+ t.string :email
+ t.string :phone
+ t.text :notes
+ t.references :creator, type: :uuid, null: true, index: false, foreign_key: { to_table: :users, on_delete: :nullify }
+ t.references :updater, type: :uuid, null: true, index: false, foreign_key: { to_table: :users, on_delete: :nullify }
+ t.integer :lock_version, null: false, default: 0
+ t.timestamps
+ end
+
+ add_index :people, %i[organisation_id normalized_name]
+ add_index :people, %i[organisation_id user_id], unique: true, where: 'user_id IS NOT NULL',
+ name: 'index_people_on_organisation_id_and_user_id'
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index e979906..e7f3a4b 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[8.1].define(version: 2026_10_17_120000) do
+ActiveRecord::Schema[8.1].define(version: 2026_10_26_120000) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"
enable_extension "pgcrypto"
@@ -1055,6 +1055,27 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_17_120000) do
t.index ["user_id"], name: "index_overview_configurations_on_user_id"
end
+ create_table "people", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.uuid "organisation_id", null: false
+ t.uuid "user_id"
+ t.string "name", null: false
+ t.string "normalized_name", null: false
+ t.string "function"
+ t.string "department"
+ t.string "company"
+ t.string "email"
+ t.string "phone"
+ t.text "notes"
+ t.uuid "creator_id"
+ t.uuid "updater_id"
+ t.integer "lock_version", default: 0, null: false
+ t.datetime "created_at", null: false
+ t.datetime "updated_at", null: false
+ t.index ["organisation_id", "normalized_name"], name: "index_people_on_organisation_id_and_normalized_name"
+ t.index ["organisation_id", "user_id"], name: "index_people_on_organisation_id_and_user_id", unique: true, where: "(user_id IS NOT NULL)"
+ t.index ["user_id"], name: "index_people_on_user_id"
+ end
+
create_table "permissions", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.uuid "role_id", null: false
t.string "category", null: false
@@ -2071,6 +2092,10 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_17_120000) do
add_foreign_key "outbox_events", "organisations"
add_foreign_key "overview_configurations", "organisations"
add_foreign_key "overview_configurations", "users"
+ add_foreign_key "people", "organisations"
+ add_foreign_key "people", "users", column: "creator_id", on_delete: :nullify
+ add_foreign_key "people", "users", column: "updater_id", on_delete: :nullify
+ add_foreign_key "people", "users", on_delete: :nullify
add_foreign_key "permissions", "roles"
add_foreign_key "personal_access_token_organisations", "organisations"
add_foreign_key "personal_access_token_organisations", "personal_access_tokens"
diff --git a/spec/factories/people.rb b/spec/factories/people.rb
new file mode 100644
index 0000000..9bf45fa
--- /dev/null
+++ b/spec/factories/people.rb
@@ -0,0 +1,12 @@
+# frozen_string_literal: true
+
+# Invented names only (no real people in fixtures).
+FactoryBot.define do
+ factory :person do
+ sequence(:name) { |n| "Erika Beispiel #{n}" }
+ function { 'Technischer Ansprechpartner' }
+ company { 'Beispiel GmbH' }
+ sequence(:email) { |n| "person#{n}@example.com" }
+ association :organisation
+ end
+end
diff --git a/spec/models/concerns/person_link_release_spec.rb b/spec/models/concerns/person_link_release_spec.rb
new file mode 100644
index 0000000..17c560f
--- /dev/null
+++ b/spec/models/concerns/person_link_release_spec.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# Leaving an organisation keeps the person row and drops only its link, on
+# every path that removes a membership (members page and the operator's admin
+# backend write the same table through two classes).
+RSpec.describe PersonLinkRelease, type: :model do
+ let(:organisation) { create(:organisation) }
+ let(:other_organisation) { create(:organisation) }
+ let(:admin_role) { create(:role, organisation: organisation, title: Role::ACCOUNT_ADMIN_TITLE) }
+ let(:admin) { create(:user) }
+ let(:user) { create(:user) }
+
+ before do
+ ActsAsTenant.current_tenant = organisation
+ create(:membership, user: admin, organisation: organisation, role: admin_role)
+ create(:membership, user: user, organisation: organisation)
+ create(:membership, user: user, organisation: other_organisation)
+ end
+
+ after { ActsAsTenant.current_tenant = nil }
+
+ let!(:row) { create(:person, organisation: organisation, user: user, name: 'Mia Mitglied', phone: '1') }
+ let!(:other_row) do
+ ActsAsTenant.with_tenant(other_organisation) { create(:person, organisation: other_organisation, user: user) }
+ end
+
+ it 'keeps the row and drops the link when a member is removed on the members page' do
+ membership = Membership.find_by(user: user, organisation: organisation)
+
+ expect(RemoveMembershipService.new(membership: membership, admin: User.find(admin.id)).call).to be(true)
+
+ expect(row.reload.user_id).to be_nil
+ expect([row.name, row.phone]).to eq(['Mia Mitglied', '1'])
+ expect(Person.unscoped.find(other_row.id).user_id).to eq(user.id)
+ end
+
+ it 'does the same when the operator removes the membership in the admin backend' do
+ ActsAsTenant.current_tenant = nil
+ Admin::Membership.find_by(user_id: user.id, organisation_id: organisation.id).destroy!
+
+ expect(Person.unscoped.find(row.id).user_id).to be_nil
+ expect(Person.unscoped.find(other_row.id).user_id).to eq(user.id)
+ end
+
+ it 'keeps the link when the membership is only deactivated' do
+ Membership.find_by(user: user, organisation: organisation).update!(active: false)
+
+ expect(row.reload.user_id).to eq(user.id)
+ end
+end
diff --git a/spec/models/concerns/person_trackable_spec.rb b/spec/models/concerns/person_trackable_spec.rb
new file mode 100644
index 0000000..c82300d
--- /dev/null
+++ b/spec/models/concerns/person_trackable_spec.rb
@@ -0,0 +1,100 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# A person row holds data about third parties, and its activities outlive it.
+# So no activity names the person or carries a value, nothing fans out, and a
+# delete leaves exactly one anonymous row (D6).
+RSpec.describe PersonTrackable, type: :model do
+ let(:organisation) { create(:organisation) }
+ let(:writer) { create(:user, organisation: organisation) }
+
+ before do
+ ActiveJob::Base.queue_adapter = :test
+ ActsAsTenant.current_tenant = organisation
+ Current.user = writer
+ end
+
+ after do
+ Current.user = nil
+ ActsAsTenant.current_tenant = nil
+ end
+
+ let(:secret_values) { ['Erika Geheim', '+49 30 9876543', '[email protected]', 'Nur fuer uns'] }
+
+ def create_person
+ create(:person, organisation: organisation, name: 'Erika Geheim', phone: '+49 30 9876543',
+ email: '[email protected]', notes: 'Nur fuer uns')
+ end
+
+ def serialized(activities)
+ activities.map { |a| [a.parameters, a.attribute_changes].to_json }.join
+ end
+
+ def expect_no_personal_data(activities)
+ text = serialized(activities)
+ secret_values.each { |value| expect(text).not_to include(value) }
+ end
+
+ it 'writes a created activity without a name' do
+ person = create_person
+
+ activity = Activity.find_by!(trackable: person, action: 'created')
+ expect(activity.key).to eq('person.created')
+ expect_no_personal_data([activity])
+ end
+
+ it 'keeps only the names of changed fields on update, no values' do
+ person = create_person
+ person.update!(phone: '+49 40 1111111', notes: 'Neu', name: 'Erika Neu')
+
+ activity = Activity.find_by!(trackable: person, action: 'updated')
+ expect(activity.attribute_changes.keys).to contain_exactly('phone', 'notes', 'name')
+ expect(activity.attribute_changes.values).to all(be_nil)
+ expect(serialized([activity])).not_to include('+49 40 1111111', 'Erika Neu')
+ end
+
+ it 'does not record bookkeeping columns as changes' do
+ person = create_person
+ person.update!(phone: '1')
+
+ keys = Activity.find_by!(trackable: person, action: 'updated').attribute_changes.keys
+ expect(keys).not_to include('lock_version', 'normalized_name', 'updater_id', 'updated_at')
+ end
+
+ it 'leaves exactly one anonymous deleted activity behind' do
+ person = create_person
+ person.update!(phone: '1')
+ person.destroy!
+
+ remaining = Activity.where(trackable_type: 'Person', trackable_id: person.id)
+ expect(remaining.map(&:action)).to eq(['deleted'])
+ expect(remaining.first.actor).to eq(writer)
+ expect_no_personal_data(remaining)
+ end
+
+ it 'creates no outbox event and no notification on create, update or destroy' do
+ expect do
+ person = create_person
+ person.update!(phone: '1')
+ person.destroy!
+ end.not_to(change { [OutboxEvent.count, Notification.count] })
+ end
+
+ it 'keeps the quiet context even when a caller sets its own' do
+ person = build(:person, organisation: organisation)
+ person.activity_context = { 'skip_notifications' => false, 'bulk_run_id' => 'x' }
+
+ expect(person.activity_context).to include('skip_notifications' => true, 'bulk_run_id' => 'x')
+ end
+
+ # Activity has no broadcast of its own any more (activity.rb); this pins that
+ # a person write does not start one either (no Turbo broadcast job, no job at all).
+ it 'enqueues no job, so no broadcast' do
+ expect do
+ person = create_person
+ person.update!(phone: '1')
+ person.destroy!
+ end.not_to have_enqueued_job
+ end
+end
diff --git a/spec/models/permission_spec.rb b/spec/models/permission_spec.rb
index b7cdad2..c704e14 100644
--- a/spec/models/permission_spec.rb
+++ b/spec/models/permission_spec.rb
@@ -425,4 +425,27 @@ RSpec.describe Permission, type: :model do
end
end
end
+
+ # The people directory: its own category for the same reason as :assistant,
+ # customer roles are billable: false and must be able to keep the list.
+ describe 'people category' do
+ it 'knows view_people and manage_people' do
+ expect(Permission::CATEGORIES[:people]).to eq(%w[view_people manage_people])
+ end
+
+ it 'is not on the guest ceiling list' do
+ expect(Role::FORBIDDEN_BILLABLE_FALSE_CATEGORIES).not_to include('people')
+ end
+
+ %w[view_people manage_people].each do |action|
+ it "stays grantable to a billable: false role (#{action})" do
+ ActsAsTenant.with_tenant(organisation) do
+ guest_role = create(:role, billable: false)
+ permission = build(:permission, role: guest_role, category: 'people', action: action, allowed: true)
+
+ expect(permission).to be_valid
+ end
+ end
+ end
+ end
end
diff --git a/spec/models/person_name_spec.rb b/spec/models/person_name_spec.rb
new file mode 100644
index 0000000..e92da65
--- /dev/null
+++ b/spec/models/person_name_spec.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# One normalizer for meeting participants and the people directory. The same
+# fixture pins the JS mirror (spec/javascript/meetings/name_normalizer.test.js),
+# so all three read one contract.
+RSpec.describe PersonName do
+ cases = JSON.parse(File.read(Rails.root.join('spec/fixtures/name_normalization_cases.json')))['cases']
+
+ cases.each do |c|
+ it "normalizes #{c['input'].inspect} -> #{c['expected'].inspect} (#{c['why']})" do
+ expect(described_class.normalize(c['input'])).to eq(c['expected'])
+ end
+ end
+
+ it 'treats nil as empty' do
+ expect(described_class.normalize(nil)).to eq('')
+ end
+
+ it 'is the normalizer MeetingParticipant uses (delegation, not a copy)' do
+ allow(described_class).to receive(:normalize).and_call_original
+
+ MeetingParticipant.normalize_name(' Jürgen Müller ')
+
+ expect(described_class).to have_received(:normalize).with(' Jürgen Müller ')
+ end
+end
diff --git a/spec/models/person_spec.rb b/spec/models/person_spec.rb
new file mode 100644
index 0000000..76ab281
--- /dev/null
+++ b/spec/models/person_spec.rb
@@ -0,0 +1,87 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+RSpec.describe Person, type: :model do
+ let(:organisation) { create(:organisation) }
+ let(:other_organisation) { create(:organisation) }
+
+ before { ActsAsTenant.current_tenant = organisation }
+ after { ActsAsTenant.current_tenant = nil }
+
+ def member_of(org, active: true)
+ user = create(:user)
+ create(:membership, user: user, organisation: org, active: active)
+ user
+ end
+
+ it 'is bound to the tenant' do
+ mine = create(:person, organisation: organisation)
+ theirs = ActsAsTenant.with_tenant(other_organisation) { create(:person, organisation: other_organisation) }
+
+ expect(described_class.all).to contain_exactly(mine)
+ expect(described_class.unscoped.where(id: theirs.id)).to exist
+ end
+
+ it 'requires a name' do
+ person = build(:person, organisation: organisation, name: ' ')
+
+ expect(person).not_to be_valid
+ expect(person.errors[:name]).to be_present
+ end
+
+ it 'squeezes the name and stores its normalized form' do
+ person = create(:person, organisation: organisation, name: ' Jürgen Müller ')
+
+ expect(person.name).to eq('Jürgen Müller')
+ expect(person.normalized_name).to eq('juergen mueller')
+ end
+
+ it 'refuses a malformed email and accepts none' do
+ expect(build(:person, organisation: organisation, email: 'not an address')).not_to be_valid
+ expect(build(:person, organisation: organisation, email: '')).to be_valid
+ end
+
+ describe 'the member link' do
+ it 'accepts an active member of the same organisation' do
+ expect(build(:person, organisation: organisation, user: member_of(organisation))).to be_valid
+ end
+
+ it 'refuses a member of another organisation' do
+ person = build(:person, organisation: organisation, user: member_of(other_organisation))
+
+ expect(person).not_to be_valid
+ expect(person.errors.details[:user]).to include(error: :not_an_active_member)
+ end
+
+ it 'refuses a deactivated member' do
+ person = build(:person, organisation: organisation, user: member_of(organisation, active: false))
+
+ expect(person).not_to be_valid
+ end
+
+ it 'allows at most one row per member and organisation' do
+ user = member_of(organisation)
+ create(:person, organisation: organisation, user: user)
+
+ expect(build(:person, organisation: organisation, user: user)).not_to be_valid
+ end
+
+ it 'keeps a stored link valid after the member was deactivated (only a NEW link is checked)' do
+ user = member_of(organisation)
+ person = create(:person, organisation: organisation, user: user)
+ Membership.find_by(user: user, organisation: organisation).update!(active: false)
+
+ expect(person.reload.update(phone: '+49 30 1234567')).to be(true)
+ end
+ end
+
+ it 'raises on a stale save (both sides edit the same row)' do
+ person = create(:person, organisation: organisation)
+ first = described_class.find(person.id)
+ second = described_class.find(person.id)
+ first.update!(phone: '1')
+
+ expect { second.update!(phone: '2') }.to raise_error(ActiveRecord::StaleObjectError)
+ end
+end
diff --git a/spec/models/role_spec.rb b/spec/models/role_spec.rb
index 68b52af..fb2b018 100644
--- a/spec/models/role_spec.rb
+++ b/spec/models/role_spec.rb
@@ -114,6 +114,16 @@ RSpec.describe Role, type: :model do
expect(role).to be_valid
end
+ it 'allows billable: false with people-category permissions (customer roles keep the list)' do
+ role = create(:role, billable: true)
+ create(:permission, role: role, category: 'people', action: 'view_people', allowed: true)
+ create(:permission, role: role, category: 'people', action: 'manage_people', allowed: true)
+
+ role.billable = false
+
+ expect(role).to be_valid
+ end
+
it 'does not block a non-billable role with no forbidden permissions' do
role = build(:role, billable: false)
diff --git a/spec/models/user_erasure_path_parity_spec.rb b/spec/models/user_erasure_path_parity_spec.rb
index 9766b62..10ef7b9 100644
--- a/spec/models/user_erasure_path_parity_spec.rb
+++ b/spec/models/user_erasure_path_parity_spec.rb
@@ -228,6 +228,27 @@ RSpec.describe 'Account erasure path parity', type: :model do
end
end
+ # The erasure runs BEFORE the memberships go: removing a membership drops
+ # the link (PersonLinkRelease), and without the link the step would find
+ # nothing and leave the row behind as a contact with the person's data.
+ describe 'people directory rows linked to the account' do
+ it 'deletes the linked rows in every organisation and keeps the unlinked ones' do
+ create(:membership, user: user, organisation: other_organisation)
+ linked = create(:person, organisation: organisation, user: user, phone: '1')
+ elsewhere = ActsAsTenant.with_tenant(other_organisation) do
+ create(:person, organisation: other_organisation, user: user)
+ end
+ namesake = create(:person, organisation: organisation, name: linked.name)
+
+ record.soft_delete_and_anonymize!
+
+ ActsAsTenant.without_tenant do
+ expect(Person.where(id: [linked.id, elsewhere.id])).not_to exist
+ expect(Person.where(id: namesake.id)).to exist
+ end
+ end
+ end
+
describe 'personal access tokens (access revocation)' do
it 'revokes the tokens so they stop authenticating' do
raw = create(:personal_access_token, user: user, organisations: [organisation]).token
diff --git a/spec/policies/inactive_membership_scope_guard_spec.rb b/spec/policies/inactive_membership_scope_guard_spec.rb
index 5eb7fe7..b9d6230 100644
--- a/spec/policies/inactive_membership_scope_guard_spec.rb
+++ b/spec/policies/inactive_membership_scope_guard_spec.rb
@@ -100,6 +100,22 @@ RSpec.describe 'Policy scopes and a deactivated membership', :ci_guard, type: :p
# The org-wide assistant threads have no project, so they never pass through
# accessible_project_ids. ChatPolicy::Scope keeps its own check for that branch;
# this cell is what says so out loud.
+ # The people directory has no project either: PersonPolicy::Scope asks the
+ # membership itself (PersonPolicy.view_allowed?).
+ describe 'PersonPolicy::Scope' do
+ let!(:person) { create(:person, organisation: organisation) }
+
+ it 'drops the rows once the membership is deactivated' do
+ create(:permission, role: role, category: 'people', action: 'view_people', allowed: true)
+
+ expect(PersonPolicy::Scope.new(User.find(user.id), Person).resolve).to include(person)
+
+ membership.update!(active: false)
+
+ expect(PersonPolicy::Scope.new(User.find(user.id), Person).resolve).to be_empty
+ end
+ end
+
describe 'ChatPolicy::Scope' do
let!(:org_thread) { create(:chat, user: user, organisation: organisation) }
diff --git a/spec/policies/person_policy_spec.rb b/spec/policies/person_policy_spec.rb
new file mode 100644
index 0000000..b58661b
--- /dev/null
+++ b/spec/policies/person_policy_spec.rb
@@ -0,0 +1,128 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# The people directory is a right of its own (D7): account admins without a
+# row, everyone else only with view_people / manage_people, and only while the
+# membership is active.
+RSpec.describe PersonPolicy, :ci_guard, type: :policy do
+ let(:organisation) { create(:organisation) }
+ let(:other_organisation) { create(:organisation) }
+
+ before { ActsAsTenant.current_tenant = organisation }
+ after { ActsAsTenant.current_tenant = nil }
+
+ def role_with(*actions, billable: true, title: nil)
+ role = create(:role, organisation: organisation, billable: billable, **{ title: title }.compact)
+ actions.each { |action| create(:permission, role: role, category: 'people', action: action, allowed: true) }
+ role
+ end
+
+ def member_with(role, active: true)
+ user = create(:user)
+ create(:membership, user: user, organisation: organisation, role: role, active: active)
+ User.find(user.id)
+ end
+
+ let(:admin) { member_with(role_with(title: Role::ACCOUNT_ADMIN_TITLE)) }
+ let(:viewer) { member_with(role_with('view_people')) }
+ let(:manager) { member_with(role_with('manage_people')) }
+ let(:nobody) { member_with(role_with) }
+ let(:guest_manager) { member_with(role_with('manage_people', billable: false)) }
+ let(:person) { create(:person, organisation: organisation) }
+
+ def allowed(user, record = person)
+ policy = described_class.new(user, record)
+ %i[index? show? create? update? destroy?].select { |predicate| policy.public_send(predicate) }
+ end
+
+ it 'lets an account admin do everything without a permission row' do
+ expect(Permission.where(category: 'people').exists?).to be(false)
+ expect(allowed(admin)).to eq(%i[index? show? create? update? destroy?])
+ end
+
+ it 'lets view_people read, not write' do
+ expect(allowed(viewer)).to eq(%i[index? show?])
+ end
+
+ it 'lets manage_people read, write and delete' do
+ expect(allowed(manager)).to eq(%i[index? show? create? update? destroy?])
+ end
+
+ it 'denies a member without the right' do
+ expect(allowed(nobody)).to be_empty
+ end
+
+ it 'lets a guest role (billable: false) with manage_people write' do
+ expect(allowed(guest_manager)).to eq(%i[index? show? create? update? destroy?])
+ end
+
+ it 'denies a deactivated member who still holds the right' do
+ user = member_with(role_with('manage_people'), active: false)
+
+ expect(allowed(user)).to be_empty
+ end
+
+ it 'denies a deactivated account admin' do
+ user = member_with(role_with(title: Role::ACCOUNT_ADMIN_TITLE), active: false)
+
+ expect(allowed(user)).to be_empty
+ end
+
+ it 'denies a record of another organisation' do
+ theirs = ActsAsTenant.with_tenant(other_organisation) { create(:person, organisation: other_organisation) }
+
+ expect(allowed(admin, theirs)).to eq(%i[index? create?])
+ end
+
+ describe 'Scope' do
+ let(:visible_project) { create(:project, organisation: organisation) }
+ let(:foreign_project) { create(:project, organisation: organisation) }
+ let(:colleague) { member_with(role_with) }
+ let(:stranger) { member_with(role_with) }
+
+ before do
+ create(:project_permission, user: viewer, project: visible_project, tickets_access: :read_only)
+ create(:project_permission, user: colleague, project: visible_project, tickets_access: :read_only)
+ create(:project_permission, user: stranger, project: foreign_project, tickets_access: :read_only)
+ end
+
+ def rows(user)
+ described_class::Scope.new(User.find(user.id), Person).resolve
+ end
+
+ it 'hides a row linked to a member the viewer cannot see, and keeps the rest' do
+ contact = create(:person, organisation: organisation)
+ colleague_row = create(:person, organisation: organisation, user: colleague)
+ stranger_row = create(:person, organisation: organisation, user: stranger)
+
+ expect(rows(viewer)).to contain_exactly(contact, colleague_row)
+ expect(rows(admin)).to contain_exactly(contact, colleague_row, stranger_row)
+ end
+
+ it 'denies show by id for a row linked to an invisible member' do
+ stranger_row = create(:person, organisation: organisation, user: stranger)
+
+ expect(described_class.new(User.find(viewer.id), stranger_row).show?).to be(false)
+ end
+
+ it 'shows a row linked to a former member as a contact' do
+ former_row = create(:person, organisation: organisation, user: stranger)
+ Membership.find_by(user: stranger, organisation: organisation).update!(active: false)
+
+ expect(rows(viewer)).to include(former_row)
+ end
+
+ it 'returns nothing without the right' do
+ create(:person, organisation: organisation)
+
+ expect(rows(nobody)).to be_empty
+ end
+
+ it 'never returns a row of another organisation' do
+ ActsAsTenant.with_tenant(other_organisation) { create(:person, organisation: other_organisation) }
+
+ expect(rows(admin)).to be_empty
+ end
+ end
+end
diff --git a/spec/services/actors/destroy_person_spec.rb b/spec/services/actors/destroy_person_spec.rb
new file mode 100644
index 0000000..413d9ed
--- /dev/null
+++ b/spec/services/actors/destroy_person_spec.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+RSpec.describe Actors::DestroyPerson do
+ let(:organisation) { create(:organisation) }
+ let(:writer) { create(:user, organisation: organisation) }
+
+ before { ActsAsTenant.current_tenant = organisation }
+ after { ActsAsTenant.current_tenant = nil }
+
+ it 'deletes the row and leaves one anonymous deleted activity by the writer' do
+ person = create(:person, organisation: organisation, name: 'Erika Geheim')
+
+ result = described_class.call(person: person, current_user: writer)
+
+ expect(result).to be_success
+ expect(Person.exists?(person.id)).to be(false)
+ activities = Activity.where(trackable_type: 'Person', trackable_id: person.id)
+ expect(activities.map { |a| [a.action, a.actor] }).to eq([['deleted', writer]])
+ expect(activities.first.parameters.to_json).not_to include('Erika')
+ end
+end
diff --git a/spec/services/actors/save_person_spec.rb b/spec/services/actors/save_person_spec.rb
new file mode 100644
index 0000000..7cc2a88
--- /dev/null
+++ b/spec/services/actors/save_person_spec.rb
@@ -0,0 +1,119 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+RSpec.describe Actors::SavePerson do
+ let(:organisation) { create(:organisation) }
+ let(:other_organisation) { create(:organisation) }
+ let(:admin_role) { create(:role, organisation: organisation, title: Role::ACCOUNT_ADMIN_TITLE) }
+ let(:writer) { member(role: admin_role) }
+
+ before { ActsAsTenant.current_tenant = organisation }
+ after { ActsAsTenant.current_tenant = nil }
+
+ def member(role: create(:role, organisation: organisation), active: true, org: organisation)
+ user = create(:user, first_name: 'Mia', last_name: "Mitglied#{SecureRandom.hex(2)}")
+ create(:membership, user: user, organisation: org, role: role, active: active)
+ user
+ end
+
+ def save(id: nil, **params)
+ described_class.call(organisation: organisation, params: params, current_user: writer, id: id)
+ end
+
+ it 'creates a contact with creator and updater' do
+ result = save(name: 'Erika Beispiel', function: 'IT')
+
+ expect(result).to be_success
+ person = result.resource
+ expect(person).to be_persisted
+ expect([person.creator_id, person.updater_id]).to eq([writer.id, writer.id])
+ end
+
+ it 'records the actor of the activity (Current.user from the actor)' do
+ result = save(name: 'Erika Beispiel')
+
+ expect(Activity.find_by!(trackable: result.resource, action: 'created').actor).to eq(writer)
+ end
+
+ it 'updates and moves the updater, keeping the creator' do
+ person = save(name: 'Erika Beispiel').resource
+ editor = member(role: admin_role)
+
+ result = described_class.call(organisation: organisation, params: { phone: '1', lock_version: person.lock_version },
+ current_user: editor, id: person.id)
+
+ expect(result).to be_success
+ expect(person.reload.phone).to eq('1')
+ expect([person.creator_id, person.updater_id]).to eq([writer.id, editor.id])
+ end
+
+ it 'copies the member name when a link is set' do
+ user = member
+ result = save(name: 'egal', user_id: user.id)
+
+ expect(result.resource.user).to eq(user)
+ expect(result.resource.name).to eq(user.display_name)
+ end
+
+ it 'drops a link when user_id is blank' do
+ user = member
+ person = save(name: 'x', user_id: user.id).resource
+
+ save(user_id: '', lock_version: person.lock_version, id: person.id)
+
+ expect(person.reload.user_id).to be_nil
+ expect(person.name).to eq(user.display_name)
+ end
+
+ it 'refuses a raw user_id the writer may not link (another organisation)' do
+ foreign = member(org: other_organisation)
+
+ result = save(name: 'x', user_id: foreign.id)
+
+ expect(result).not_to be_success
+ expect(Person.count).to eq(0)
+ end
+
+ it 'refuses a member the writer cannot see' do
+ viewer_role = create(:role, organisation: organisation)
+ limited_writer = member(role: viewer_role)
+ stranger = member
+ project = create(:project, organisation: organisation)
+ create(:project_permission, user: limited_writer, project: project, tickets_access: :read_only)
+
+ result = described_class.call(organisation: organisation, params: { name: 'x', user_id: stranger.id },
+ current_user: limited_writer)
+
+ expect(result).not_to be_success
+ end
+
+ it 'maps a stale save to code :stale_object and keeps the newer value' do
+ person = save(name: 'Erika Beispiel').resource
+ stale_version = person.lock_version
+ save(phone: 'first', lock_version: stale_version, id: person.id)
+
+ result = save(phone: 'second', lock_version: stale_version, id: person.id)
+
+ expect(result).not_to be_success
+ expect(result.code).to eq(:stale_object)
+ expect(person.reload.phone).to eq('first')
+ end
+
+ it 'answers not found for an id of another organisation' do
+ theirs = ActsAsTenant.with_tenant(other_organisation) { create(:person, organisation: other_organisation) }
+
+ result = save(phone: '1', id: theirs.id)
+
+ expect(result).not_to be_success
+ expect(result.code).to eq(:not_found)
+ expect(Person.unscoped.find(theirs.id).phone).to be_nil
+ end
+
+ it 'maps a validation error to a failure' do
+ result = save(name: '')
+
+ expect(result).not_to be_success
+ expect(result.code).to eq(:validation_failed)
+ end
+end
diff --git a/spec/services/people/directory_spec.rb b/spec/services/people/directory_spec.rb
new file mode 100644
index 0000000..c93ff68
--- /dev/null
+++ b/spec/services/people/directory_spec.rb
@@ -0,0 +1,102 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+RSpec.describe People::Directory, :ci_guard do
+ let(:organisation) { create(:organisation) }
+
+ before { ActsAsTenant.current_tenant = organisation }
+ after { ActsAsTenant.current_tenant = nil }
+
+ def role_with(*actions, title: nil)
+ role = create(:role, organisation: organisation, **{ title: title }.compact)
+ actions.each { |action| create(:permission, role: role, category: 'people', action: action, allowed: true) }
+ role
+ end
+
+ def member(first, last, role: role_with, active: true)
+ user = create(:user, first_name: first, last_name: last)
+ create(:membership, user: user, organisation: organisation, role: role, active: active)
+ User.find(user.id)
+ end
+
+ let(:project) { create(:project, organisation: organisation) }
+ let(:other_project) { create(:project, organisation: organisation) }
+ let(:viewer) { member('Vera', 'Viewer', role: role_with('view_people')) }
+ let(:admin) { member('Anna', 'Admin', role: role_with(title: Role::ACCOUNT_ADMIN_TITLE)) }
+ let(:colleague) { member('Carl', 'Kollege') }
+ let(:stranger) { member('Sven', 'Fremd') }
+ let!(:contact) { create(:person, organisation: organisation, name: 'Doris Dienstleister', company: 'Hosting AG') }
+
+ before do
+ create(:project_permission, user: viewer, project: project, tickets_access: :read_only)
+ create(:project_permission, user: colleague, project: project, tickets_access: :read_only)
+ create(:project_permission, user: stranger, project: other_project, tickets_access: :read_only)
+ end
+
+ def entries(user = viewer, **options)
+ described_class.new(viewer: user, organisation: organisation, **options).entries
+ end
+
+ def names(list)
+ list.map { |entry| entry.person&.name || entry.user.display_name }
+ end
+
+ it 'lists the visible members and the contacts, sorted by name' do
+ expect(names(entries)).to eq(['Carl Kollege', 'Doris Dienstleister', 'Vera Viewer'])
+ end
+
+ it 'follows MembershipPolicy::Scope: a member of a foreign project is absent for a non-admin' do
+ create(:person, organisation: organisation, user: stranger, name: 'Sven Fremd', phone: '1')
+
+ expect(names(entries)).not_to include('Sven Fremd')
+ expect(names(entries(admin))).to include('Sven Fremd')
+ end
+
+ it 'attaches the person row of a member' do
+ row = create(:person, organisation: organisation, user: colleague, name: 'Carl Kollege', function: 'Admin')
+
+ entry = entries.find { |item| item.user == colleague }
+ expect(entry).to be_member
+ expect(entry.person).to eq(row)
+ end
+
+ it 'shows a row linked to a deactivated member as a contact' do
+ row = create(:person, organisation: organisation, user: colleague, name: 'Carl Kollege')
+ Membership.find_by(user: colleague, organisation: organisation).update!(active: false)
+
+ list = entries
+ expect(list.find { |item| item.person == row }.kind).to eq(:contact)
+ expect(list.count { |item| item.user == colleague }).to eq(0)
+ end
+
+ # One directory per example: each call resolves the viewer's reach once, and
+ # Prosopite would read a second call as an N+1.
+ {
+ 'members' => ['Carl Kollege', 'Vera Viewer'],
+ 'contacts' => ['Doris Dienstleister'],
+ 'nonsense' => ['Carl Kollege', 'Doris Dienstleister', 'Vera Viewer']
+ }.each do |kind, expected|
+ it "filters by kind #{kind}" do
+ expect(names(entries(kind: kind))).to eq(expected)
+ end
+ end
+
+ {
+ 'hosting' => ['Doris Dienstleister'],
+ 'mueller' => ['Jürgen Müller'],
+ 'Müller' => ['Jürgen Müller'],
+ 'kollege' => ['Carl Kollege'],
+ 'zzz' => []
+ }.each do |query, expected|
+ it "searches the fields umlaut-insensitive (#{query})" do
+ create(:person, organisation: organisation, name: 'Jürgen Müller', company: nil)
+
+ expect(names(entries(query: query))).to eq(expected)
+ end
+ end
+
+ it 'returns nothing without the right' do
+ expect(entries(colleague)).to be_empty
+ end
+end
diff --git a/spec/support/prosopite.rb b/spec/support/prosopite.rb
index fdfbce6..b310d19 100644
--- a/spec/support/prosopite.rb
+++ b/spec/support/prosopite.rb
@@ -60,7 +60,7 @@ Prosopite.allow_stack_paths = [
'signal_count_in_organisation', # Notifications::UnreadSignals: one access-filtered count per OTHER organisation that has unread notifications at all (a grouped query decides first), bounded by the user's org count; the per-tenant loop of aggregate_org_slice, for the org switcher dot
'refresh_later', # Notifications::UnreadSignals.refresh_later: one UnreadSignalsJob per recipient of an in-app notification (fanout of a comment, bulk_transition!), bounded by the recipients of one event. The job carries limits_concurrency, and Solid Queue dispatches such jobs one by one even from perform_all_later (dispatch_all_one_by_one), so each enqueue reads its own semaphore — not a request N+1
'personal_tasks_for_org', # Dashboard::PersonalTaskRollup: one open-to-dos read per org for the cockpit roll-up (bounded by the user's org count) — the repeated identical SQL is the intentional per-tenant loop, not a per-record N+1
- 'role_permission_sync', # RolePermissionSync: one find_or_initialize_by per submitted permission when saving a role's permissions; bounded by Permission::CATEGORIES (~22 actions), not an unbounded request N+1
+ 'role_permission_sync', # RolePermissionSync: one find_or_initialize_by per submitted permission when saving a role's permissions; bounded by Permission::CATEGORIES (~30 actions), not an unbounded request N+1
'share_with', # SmartFolder#share_with, called per user by Actors::ShareSmartFolder: one find_or_initialize_by (share existence check) per user when sharing a folder with the picked set — bounded by the handful of users a person selects, each share is an independent write, not a request N+1
'create_tutorial_tickets', # Actors::SeedOnboarding: one create! per tutorial ticket (bounded by the ~4 content entries, runs once per registration) — per-record callbacks (numbering, activities) are the point, not a request N+1
'assign_to_user_as_system', # Actors::SeedOnboarding: one TicketAssignmentSync per tutorial ticket (same bounded seed loop as above)
@@ -94,6 +94,7 @@ Prosopite.allow_stack_paths = [
'open_hours_in_organisation', # TimeSessions::OpenHours (GET /api/v1/time_sessions/open): one ViewingScope resolution per ORGANISATION in a token's reach (active membership, admin check, ONE read of the time permission rows), to narrow that organisation's own bookings the way TimeSessionPolicy::Scope does. ViewingScope answers per organisation by construction, so the loop is mandatory; it is bounded by the organisations the TOKEN names, not by any record count. A frame of its own for the same reason as inbox_query_current_access below
'readable_open_hour_tickets', # TimeSessions::OpenHours: one TicketPolicy::Scope resolution plus one pluck per ORGANISATION that has a ticket on the current page (at most the organisations of the token, and at most per_page rows), the tickets the person may read. The policy scope takes one organisation as its tenant, so the loop is mandatory; a check per ROW would be the real N+1 (time_sessions_open_access_spec.rb pins it)
'inbox_query_current_access', # Notifications::InboxQuery: one project-access RESOLUTION per ORGANISATION in a token's reach, for the API and MCP notification list. Not one query — a resolution is a membership check, a role read and the service's own reads, so read this as a bundle per organisation, the same way aggregate_org_slice and export_org_slice above are bundles. AccessCheck::ProjectAccessService answers per organisation by construction, so the loop is mandatory; it is bounded by the organisations the TOKEN names (a handful), not by any record count. Deliberately a frame of its OWN rather than an entry on ProjectAccessService: silencing the service itself would blind every other caller in the app to a real N+1. What this does NOT cover, because Prosopite groups by query shape and each of them names a different column: the eight per-AREA project_permissions reads inside find_projects_with_local_permissions. Those are one OR-query's worth of work spread over eight, they cost every policy scope in the app, and they belong to ProjectAccessService, not here. The organisation lookup that used to repeat here is batched (InboxQuery#reach_organisations)
+ 'erase_person_links!', # PersonalDataErasure: one destroy per people directory row linked to the erased account, so each row leaves its anonymous person.deleted activity (PersonTrackable). At most one row per organisation the account was in (unique index), run once per erasure, never in a request
'collect_space' # Embeddings::OrphanGc sweep 3 (PR 6b): one batched delete pass per COLLECTED SPACE. Bounded by the org's retention limit (1..5, so at most four spaces past it) and run by the nightly GC, never in a request. Folding the spaces into ONE delete would save a handful of queries and cost the per-space count that the GDPR attribution log and the "no silent caps" rule both need — the repeated identical SQL IS the per-space loop, not a per-record N+1. As a REGEX this prefix also matches collect_spaces_for frames — intentional: the per-ORG decision queries (ordered_spaces, per-space counts) are the same deliberate bounded loop, and the two-org sweep-3 specs rely on that coverage
]