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.
Ruby agplai-assistantdockerdsgvogdprhotwireissue-trackerjira-alternativeknowledge-basellmmcp-servermeeting-notesopen-sourceproject-managementredmine-alternativeruby-on-railsself-hostedticketingtime-tracking
Extract People::Lookup from the assistant's people tools
Guido Boykeaaddafbae770
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.ymlindex 73d4737..06e6633 100644--- a/.github/workflows/guards.yml+++ b/.github/workflows/guards.yml@@ -325,6 +325,7 @@ jobs:spec/requests/organisations/people_spec.rbspec/services/people/directory_spec.rbspec/services/people/contacts_spec.rb+ spec/services/people/lookup_spec.rbspec/requests/organisations/people_last_contact_spec.rbspec/services/lalabase/tools/find_people_spec.rbspec/services/lalabase/tools/get_person_spec.rbdiff --git a/app/services/lalabase/CLAUDE.md b/app/services/lalabase/CLAUDE.mdindex 08929c4..9e38e4a 100644--- a/app/services/lalabase/CLAUDE.md+++ b/app/services/lalabase/CLAUDE.md@@ -22,11 +22,11 @@ Codebase-Verständnis.`:assistant` and `:assistant_with_code` only, People S3): no project and no coverage likethe help, but a right of their own. `PersonPolicy.view_allowed?` is asked inside the toolBEFORE anything is read, else `refused` (a deactivated member too). They read through- `People::Directory` only, never `Person.where`/`find`. The id is the format of- `Meetings::ParticipantLinkChoice` (`person:<uuid>` for a contact, `member:<uuid>` for a- member); unknown, foreign and invisible ids give the same `not_found`. Which fields reach- the provider is decided only in `PeopleTool.row`/`.card` (never `notes`, E2; the last- contact as date and kind, E3). Both cite type `person` (area `people`, no project, a content+ `People::Lookup` only (over `People::Directory`), never `Person.where`/`find`. The id is the+ format of `Meetings::ParticipantLinkChoice` (`person:<uuid>` for a contact, `member:<uuid>`+ for a member); unknown, foreign and invisible ids give the same `not_found`. Which fields+ reach the provider is decided only in `People::Lookup.row`/`.card` (never `notes`, E2; the+ last contact as date and kind, E3). Both cite type `person` (area `people`, no project, a contenttype): a contact by its row, a member by the account (`member_id`, the page sends it on tothe row). `find_people` cites its first five rows, or an answer drawn on the list alonewould carry no area and stay unredacted for others.diff --git a/app/services/lalabase/tools/find_people.rb b/app/services/lalabase/tools/find_people.rbindex 68b0ef6..c2d8b83 100644--- a/app/services/lalabase/tools/find_people.rb+++ b/app/services/lalabase/tools/find_people.rb@@ -19,8 +19,6 @@ module Lalabase# every reader unredacted.MAX_CITATIONS = 5- KINDS_TEXT = People::Directory::KINDS.join(', ')-# What an empty list says next, the way search_help names its second route. Measured# with a real model (28.10.2026): asked for the technical contact at a company, it# searched "Technik" among members only, found nobody and said so, while the person@@ -71,20 +69,24 @@ module Lalabaseenddef self.execute(args:, context:)- refused = refusal(context)- return refused if refused-- args = symbolized(args)- kind = args[:kind].presence&.to_s || 'all'- # The page reads an unknown kind as "all"; for the model that would be a filter it- # believes it set and did not.- return Result.invalid_input("kind must be one of: #{KINDS_TEXT}") unless People::Directory::KINDS.include?(kind)+ list(lookup(context), symbolized(args), cite: true)+ end- entries = directory(context, query: args[:query].to_s.strip, kind: kind).entries- shown = entries.first(MAX_ENTRIES)- payload = { total: entries.size, truncated: entries.size > MAX_ENTRIES, data: shown.map { |entry| row(entry) } }- payload[:next_step] = NO_MATCH_NEXT_STEP if entries.empty?- json_result(payload, citations: shown.first(MAX_CITATIONS).map { |entry| Lalabase::Citations.person(entry) })+ # The answer for a directory, shared with the MCP twin (McpFindPeople), which cites+ # nothing. People::Lookup asks the right before anything else and refuses a kind it does+ # not know: the page reads one as "all", and for the model that would be a filter it+ # believes it set and did not.+ def self.list(people, args, cite:)+ page = people.find(query: args[:query].to_s.strip, kind: args[:kind], limit: MAX_ENTRIES)+ payload = { total: page.total, truncated: page.total > MAX_ENTRIES,+ data: page.entries.map { |entry| People::Lookup.row(entry) } }+ payload[:next_step] = NO_MATCH_NEXT_STEP if page.total.zero?+ citations = cite ? page.entries.first(MAX_CITATIONS).map { |entry| Lalabase::Citations.person(entry) } : []+ json_result(payload, citations: citations)+ rescue People::Lookup::Refused+ refused+ rescue People::Lookup::InvalidArgument => e+ Result.invalid_input(e.message)endendenddiff --git a/app/services/lalabase/tools/get_person.rb b/app/services/lalabase/tools/get_person.rbindex f1b3df5..a524a94 100644--- a/app/services/lalabase/tools/get_person.rb+++ b/app/services/lalabase/tools/get_person.rb@@ -7,13 +7,11 @@ module Lalabase# the contact details are: email, phone and the additional details, for the one person the# model chose (PeopleTool.card).#- # The id resolves through the asker's People::Directory and nowhere else (never- # Person.find), so the id of another organisation, of a person the asker may not see and- # an unknown id give the same answer, word for word: nothing in it tells which ids exist.+ # The id resolves through the asker's directory (People::Lookup#entry) and nowhere else+ # (never Person.find), so the id of another organisation, of a person the asker may not see+ # and an unknown id give the same answer, word for word: nothing in it tells which ids exist.# An id of the wrong shape is invalid input, whatever it names.class GetPerson < PeopleTool- # The two kinds of id find_people hands out; the link dialog's third ("new") is none.- ADDRESSES = %i[person member].freezeINVALID_ID = 'invalid id (expected an id find_people returned, "person:<uuid>" or "member:<uuid>")'def self.tool_name@@ -41,21 +39,21 @@ module Lalabaseenddef self.execute(args:, context:)- refused = refusal(context)- return refused if refused-- raw = symbolized(args)[:id].to_s.strip- return Result.invalid_input('id is required') if raw.empty?-- choice = Meetings::ParticipantLinkChoice.parse(raw)- return Result.invalid_input(INVALID_ID) unless choice && ADDRESSES.include?(choice.kind)+ read(lookup(context), symbolized(args), cite: true)+ end- people = directory(context)- entry = choice.kind == :member ? people.member_entry(choice.id) : people.person_entry(choice.id)+ # The answer for a directory, shared with the MCP twin (McpGetPerson), which cites+ # nothing. People::Lookup#entry asks the right first, then the shape of the id.+ def self.read(people, args, cite:)+ raw = args[:id].to_s.strip+ entry = people.entry(raw)return not_found(raw) if entry.nil?- entry.last_contact = people.last_contacts_for([entry]).first- json_result(card(entry), citations: [Lalabase::Citations.person(entry)])+ json_result(People::Lookup.card(entry), citations: cite ? [Lalabase::Citations.person(entry)] : [])+ rescue People::Lookup::Refused+ refused+ rescue People::Lookup::InvalidArgument+ Result.invalid_input(raw.empty? ? 'id is required' : INVALID_ID)end# Unknown, foreign and out of reach: one answer for all three.diff --git a/app/services/lalabase/tools/people_tool.rb b/app/services/lalabase/tools/people_tool.rbindex de8461e..a16195a 100644--- a/app/services/lalabase/tools/people_tool.rb+++ b/app/services/lalabase/tools/people_tool.rb@@ -3,23 +3,23 @@module Lalabasemodule Tools# What the two tools that read the people directory share (People S3): find_people lists- # people, get_person reads one. Both read through People::Directory, the one owner of who- # sees whom, and through nothing else: no Person.where, no Person.find.+ # people, get_person reads one. Both read through People::Lookup (People S3b), the one read+ # of the directory that the MCP tools and the REST endpoints share with them: the rights,+ # the search, the id format and the field selection live there, not here. No Person.where,+ # no Person.find.#- # Rights come first: the people right (PersonPolicy.view_allowed?) is asked before anything- # is read, and its absence is a refusal the model can say out loud instead of "nobody- # found". It also asks for an ACTIVE membership, so a deactivated member who still holds the- # right is refused too. The assistant's own gates (ai_enabled, assistant_enabled, the quota)- # stay where they are; the directory has no switch of its own (decision E1).+ # Rights come first: the people right is asked before anything is read, and its absence is a+ # refusal the model can say out loud instead of "nobody found". It also asks for an ACTIVE+ # membership, so a deactivated member who still holds the right is refused too. The+ # assistant's own gates (ai_enabled, assistant_enabled, the quota) stay where they are; the+ # directory has no switch of its own (decision E1).## The directory belongs to the organisation, not to a project: like the help tools these# take no project, report no coverage and filter by no project. Their citations carry the# people area (Citations.person), which keeps an answer drawn on them with the asker.#- # Which fields reach the AI provider is decided HERE and nowhere else (row, card): name,- # salutation, function, department, company, email, phone, the additional details and the- # date of the last contact. Never the notes (decision E2): free text about a third person,- # it may hold anything, and the questions these tools are for are answered without it.+ # Which fields reach the AI provider is decided in People::Lookup.row and .card, never the+ # notes (decision E2).class PeopleTool < BaseREFUSAL = 'The asking user may not see the people directory of this organisation. Say so, ' \'and do not guess names or contact details.'@@ -30,69 +30,13 @@ module Lalabasetrueend- # The refusal without the people right, or nil.- def self.refusal(context)- return nil if PersonPolicy.view_allowed?(context.actor, context.organisation)-- Result.refused(REFUSAL, reason: :people_directory)- end-- def self.directory(context, query: nil, kind: 'all')- People::Directory.new(viewer: context.actor, organisation: context.organisation, query: query, kind: kind)- end-- # The id find_people hands out and get_person reads: "person:<uuid>" for a contact,- # "member:<uuid>" for a member. The format of the link dialog- # (Meetings::ParticipantLinkChoice), so a directory entry has one address, not two.- def self.key_for(entry)- Meetings::ParticipantLinkChoice.value_for(entry)- end-- # One row of find_people: who it is and what they do, no contact details. A member's- # name is the account's (Entry#plain_name), as on the people page.- def self.row(entry)- person = entry.person- {- id: key_for(entry),- name: entry.plain_name,- kind: entry.member? ? 'member' : 'contact',- function: person&.function,- department: person&.department,- company: person&.company,- last_contact: last_contact(entry.last_contact)- }+ # The asker's directory in the thread's organisation.+ def self.lookup(context)+ People::Lookup.new(viewer: context.actor, organisation: context.organisation)end- # The card of get_person: the row plus how to reach the person. A member's email is the- # account's, as on the people page; phone and details come from the row.- def self.card(entry)- person = entry.person- row(entry).merge(- salutation: person&.salutation,- email: entry.member? ? entry.user.email : person&.email,- phone: person&.phone,- additional_details: details(person)- )- end-- # The additional details as label and value. A detail without a label is named by its- # kind, as the people page names it by the kind's name.- def self.details(person)- list = person&.additional_details- return [] unless list.is_a?(Array)-- list.map do |raw|- detail = PersonDetail.new(raw)- { label: detail.label.presence || detail.kind, value: detail.value }- end- end-- # The last contact as date and kind only (decision E3): no meeting title, no ticket- # number, so an answer names nothing it does not cite. The date in the app's time zone.- def self.last_contact(last)- return nil if last.nil?-- { on: last.at.in_time_zone.to_date.iso8601, kind: last.kind.to_s }+ def self.refused+ Result.refused(REFUSAL, reason: :people_directory)endendenddiff --git a/app/services/people/lookup.rb b/app/services/people/lookup.rbnew file mode 100644index 0000000..98e5cc7--- /dev/null+++ b/app/services/people/lookup.rb@@ -0,0 +1,161 @@+# frozen_string_literal: true++# The one read of the people directory outside the people page (People S3b): the+# assistant's find_people and get_person, the same two tools on /api/mcp, and+# GET /api/v1/organisations/:organisation_id/people (cli_rest_plan D5: one rule, several+# adapters). An adapter chooses how many rows it shows and whether a card carries the notes,+# nothing else.+#+# Entry point: find / entry+module People+ # * Rights: PersonPolicy.view_allowed? (#allowed?), asked again by #find and #entry before+ # anything is read, so an adapter that forgets to ask still reads nothing. It asks for an+ # ACTIVE membership, so a deactivated member who still holds the right is refused too.+ # * Search: People::Directory, the page's own reach and match. The kind is checked here+ # instead of being read as "all" the way the page does: a program would believe in a+ # filter it never set.+ # * Ids: "person:<uuid>" for a contact, "member:<uuid>" for a member, the format of the link+ # dialog (Meetings::ParticipantLinkChoice), so an entry has one address everywhere. An+ # unknown id, one of another organisation and one the viewer may not see all answer nil.+ # * Fields: .row for a list, .card for one person, and nowhere else. The notes go out only+ # with notes: true, which only the REST card passes (S3b E2 B): free text about a third+ # person, never sent to an AI provider and never in a list.+ # * Tokens: .for_token, which organisations a Personal Access Token may read (S3b E1).+ #+ # The organisation's tenant is the caller's to set: the assistant runs under it, the MCP+ # tools and the REST controller set it before they call (People::Directory sets it again+ # for its own reads).+ class Lookup+ KINDS = People::Directory::KINDS+ KIND_ERROR = "kind must be one of: #{KINDS.join(', ')}".freeze+ # The two kinds of id the list hands out; the link dialog's third value ("new") is none.+ ADDRESSES = %i[person member].freeze+ ID_ERROR = 'invalid id (expected "person:<uuid>" or "member:<uuid>")'++ # The viewer may not see the directory of this organisation.+ class Refused < StandardError; end+ # An argument the lookup cannot take: an unknown kind, an id of another shape.+ class InvalidArgument < ArgumentError; end++ # entries: the entries from offset on, at most limit; total: how many matched before the cut.+ Page = Data.define(:entries, :total)++ attr_reader :organisation++ def initialize(viewer:, organisation:)+ @viewer = viewer+ @organisation = organisation+ end++ # The lookup a Personal Access Token may open, or nil (S3b E1): only for an organisation+ # whose every project the token reaches (PersonalAccessToken::Reach, nil = all projects).+ # The directory and the last contact read across the whole organisation, and a token+ # limited to some projects was meant to keep its holder to those. A token limited to+ # some projects, an organisation outside the token (an inactive membership included,+ # PersonalAccessToken#organisation_scopes), a missing one and a malformed id all answer+ # nil, so a caller tells none of them apart.+ def self.for_token(reach:, viewer:, organisation_id:)+ id = Lalabase::Uuid.dashed(organisation_id)+ return nil if id.nil? || !reach.project_ids_for(id).nil?++ organisation = Organisation.find_by(id: id)+ new(viewer: viewer, organisation: organisation) if organisation+ end++ # The one rights question of the directory, the people page's own.+ def allowed?+ PersonPolicy.view_allowed?(@viewer, @organisation)+ end++ # The entries matching query and kind, sorted by name, each with its last contact.+ def find(limit:, query: nil, kind: nil, offset: 0)+ check_allowed!+ entries = directory(query: query, kind: kind_of(kind)).entries+ Page.new(entries: entries.drop(offset).first(limit), total: entries.size)+ end++ # The entry an id names, with its last contact, or nil.+ def entry(id)+ check_allowed!+ choice = Meetings::ParticipantLinkChoice.parse(id.to_s)+ raise InvalidArgument, ID_ERROR unless choice && ADDRESSES.include?(choice.kind)++ people = directory+ found = choice.kind == :member ? people.member_entry(choice.id) : people.person_entry(choice.id)+ found&.tap { |entry| entry.last_contact = people.last_contacts_for([entry]).first }+ end++ def self.key_for(entry)+ Meetings::ParticipantLinkChoice.value_for(entry)+ end++ # One row of a list: who it is and what they do, no contact details. A member's name is+ # the account's (Entry#plain_name), as on the people page.+ def self.row(entry)+ person = entry.person+ {+ id: key_for(entry),+ name: entry.plain_name,+ kind: entry.member? ? 'member' : 'contact',+ function: person&.function,+ department: person&.department,+ company: person&.company,+ last_contact: last_contact(entry.last_contact)+ }+ end++ # The card of one person: the row plus how to reach them. A member's email is the+ # account's, as on the people page; phone, details and notes come from the row. The notes+ # as stored, nil when blank or when a member has no row.+ def self.card(entry, notes: false)+ person = entry.person+ card = row(entry).merge(+ salutation: person&.salutation,+ email: entry.member? ? entry.user.email : person&.email,+ phone: person&.phone,+ additional_details: details(person)+ )+ notes ? card.merge(notes: person&.notes.presence) : card+ end++ # The additional details as label and value. A detail without a label is named by its+ # kind, as the people page names it by the kind's name.+ def self.details(person)+ list = person&.additional_details+ return [] unless list.is_a?(Array)++ list.map do |raw|+ detail = PersonDetail.new(raw)+ { label: detail.label.presence || detail.kind, value: detail.value }+ end+ end++ # The last contact as date and kind only (S3 E3): no meeting title, no ticket number, so+ # an answer names nothing it does not cite. The date in the app's time zone.+ def self.last_contact(last)+ return nil if last.nil?++ { on: last.at.in_time_zone.to_date.iso8601, kind: last.kind.to_s }+ end++ private_class_method :details, :last_contact++ private++ def check_allowed!+ raise Refused unless allowed?+ end++ # Blank is "all"; anything else must be one of KINDS.+ def kind_of(value)+ kind = value.presence&.to_s || 'all'+ raise InvalidArgument, KIND_ERROR unless KINDS.include?(kind)++ kind+ end++ def directory(query: nil, kind: 'all')+ People::Directory.new(viewer: @viewer, organisation: @organisation, query: query, kind: kind)+ end+ end+enddiff --git a/spec/services/people/lookup_spec.rb b/spec/services/people/lookup_spec.rbnew file mode 100644index 0000000..13d254d--- /dev/null+++ b/spec/services/people/lookup_spec.rb@@ -0,0 +1,283 @@+# frozen_string_literal: true++require 'rails_helper'++# What: People::Lookup, the one read of the people directory behind the assistant's+# find_people and get_person, their MCP twins and the REST people endpoints (People S3b).+# Type: Service spec against real rows.+# Why: Three adapters read the directory through this object, so its rules are their rules:+# the people right first (nothing read without it, a deactivated member included), the+# page's own reach and search, a kind that is checked instead of read as "all", one id+# format, the field lists (a row never carries contact details or notes, a card carries+# notes only when asked) and the token rule E1 (only a token that reaches every project of+# the organisation opens its directory).+RSpec.describe People::Lookup, :ci_guard do+ let(:organisation) { create(:organisation) }+ let(:other_organisation) { create(:organisation) }++ before { ActsAsTenant.current_tenant = organisation }+ after { ActsAsTenant.current_tenant = nil }++ def role_with(*actions)+ role = create(:role, organisation: organisation)+ 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, email: "#{first.downcase}@example.com")+ create(:membership, user: user, organisation: organisation, role: role, active: active)+ User.find(user.id)+ end++ let(:project) { create(:project, organisation: organisation) }+ let(:hidden_project) { create(:project, organisation: organisation) }+ let(:viewer) { member('Vera', 'Viewer', role: role_with('view_people')) }+ let(:colleague) { member('Carl', 'Kollege') }+ let(:stranger) { member('Sven', 'Fremd') }+ let!(:contact) do+ create(:person, organisation: organisation, name: 'Doris Dienstleister', salutation: 'Frau',+ function: 'Leitung IT', department: 'Technik', company: 'Hosting AG',+ email: '[email protected]', phone: '+49 30 1234567', notes: 'Nur vormittags anrufen.',+ additional_details: [{ 'kind' => 'phone', 'label' => 'Mobil', 'value' => '+49 170 1234567' }])+ end++ before do+ create(:project_permission, user: viewer, project: project, tickets_access: :read_only, meetings_access: :read_only)+ create(:project_permission, user: colleague, project: project, tickets_access: :read_only)+ create(:project_permission, user: stranger, project: hidden_project, tickets_access: :read_only)+ end++ def lookup(user = viewer)+ described_class.new(viewer: user, organisation: organisation)+ end++ def names(page)+ page.entries.map(&:plain_name)+ end++ describe '#allowed?' do+ it 'is the people right: with view_people yes, without no' do+ expect(lookup.allowed?).to be true+ expect(lookup(colleague).allowed?).to be false+ end++ it 'holds for manage_people, which implies view_people' do+ expect(lookup(member('Mona', 'Manager', role: role_with('manage_people'))).allowed?).to be true+ end++ it 'holds for an account admin without a people row' do+ admin = member('Ada', 'Admin', role: create(:role, organisation: organisation, title: 'account_admin'))++ expect(lookup(admin).allowed?).to be true+ end++ it 'is false for a deactivated member who still holds the right' do+ Membership.find_by(user: viewer, organisation: organisation).update!(active: false)++ expect(lookup(User.find(viewer.id)).allowed?).to be false+ end+ end++ describe '#find' do+ it 'lists everyone the viewer sees, sorted by name, with the true total' do+ page = lookup.find(limit: 10)++ expect(names(page)).to eq(['Carl Kollege', 'Doris Dienstleister', 'Vera Viewer'])+ expect(page.total).to eq(3)+ end++ # The page's own search (People::Directory#matches?), not a second one.+ it 'searches as the people page does' do+ directory = People::Directory.new(viewer: viewer, organisation: organisation, query: 'techn')++ expect(names(lookup.find(query: 'techn', limit: 10))).to eq(directory.entries.map(&:plain_name))+ expect(names(lookup.find(query: 'techn', limit: 10))).to eq(['Doris Dienstleister'])+ end++ it 'filters by kind' do+ expect(names(lookup.find(kind: 'members', limit: 10))).to eq(['Carl Kollege', 'Vera Viewer'])+ expect(names(lookup.find(kind: 'contacts', limit: 10))).to eq(['Doris Dienstleister'])+ end++ it 'reads a blank kind as all' do+ expect(lookup.find(kind: '', limit: 10).total).to eq(3)+ expect(lookup.find(kind: nil, limit: 10).total).to eq(3)+ end++ # The page reads an unknown kind as "all"; a program would believe in a filter it never set.+ it 'refuses a kind it does not know, with the one wording all adapters show' do+ expect { lookup.find(kind: 'member', limit: 10) }+ .to raise_error(People::Lookup::InvalidArgument, 'kind must be one of: all, members, contacts')+ end++ it 'cuts at limit from offset, and counts what matched before the cut' do+ page = lookup.find(limit: 1, offset: 1)++ expect(names(page)).to eq(['Doris Dienstleister'])+ expect(page.total).to eq(3)+ expect(lookup.find(limit: 2, offset: 3).entries).to eq([])+ end++ it 'leaves out a member of a project the viewer cannot see, and that member\'s row' do+ create(:person, organisation: organisation, user: stranger, name: 'Sven Fremd')++ expect(names(lookup.find(limit: 10))).not_to include('Sven Fremd')+ expect(names(lookup.find(limit: 10))).to include('Doris Dienstleister')+ end++ it 'attaches the last contact to each entry' do+ meeting = create(:meeting, organisation: organisation, project: project, occurred_at: 3.days.ago)+ create(:meeting_participant, meeting: meeting, person: contact, display_name: 'Gast')++ entry = lookup.find(query: 'doris', limit: 10).entries.first++ expect(entry.last_contact.kind).to eq(:meeting)+ end++ it 'refuses without the people right, before it reads anything' do+ allow(People::Directory).to receive(:new).and_call_original++ expect { lookup(colleague).find(limit: 10) }.to raise_error(People::Lookup::Refused)+ expect(People::Directory).not_to have_received(:new)+ end++ it 'refuses the right before it looks at the kind' do+ expect { lookup(colleague).find(kind: 'member', limit: 10) }.to raise_error(People::Lookup::Refused)+ end++ it 'refuses a deactivated member who still holds the right' do+ Membership.find_by(user: viewer, organisation: organisation).update!(active: false)++ expect { lookup(User.find(viewer.id)).find(limit: 10) }.to raise_error(People::Lookup::Refused)+ end+ end++ describe '#entry' do+ it 'reads a contact by "person:<uuid>", with its last contact' do+ meeting = create(:meeting, organisation: organisation, project: project, occurred_at: 2.days.ago)+ create(:meeting_participant, meeting: meeting, person: contact, display_name: 'Gast')++ entry = lookup.entry("person:#{contact.id}")++ expect(entry.person).to eq(contact)+ expect(entry.last_contact.kind).to eq(:meeting)+ end++ it 'reads a member by "member:<uuid>", also without a row of their own' do+ entry = lookup.entry("member:#{colleague.id}")++ expect(entry).to be_member+ expect(entry.user).to eq(colleague)+ expect(entry.person).to be_nil+ end++ # Unknown, foreign and invisible: one answer, nothing tells which ids exist. Five lookups+ # in a row read the directory five times from one line, which Prosopite counts as an N+1;+ # a request reads it once.+ it 'answers nil for an unknown id, a person of another organisation and one the viewer may not see' do+ foreign = ActsAsTenant.with_tenant(other_organisation) { create(:person, organisation: other_organisation) }+ hidden_row = create(:person, organisation: organisation, user: stranger, name: 'Sven Fremd')++ Prosopite.pause do+ ["person:#{SecureRandom.uuid}", "member:#{SecureRandom.uuid}", "person:#{foreign.id}",+ "person:#{hidden_row.id}", "member:#{stranger.id}"].each do |id|+ expect(lookup.entry(id)).to be_nil, id+ end+ end+ end++ ['abc', 'person:abc', 'member:', 'new', '12345', ''].each do |id|+ it "refuses #{id.inspect} as an id of the wrong shape" do+ expect { lookup.entry(id) }.to raise_error(People::Lookup::InvalidArgument)+ end+ end++ it 'refuses without the people right, before it reads anything, whatever the id' do+ allow(People::Directory).to receive(:new).and_call_original++ expect { lookup(colleague).entry("person:#{contact.id}") }.to raise_error(People::Lookup::Refused)+ expect { lookup(colleague).entry('abc') }.to raise_error(People::Lookup::Refused)+ expect(People::Directory).not_to have_received(:new)+ end+ end++ describe '.row and .card' do+ let(:entry) { lookup.entry("person:#{contact.id}") }++ it 'gives a row who it is and what they do, never contact details or notes' do+ expect(described_class.row(entry).keys)+ .to eq(%i[id name kind function department company last_contact])+ expect(described_class.row(entry)).to include(id: "person:#{contact.id}", name: 'Doris Dienstleister', kind: 'contact')+ end++ it 'gives a card the row plus how to reach the person, without notes unless asked' do+ expect(described_class.card(entry).keys)+ .to eq(%i[id name kind function department company last_contact salutation email phone additional_details])+ expect(described_class.card(entry)).to include(email: '[email protected]', phone: '+49 30 1234567',+ additional_details: [{ label: 'Mobil', value: '+49 170 1234567' }])+ end++ it 'adds the stored notes when asked, and nothing else' do+ card = described_class.card(entry, notes: true)++ expect(card.keys - described_class.card(entry).keys).to eq([:notes])+ expect(card[:notes]).to eq('Nur vormittags anrufen.')+ end++ it 'answers blank notes and a member without a row with null notes' do+ contact.update!(notes: ' ')++ expect(described_class.card(lookup.entry("person:#{contact.id}"), notes: true)[:notes]).to be_nil+ expect(described_class.card(lookup.entry("member:#{colleague.id}"), notes: true)[:notes]).to be_nil+ end++ # As on the people page: a member's name and email are the account's, the rest is the row's.+ it 'takes a member\'s name and email from the account, the notes from the row' do+ create(:person, organisation: organisation, user: colleague, name: 'C. Kollege (alt)', email: '[email protected]',+ notes: 'Bevorzugt Mail.')++ card = described_class.card(lookup.entry("member:#{colleague.id}"), notes: true)++ expect(card).to include(id: "member:#{colleague.id}", name: 'Carl Kollege', email: '[email protected]',+ notes: 'Bevorzugt Mail.')+ end+ end++ # E1 of S3b: the directory and the last contact read across the whole organisation, so only+ # a token that reaches every project of it may open them.+ describe '.for_token' do+ let(:reach) do+ PersonalAccessToken::Reach.new(project_ids_by_organisation: { organisation.id => nil,+ other_organisation.id => [project.id] })+ end++ def for_token(organisation_id)+ described_class.for_token(reach: reach, viewer: viewer, organisation_id: organisation_id)+ end++ it 'opens the directory of an organisation whose every project the token reaches' do+ found = for_token(organisation.id)++ expect(found.organisation).to eq(organisation)+ expect(found.find(limit: 10).total).to eq(3)+ end++ it 'takes the id in any spelling the UUID format allows' do+ expect(for_token(organisation.id.upcase)&.organisation).to eq(organisation)+ expect(for_token(organisation.id.delete('-'))&.organisation).to eq(organisation)+ end++ it 'opens nothing for an organisation the token reaches only in some projects' do+ expect(for_token(other_organisation.id)).to be_nil+ end++ it 'opens nothing for an organisation outside the token, a missing one or a malformed id' do+ outside = create(:organisation)++ [outside.id, SecureRandom.uuid, 'oops', '', nil].each do |id|+ expect(for_token(id)).to be_nil, id.inspect+ end+ end+ end+end