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
feat(meetings): correct a misheard word in a meeting and learn it
Guido Boykea025ff0cf6e3
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.ymlindex 843f562..5c309d8 100644--- a/.github/workflows/guards.yml+++ b/.github/workflows/guards.yml@@ -353,6 +353,7 @@ jobs:spec/services/actors/merge_glossary_terms_spec.rbspec/services/actors/save_glossary_term_spec.rbspec/requests/organisations/glossary_spec.rb+ spec/services/actors/correct_meeting_term_spec.rbspec/requests/organisations/people_spec.rbspec/requests/organisations/shown_email_spec.rbspec/requests/user_preferences_email_visibility_spec.rbdiff --git a/app/services/actors/correct_meeting_term.rb b/app/services/actors/correct_meeting_term.rbnew file mode 100644index 0000000..4e5712c--- /dev/null+++ b/app/services/actors/correct_meeting_term.rb@@ -0,0 +1,195 @@+# frozen_string_literal: true++# app/services/actors/correct_meeting_term.rb+#+# Corrects one misheard word in the transcript of a meeting and learns it for+# the glossary of the organisation (K4b, plan §5): the heard form, the right+# form, who spoke, the project and the place.+#+# * The meeting first: its row lock in the project the request was checked+# for (Meeting#lock_in_project!; a meeting moved meanwhile is gone), then+# the right to edit it again under the lock (MeetingPolicy#update?, E2;+# closed in an archived project as every meeting write), then the digest:+# the dialog counted a transcript, and a different one now is not replaced+# (code :stale_transcript; the caller counts again and asks).+# * The place comes from the client (through Meetings::TranscriptMark) and is+# only taken where the heard form stands as an occurrence+# (Meetings::TermReplacement#at): never in a speaker label, never part of a+# longer word.+# * The transcript is written through Actors::SaveMeeting (derived text,+# search, fragments as for an edit). On "everywhere" the AI summary gets the+# same replacement; it stays in either case (keep_summary: true, the one+# exception of Meeting#invalidate_stale_summary, E4/E5).+# * The glossary, when asked: the term of the right form is found (in any+# spelling of the same normalized form) or created; one created at the same+# moment is found, not refused. Then its row lock (Glossary::TermLock: the+# meeting first, then the term, always in this order). With manage_glossary+# (GlossaryPolicy.manage_allowed?) the term is confirmed and the heard form+# too; without it a new term is proposed, a term keeps its status, and the+# heard form is a proposal, also at a confirmed term (E3): it works nowhere+# before someone with the right confirmed it. A heard form that is the term+# itself (case aside) writes no row (plan §3.2).+# * The speaker is a participant of THIS meeting, never a raw id: the person+# or the member it is linked to, or nobody.+#+# One transaction (BaseActor#call): a refusal anywhere leaves everything as it was.+module Actors+ class CorrectMeetingTerm < BaseActor+ SCOPES = %w[here everywhere].freeze++ # How many places the transcript changed, and what the glossary learnt:+ # :none (not asked), :term (the heard form is the term itself), :confirmed+ # or :proposed (the heard form's status).+ attr_reader :replaced_count, :glossary_outcome++ # place: { line_index:, char_offset:, length: } of the marked span in the+ # stored transcript. digest: SHA-256 (hex) of the transcript the dialog+ # counted. speaker_id: a meeting_participants id of this meeting, or nil.+ def initialize(meeting:, project:, heard:, correct:, scope:, place:, digest:, speaker_id:, to_glossary:,+ current_user:)+ super()+ @meeting = meeting+ @project = project+ @heard = heard.to_s+ @correct = GlossaryText.clean(correct)+ @scope = scope.to_s+ @place = place.to_h.symbolize_keys.slice(:line_index, :char_offset, :length)+ @digest = digest.to_s+ @speaker_id = speaker_id.presence+ @to_glossary = to_glossary+ @current_user = current_user+ @glossary_outcome = :none+ end++ def record+ @meeting+ end++ def perform+ refuse(:invalid_scope) unless SCOPES.include?(@scope)+ check_forms+ lock_meeting+ refuse(:stale_transcript) unless Digest::SHA256.hexdigest(@meeting.transcript.to_s) == @digest++ occurrence = marked_occurrence+ speaker = chosen_speaker+ write_meeting(occurrence)+ learn(occurrence, speaker) if @to_glossary+ end++ private++ attr_reader :current_user++ def refuse(code)+ raise ActorError.new(I18n.t("services.actors.correct_meeting_term.#{code}"), code: code)+ end++ def check_forms+ heard = @heard.strip+ refuse(:heard_invalid) if heard.empty? || heard.match?(/[\r\n]/) || heard.length > GlossaryTerm::MAX_LENGTH+ refuse(:correct_blank) if @correct.empty?+ refuse(:correct_too_long) if @correct.length > GlossaryTerm::MAX_LENGTH+ refuse(:same_form) if @correct == GlossaryText.clean(heard)+ end++ def lock_meeting+ refuse(:not_found) unless @meeting.lock_in_project!(@project.id)+ refuse(:forbidden) unless MeetingPolicy.new(current_user, @meeting).update?+ end++ def participants+ @participants ||= @meeting.meeting_participants.to_a+ end++ def replacement+ @replacement ||= Meetings::TermReplacement.new(text: @meeting.transcript, heard: @heard, participants: participants)+ end++ def marked_occurrence+ line_index, char_offset, length = @place.values_at(:line_index, :char_offset, :length)+ refuse(:place_gone) unless [line_index, char_offset, length].all?(Integer)++ replacement.at(line_index: line_index, char_offset: char_offset, length: length) || refuse(:place_gone)+ end++ def chosen_speaker+ return if @speaker_id.nil?++ participants.find { |participant| participant.id == @speaker_id } || refuse(:speaker_not_found)+ end++ def write_meeting(occurrence)+ transcript = @scope == 'everywhere' ? replacement.replace(with: @correct) : replacement.replace(with: @correct, only: occurrence)+ params = { transcript: transcript.text }+ summary = replaced_summary if @scope == 'everywhere'+ params[:generated_summary] = summary if summary++ @replaced_count = transcript.count+ saved = Actors::SaveMeeting.call(project: @project, params: params, id: @meeting.id, current_user: current_user,+ keep_summary: true)+ raise ActorError.new(saved.errors, code: saved.code) unless saved.success?++ @meeting = saved.resource+ end++ # The summary with the same replacement, or nil where the word is not in it.+ def replaced_summary+ summary = Meetings::TermReplacement.new(text: @meeting.generated_summary, heard: @heard, participants: participants)+ summary.replace(with: @correct).text if summary.count.positive?+ end++ def learn(occurrence, speaker)+ manage = GlossaryPolicy.manage_allowed?(current_user, @meeting.organisation)+ term = existing_term || create_term(manage ? 'confirmed' : 'proposed')+ Glossary::TermLock.call(term: term)+ term.update!(status: 'confirmed') if manage && !term.confirmed?+ return @glossary_outcome = :term if GlossaryText.normalize(@heard) == term.normalized_term++ TermCorrection.create!(+ organisation: @meeting.organisation, glossary_term: term, project: @meeting.project, meeting: @meeting,+ heard: @heard, line_index: occurrence.line_index, char_offset: occurrence.char_offset,+ transcript_digest: @digest, replaced_count: @replaced_count, corrected_by: current_user,+ status: manage ? 'confirmed' : 'proposed', **speaker_link(speaker)+ )+ @glossary_outcome = manage ? :confirmed : :proposed+ end++ def existing_term+ terms.find_by(normalized_term: GlossaryText.normalize(@correct))+ end++ # A term of the same form created at the same moment is that term: the+ # validation that saw it, or the unique index that caught it, finds it.+ # The insert runs in a savepoint, so the index refusal leaves the+ # transaction usable.+ def create_term(status)+ term = GlossaryTerm.new(organisation: @meeting.organisation, term: @correct, status: status, created_by: current_user)+ return term_of_the_same_form if term.invalid? && term.errors.of_kind?(:term, :taken)+ raise ActiveRecord::RecordInvalid, term if term.errors.any?++ GlossaryTerm.transaction(requires_new: true) { term.save!(validate: false) }+ term+ rescue ActiveRecord::RecordNotUnique+ term_of_the_same_form+ end++ def term_of_the_same_form+ terms.find_by!(normalized_term: GlossaryText.normalize(@correct))+ end++ def terms+ GlossaryTerm.where(organisation_id: @meeting.organisation_id)+ end++ # The person or the member a participant is linked to. A member who has+ # left the organisation is no speaker any more (TermCorrection#speaker_is_member).+ def speaker_link(speaker)+ return {} unless speaker+ return { person_id: speaker.person_id } if speaker.person_id+ return {} unless speaker.user_id && Membership.exists?(organisation_id: @meeting.organisation_id, user_id: speaker.user_id)++ { user_id: speaker.user_id }+ end+ end+enddiff --git a/config/locales/services.de.yml b/config/locales/services.de.ymlindex 81c336a..c4c75fd 100644--- a/config/locales/services.de.yml+++ b/config/locales/services.de.yml@@ -62,6 +62,18 @@ de:published_analyses_bound: "Eine veröffentlichte Analyse stützt sich auf das alte Projekt. Mach sie wieder privat, dann kannst du das Meeting verschieben."moved_meanwhile: "Das Meeting wurde gerade schon verschoben. Lade die Seite neu."suggestion_run_active: "Für das Meeting werden gerade Ticket-Vorschläge erzeugt. Versuche es gleich noch einmal."+ # Correcting a misheard word in a meeting (K4b, Actors::CorrectMeetingTerm).+ correct_meeting_term:+ not_found: "Dieses Meeting gibt es hier nicht mehr. Lade die Seite neu."+ forbidden: "Du darfst dieses Meeting nicht bearbeiten."+ stale_transcript: "Das Transkript hat sich inzwischen geändert."+ place_gone: "An der markierten Stelle steht diese Form nicht. Markiere das Wort im Transkript neu."+ speaker_not_found: "Diesen Sprecher gibt es in diesem Meeting nicht."+ heard_invalid: "Die gehörte Form muss ein Wort oder mehrere Wörter in einer Zeile sein, höchstens 255 Zeichen."+ correct_blank: "Bitte die richtige Form eingeben."+ correct_too_long: "Die richtige Form darf höchstens 255 Zeichen lang sein."+ same_form: "Die richtige Form ist dieselbe wie die gehörte."+ invalid_scope: "Bitte wählen: nur hier oder überall ersetzen."move_ticket:number_conflict: "Nummernkonflikt nach %{retries} Versuchen: %{error}"has_hierarchy: "Tickets mit Unteraufgaben oder einem übergeordneten Ticket können nicht verschoben werden."diff --git a/config/locales/services.en.yml b/config/locales/services.en.ymlindex 1d11104..f095543 100644--- a/config/locales/services.en.yml+++ b/config/locales/services.en.yml@@ -62,6 +62,18 @@ en:published_analyses_bound: "A published analysis draws on the old project. Make it private again, then you can move the meeting."moved_meanwhile: "The meeting was just moved already. Reload the page."suggestion_run_active: "Ticket suggestions are being generated for this meeting. Try again in a moment."+ # Correcting a misheard word in a meeting (K4b, Actors::CorrectMeetingTerm).+ correct_meeting_term:+ not_found: "This meeting is no longer here. Reload the page."+ forbidden: "You may not edit this meeting."+ stale_transcript: "The transcript has changed in the meantime."+ place_gone: "This form does not stand at the marked place. Mark the word in the transcript again."+ speaker_not_found: "This speaker is not part of this meeting."+ heard_invalid: "The heard form must be one or more words on one line, at most 255 characters."+ correct_blank: "Please enter the right form."+ correct_too_long: "The right form may be at most 255 characters long."+ same_form: "The right form is the same as the heard one."+ invalid_scope: "Please choose: replace only here or everywhere."move_ticket:number_conflict: "Number conflict after %{retries} retries: %{error}"has_hierarchy: "Tickets with sub-tasks or a parent ticket cannot be moved."diff --git a/spec/architecture/meeting_lock_guard_spec.rb b/spec/architecture/meeting_lock_guard_spec.rbindex 5859a80..a85b624 100644--- a/spec/architecture/meeting_lock_guard_spec.rb+++ b/spec/architecture/meeting_lock_guard_spec.rb@@ -38,6 +38,7 @@ module MeetingLockGuard}.freezeWRITERS = %w[+ app/services/actors/correct_meeting_term.rbapp/services/actors/link_meeting_participant.rbapp/services/actors/move_meeting.rbapp/services/actors/save_meeting.rb@@ -58,7 +59,8 @@ module MeetingLockGuardCONTROLLER_LOCK = 'with_meeting_in_project'# Each one is in WRITERS (checked below).- LOCKING_ACTORS = %w[Actors::SaveMeeting Actors::MoveMeeting Actors::LinkMeetingParticipant].freeze+ LOCKING_ACTORS = %w[Actors::SaveMeeting Actors::MoveMeeting Actors::LinkMeetingParticipant+ Actors::CorrectMeetingTerm].freeze# Only shrinks; every entry gives its reason.NO_MEETING_YET = {diff --git a/spec/architecture/meeting_summary_exception_guard_spec.rb b/spec/architecture/meeting_summary_exception_guard_spec.rbnew file mode 100644index 0000000..165036a--- /dev/null+++ b/spec/architecture/meeting_summary_exception_guard_spec.rb@@ -0,0 +1,56 @@+# frozen_string_literal: true++require 'rails_helper'++# What: the AI summary of a meeting survives a change of its transcript in+# one case only, a term correction (K4b, E4/E5). Meeting#invalidate_stale_summary+# skips one save after Meeting#keep_summary_for_next_save!; only+# Actors::SaveMeeting calls that, on its own instance, when its caller passes+# keep_summary: true; and only Actors::CorrectMeetingTerm passes it.+# Why: everywhere else a summary of a changed transcript must go (GDPR erasure+# consistency, review #235): a word removed from the transcript must not live+# on in the summary. An exception that a second caller can set quietly would+# undo that for whatever that caller writes.+# Not seen: a call built at run time (send, a keyword in a splatted hash+# assembled elsewhere). Those are for the person who reads the diff.+module MeetingSummaryExceptionGuard+ ROOTS = %w[app lib].freeze++ SETTER = /\bkeep_summary_for_next_save!/+ SETTERS = {+ 'app/models/meeting.rb' => 'defines it and takes it back in invalidate_stale_summary',+ 'app/services/actors/save_meeting.rb' => 'sets it on its own instance, right before the one save'+ }.freeze++ KEYWORD = /\bkeep_summary:/+ KEYWORD_USERS = {+ 'app/services/actors/save_meeting.rb' => 'takes the keyword',+ 'app/services/actors/correct_meeting_term.rb' => 'the one caller that asks for it (K4b)'+ }.freeze++ # Files whose code (not their comments) matches the pattern.+ def self.files_with(pattern)+ ROOTS.flat_map { |root| Dir[Rails.root.join(root, '**', '*.{rb,erb}')] }.filter_map do |path|+ code = File.readlines(path).reject { |line| line.strip.start_with?('#', '<%#') }.join+ Pathname(path).relative_path_from(Rails.root).to_s if code.match?(pattern)+ end.sort+ end+end++RSpec.describe 'The AI summary survives a transcript change only for a term correction', type: :architecture do+ it 'is kept for the next save only through Actors::SaveMeeting' do+ expect(MeetingSummaryExceptionGuard.files_with(MeetingSummaryExceptionGuard::SETTER))+ .to eq(MeetingSummaryExceptionGuard::SETTERS.keys.sort)+ end++ it 'is asked of Actors::SaveMeeting by Actors::CorrectMeetingTerm alone' do+ expect(MeetingSummaryExceptionGuard.files_with(MeetingSummaryExceptionGuard::KEYWORD))+ .to eq(MeetingSummaryExceptionGuard::KEYWORD_USERS.keys.sort)+ end++ it 'sees the forms a call takes, and not a comment' do+ expect('meeting.keep_summary_for_next_save! if keep').to match(MeetingSummaryExceptionGuard::SETTER)+ expect('SaveMeeting.call(id: id, keep_summary: true)').to match(MeetingSummaryExceptionGuard::KEYWORD)+ expect('keep_summary_once = 1').not_to match(MeetingSummaryExceptionGuard::KEYWORD)+ end+enddiff --git a/spec/services/actors/correct_meeting_term_spec.rb b/spec/services/actors/correct_meeting_term_spec.rbnew file mode 100644index 0000000..f457411--- /dev/null+++ b/spec/services/actors/correct_meeting_term_spec.rb@@ -0,0 +1,393 @@+# frozen_string_literal: true++require 'rails_helper'++# Correcting a misheard word in a meeting (K4b, plan §5): the transcript is+# replaced through Actors::SaveMeeting with the right to edit the meeting+# (E2); what reaches the glossary depends on the glossary right: confirmed+# with manage_glossary, a proposal without, also at a confirmed term (E3).+# On "everywhere" the AI summary gets the same replacement and stays (E4), on+# "only here" it stays as it is (E5). Invented words and names only.+RSpec.describe Actors::CorrectMeetingTerm, :ci_guard do+ let(:organisation) { create(:organisation) }++ before { ActsAsTenant.current_tenant = organisation }+ after { ActsAsTenant.current_tenant = nil }++ let(:project) { create(:project, organisation: organisation, name: 'Projekt Ahorn') }+ let(:transcript) do+ "Anna: Wir testen Lalabeis heute.\nBen: Lalabeis kann viel, sagt Anna.\nUnd Lalabeis-Konten auch."+ end+ let(:creator) { member_with(role_with) }+ let(:meeting) do+ create(:meeting, organisation: organisation, project: project, creator: creator, title: 'Abstimmung',+ transcript: transcript, generated_summary: 'Lalabeis wurde vorgestellt.')+ end+ let(:contact) { create(:person, organisation: organisation, name: 'Anna Ananas') }+ let(:ben_user) { member_with(role_with, first_name: 'Ben') }+ let!(:anna) { create(:meeting_participant, meeting: meeting, display_name: 'Anna Ananas', person: contact) }+ let!(:ben) { create(:meeting_participant, meeting: meeting, display_name: 'Ben Birne', user: ben_user) }+ let!(:carla) { create(:meeting_participant, meeting: meeting, display_name: 'Carla Kiwi') }++ let(:manager) { writer(role_with('manage_glossary')) }+ let(:writer_without_glossary) { writer(role_with('view_glossary')) }++ # The place of the second occurrence ("Ben: Lalabeis"), as TranscriptMark gives it.+ let(:place_of_ben) { { line_index: 1, char_offset: 5, length: 8 } }++ def role_with(*glossary_actions)+ role = create(:role, organisation: organisation)+ glossary_actions.each { |action| create(:permission, role: role, category: 'glossary', action: action, allowed: true) }+ role+ end++ def member_with(role, first_name: 'Max', active: true)+ user = create(:user, first_name: first_name, last_name: "Muster#{SecureRandom.hex(2)}")+ create(:membership, user: user, organisation: organisation, role: role, active: active)+ user+ end++ def writer(role, access: :read_write, in_project: project)+ member_with(role).tap do |user|+ create(:project_permission, user: user, project: in_project, meetings_access: access)+ end+ end++ def digest_of(text)+ Digest::SHA256.hexdigest(text.to_s)+ end++ def correct(user: manager, scope: 'everywhere', heard: 'Lalabeis', correct: 'Lalabase', place: place_of_ben,+ digest: digest_of(transcript), speaker_id: ben.id, to_glossary: true, on: meeting, in_project: project)+ described_class.call(meeting: on, project: in_project, heard: heard, correct: correct, scope: scope, place: place,+ digest: digest, speaker_id: speaker_id, to_glossary: to_glossary, current_user: user)+ end++ def nothing_written+ [meeting.reload.transcript, meeting.generated_summary, GlossaryTerm.count, TermCorrection.count]+ end++ describe 'the transcript' do+ it 'is replaced everywhere, never in the speaker label, through the meeting write' do+ result = correct(heard: 'Anna', correct: 'Hanna', place: { line_index: 1, char_offset: 30, length: 4 })++ expect(result).to be_success+ expect(meeting.reload.transcript)+ .to eq("Anna: Wir testen Lalabeis heute.\nBen: Lalabeis kann viel, sagt Hanna.\nUnd Lalabeis-Konten auch.")+ end++ it 'is replaced at every place on "everywhere", and says how often' do+ actor = described_class.new(meeting: meeting, project: project, heard: 'Lalabeis', correct: 'Lalabase',+ scope: 'everywhere', place: place_of_ben, digest: digest_of(transcript),+ speaker_id: ben.id, to_glossary: false, current_user: manager)++ expect(actor.call).to be_success+ expect(meeting.reload.transcript)+ .to eq("Anna: Wir testen Lalabase heute.\nBen: Lalabase kann viel, sagt Anna.\nUnd Lalabase-Konten auch.")+ expect(actor.replaced_count).to eq(3)+ end++ it 'is replaced at the marked place only on "only here"' do+ expect(correct(scope: 'here')).to be_success+ expect(meeting.reload.transcript)+ .to eq("Anna: Wir testen Lalabeis heute.\nBen: Lalabase kann viel, sagt Anna.\nUnd Lalabeis-Konten auch.")+ end++ it 'runs the derived columns and the search like an edit does (Actors::SaveMeeting)' do+ allow(EmbeddingProcessingJob).to receive(:perform_later)+ meeting.update_columns(create_embeddings: true)++ correct++ expect(meeting.reload.plain_text_version).to include('Ben: Lalabase kann viel')+ expect(EmbeddingProcessingJob).to have_received(:perform_later)+ .with(record_class: Meeting, record_id: meeting.id, fragment_association: :fragments)+ end++ it 'leaves no fragments of a meeting that is not released for search' do+ create(:fragment, fragmentable: meeting, organisation: organisation, plain_text_content: 'Lalabeis alt')++ correct++ expect(meeting.reload.fragments).to be_empty+ end+ end++ describe 'the AI summary' do+ it 'gets the same replacement and stays on "everywhere"' do+ correct++ expect(meeting.reload.generated_summary).to eq('Lalabase wurde vorgestellt.')+ end++ it 'stays as it is on "everywhere" when the word is not in it' do+ meeting.update_columns(generated_summary: 'Ein kurzes Gespräch.')++ correct++ expect(meeting.reload.generated_summary).to eq('Ein kurzes Gespräch.')+ end++ it 'stays as it is on "only here"' do+ correct(scope: 'here')++ expect(meeting.reload.generated_summary).to eq('Lalabeis wurde vorgestellt.')+ end+ end++ describe 'the glossary' do+ def learned+ TermCorrection.order(:created_at).last+ end++ it 'confirms term and form with manage_glossary' do+ correct++ term = GlossaryTerm.find_by(normalized_term: 'lalabase')+ expect([term.term, term.status, term.created_by_id]).to eq(['Lalabase', 'confirmed', manager.id])+ expect(learned).to have_attributes(heard: 'Lalabeis', status: 'confirmed', glossary_term_id: term.id)+ end++ it 'proposes a new term and its form without manage_glossary' do+ correct(user: writer_without_glossary)++ expect(GlossaryTerm.find_by(normalized_term: 'lalabase')).to be_proposed+ expect(learned).to be_proposed+ end++ it 'proposes the form at a confirmed term without manage_glossary, and leaves the term confirmed' do+ term = create(:glossary_term, organisation: organisation, term: 'Lalabase')++ correct(user: writer_without_glossary)++ expect(term.reload).to be_confirmed+ expect(learned).to have_attributes(glossary_term_id: term.id, status: 'proposed')+ end++ it 'leaves a rejected term rejected without manage_glossary, the form a proposal' do+ term = create(:glossary_term, :rejected, organisation: organisation, term: 'Lalabase')++ correct(user: writer_without_glossary)++ expect(term.reload).to be_rejected+ expect(learned).to be_proposed+ end++ it 'confirms a rejected or proposed term with manage_glossary' do+ rejected = create(:glossary_term, :rejected, organisation: organisation, term: 'Lalabase')+ proposed = create(:glossary_term, :proposed, organisation: organisation, term: 'Zirbel')++ correct+ correct(heard: 'Lalabase', correct: 'Zirbel', digest: digest_of(meeting.reload.transcript))++ expect(rejected.reload).to be_confirmed+ expect(proposed.reload).to be_confirmed+ end++ it 'counts an account admin as holding manage_glossary' do+ admin = member_with(create(:role, organisation: organisation, title: Role::ACCOUNT_ADMIN_TITLE))++ correct(user: admin)++ expect(learned).to be_confirmed+ end++ it 'refuses a deactivated member, whatever the role grants' do+ user = manager+ user.memberships.update_all(active: false)+ before = nothing_written++ expect(correct(user: user).code).to eq(:forbidden)+ expect(nothing_written).to eq(before)+ end++ it 'finds the term in another spelling of the same form' do+ term = create(:glossary_term, organisation: organisation, term: 'LalaBase')++ correct++ expect(GlossaryTerm.count).to eq(1)+ expect(learned.glossary_term_id).to eq(term.id)+ end++ it 'writes the place, the count, the origin and who corrected' do+ correct++ expect(learned).to have_attributes(+ project_id: project.id, meeting_id: meeting.id, line_index: 1, char_offset: 5,+ transcript_digest: digest_of(transcript), replaced_count: 3, corrected_by_id: manager.id+ )+ end++ it 'writes the place of the mark and a count of one on "only here"' do+ correct(scope: 'here')++ expect(learned).to have_attributes(line_index: 1, char_offset: 5, replaced_count: 1)+ end++ it 'writes the transcript only when not asked to learn' do+ expect(correct(to_glossary: false)).to be_success+ expect([GlossaryTerm.count, TermCorrection.count]).to eq([0, 0])+ expect(meeting.reload.transcript).to include('Lalabase')+ end++ # Plan §3.2: a heard form that is the term (case aside) is no misheard form.+ it 'writes no heard form that is the term itself, case aside' do+ meeting.update_columns(transcript: 'Ben: lalabase ist gut.')++ result = correct(heard: 'lalabase', correct: 'Lalabase', place: { line_index: 0, char_offset: 5, length: 8 },+ digest: digest_of('Ben: lalabase ist gut.'))++ expect(result).to be_success+ expect(meeting.reload.transcript).to eq('Ben: Lalabase ist gut.')+ expect(GlossaryTerm.pluck(:term)).to eq(['Lalabase'])+ expect(TermCorrection.count).to eq(0)+ end++ # Two corrections create the same term at once: the second insert meets+ # the unique index (or the validation that saw the first), and finds the+ # first term instead of failing.+ it 'finds a term created at the same moment instead of failing' do+ other = create(:glossary_term, organisation: organisation, term: 'Lalabase')+ allow_any_instance_of(described_class).to receive(:existing_term).and_return(nil)++ expect(correct).to be_success+ expect(learned.glossary_term_id).to eq(other.id)+ end++ it 'finds a term the unique index reports, past a validation that did not see it' do+ other = create(:glossary_term, organisation: organisation, term: 'Lalabase')+ allow_any_instance_of(described_class).to receive(:existing_term).and_return(nil)+ allow_any_instance_of(GlossaryTerm).to receive(:term_not_taken)++ expect(correct).to be_success+ expect(learned.glossary_term_id).to eq(other.id)+ end++ it 'locks the meeting before the term' do+ expect(meeting).to receive(:lock_in_project!).ordered.and_call_original+ expect(Glossary::TermLock).to receive(:call).ordered.and_call_original++ correct+ end+ end++ describe 'the speaker' do+ def learned+ TermCorrection.order(:created_at).last+ end++ it 'is the member a participant is linked to' do+ correct(speaker_id: ben.id)++ expect(learned).to have_attributes(user_id: ben_user.id, person_id: nil)+ end++ it 'is the person of the directory a participant is linked to' do+ correct(speaker_id: anna.id)++ expect(learned).to have_attributes(user_id: nil, person_id: contact.id)+ end++ it 'stays empty for a participant without a link, and for none' do+ correct(scope: 'here', speaker_id: carla.id)+ first = learned+ correct(scope: 'here', place: { line_index: 0, char_offset: 17, length: 8 }, speaker_id: nil,+ digest: digest_of(meeting.reload.transcript))++ second = learned++ expect([first.user_id, first.person_id, second.user_id, second.person_id]).to eq([nil, nil, nil, nil])+ end++ it 'stays empty for a member who left the organisation' do+ ben_user.memberships.destroy_all++ correct(speaker_id: ben.id)++ expect(learned.user_id).to be_nil+ end++ it 'is refused when it is a participant of another meeting' do+ other_meeting = create(:meeting, organisation: organisation, project: project, creator: creator)+ stranger = create(:meeting_participant, meeting: other_meeting, display_name: 'Fremde Feige')+ before = nothing_written++ result = correct(speaker_id: stranger.id)++ expect(result).not_to be_success+ expect(result.code).to eq(:speaker_not_found)+ expect(nothing_written).to eq(before)+ end+ end++ describe 'refusals, with nothing written' do+ it 'refuses a transcript that changed since the dialog counted' do+ before = nothing_written++ result = correct(digest: digest_of("#{transcript} anders"))++ expect(result.code).to eq(:stale_transcript)+ expect(nothing_written).to eq(before)+ end++ it 'refuses a user without the right to edit the meeting' do+ reader = writer(role_with('manage_glossary'), access: :read_only)+ before = nothing_written++ expect(correct(user: reader).code).to eq(:forbidden)+ expect(nothing_written).to eq(before)+ end++ it 'refuses in an archived project, as every meeting write' do+ user = manager+ project.update_columns(archived_at: Time.current)+ before = nothing_written++ expect(correct(user: user).code).to eq(:forbidden)+ expect(nothing_written).to eq(before)+ end++ # lock_in_project! answers false: a move committed between the rights check+ # and the lock, and this project was the one the request was checked for.+ it 'refuses a meeting that moved out of the project meanwhile' do+ user = manager+ allow(meeting).to receive(:lock_in_project!).and_return(false)+ before = nothing_written++ expect(correct(user: user).code).to eq(:not_found)+ expect(nothing_written).to eq(before)+ end++ it 'refuses a place where the form does not stand' do+ expect(correct(place: { line_index: 1, char_offset: 20, length: 4 }).code).to eq(:place_gone)+ expect(correct(place: { line_index: 9, char_offset: 0, length: 8 }).code).to eq(:place_gone)+ end++ it 'refuses a mark inside the speaker label' do+ expect(correct(heard: 'Ben', correct: 'Benno', place: { line_index: 1, char_offset: 0, length: 3 }).code)+ .to eq(:place_gone)+ end++ it 'refuses a blank, an unchanged or an overlong correct form, and a heard form over a line break' do+ expect(correct(correct: ' ').code).to eq(:correct_blank)+ expect(correct(correct: 'Lalabeis').code).to eq(:same_form)+ expect(correct(correct: 'x' * (GlossaryTerm::MAX_LENGTH + 1)).code).to eq(:correct_too_long)+ expect(correct(heard: "Lala\nbeis").code).to eq(:heard_invalid)+ expect(correct(heard: ' ').code).to eq(:heard_invalid)+ end++ it 'refuses an unknown scope' do+ expect(correct(scope: 'somewhere').code).to eq(:invalid_scope)+ end++ it 'leaves the glossary as it was when the meeting write fails' do+ allow(Actors::SaveMeeting).to receive(:call).and_return(+ Actors::BaseActor::Result.new(success: false, errors: ['zu groß'], code: :validation_failed)+ )++ expect(correct.code).to eq(:validation_failed)+ expect([GlossaryTerm.count, TermCorrection.count]).to eq([0, 0])+ end+ end+end