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): mark a word in the transcript and correct it in a dialog
Guido Boykecfccd320b47f
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.ymlindex 5c309d8..a0b0285 100644--- a/.github/workflows/guards.yml+++ b/.github/workflows/guards.yml@@ -354,6 +354,7 @@ jobs:spec/services/actors/save_glossary_term_spec.rbspec/requests/organisations/glossary_spec.rbspec/services/actors/correct_meeting_term_spec.rb+ spec/requests/organisations/meeting_term_corrections_spec.rbspec/requests/organisations/people_spec.rbspec/requests/organisations/shown_email_spec.rbspec/requests/user_preferences_email_visibility_spec.rbdiff --git a/app/assets/stylesheets/application.css b/app/assets/stylesheets/application.cssindex e58fbad..455c45c 100644--- a/app/assets/stylesheets/application.css+++ b/app/assets/stylesheets/application.css@@ -19,6 +19,7 @@*= require components/filter_bar*= require components/column_picker*= require components/ticket_meeting_panel+ *= require components/transcript_correction*= require components/sidebar_nav*= require components/mobile_app*/diff --git a/app/assets/stylesheets/components/transcript_correction.css b/app/assets/stylesheets/components/transcript_correction.cssnew file mode 100644index 0000000..e522ccb--- /dev/null+++ b/app/assets/stylesheets/components/transcript_correction.css@@ -0,0 +1,30 @@+/*+ * Correcting a misheard word in the transcript of a meeting (K4b).+ *+ * .transcript-correct: the "Korrigieren" button over a mark. It stands in the+ * transcript section (.transcript-section, position: relative), and+ * transcript_selection_controller places it above the mark, below it on a touch+ * screen, where the system's own menu takes the space above. Hidden (Tailwind's+ * .hidden) while there is no mark; the second rule keeps it hidden against the+ * display of the first.+ *+ * .term-correction-modal: the width of the dialog's card.+ */+.transcript-correct {+ position: absolute;+ top: 0;+ left: 0;+ z-index: 20;+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+ white-space: nowrap;+}++.transcript-correct.hidden {+ display: none;+}++.term-correction-modal {+ max-width: 28rem;+}diff --git a/app/controllers/organisations/meeting_term_corrections_controller.rb b/app/controllers/organisations/meeting_term_corrections_controller.rbnew file mode 100644index 0000000..507b4d0--- /dev/null+++ b/app/controllers/organisations/meeting_term_corrections_controller.rb@@ -0,0 +1,209 @@+# frozen_string_literal: true++# Correcting a misheard word in the transcript of a meeting (K4b, plan §5):+# new renders the dialog into its frame (README_MODAL_PATTERN.md), count+# redraws the count of one opening when the heard form changes, create+# corrects (Actors::CorrectMeetingTerm) and answers with streams: the+# transcript, the summary, this opening removed, a flash with the number.+#+# What the browser sends is a mark (what the reader marked, a little of the+# text around it, its offset in the text the page shows) and the digest of the+# transcript it saw. The place in the stored transcript is the server's+# (Meetings::TranscriptMark, through Meetings::TermCorrectionDialog); a digest+# that is no longer the stored one is counted again and asked again, never+# replaced.+#+# Rights, before anything is read or written, all three actions alike:+# 1. write on meetings in the project of the route: the area gate of+# ProjectController (every action here is a meeting write);+# 2. MeetingPolicy#update? on the meeting, found inside that project;+# 3. what the dialog offers of the glossary: suggestions with view_glossary,+# the box "take over" with manage_glossary, "propose" without (E2).+# A denial answers 403, a meeting of another project 404 (another+# organisation: 404 from Organisations::BaseController).+module Organisations+ class MeetingTermCorrectionsController < Organisations::BaseController+ include ProjectController++ # The token of one dialog opening, echoed by its form and its count.+ MODAL_TOKEN = /\A\h{16}\z/+ MARK_KEYS = %i[text before after].freeze+ NOT_FOUND_CODES = %i[not_found].freeze+ FORBIDDEN_CODES = %i[forbidden].freeze+ # The actor's refusals that come from a changed transcript: count again.+ RECOUNT_CODES = %i[stale_transcript].freeze++ rescue_from Pundit::NotAuthorizedError, with: :render_forbidden++ before_action :read_modal_token+ before_action :set_meeting+ before_action :authorize_correction++ def new+ @modal_token = SecureRandom.hex(8)+ @dialog = build_dialog(heard: nil)+ render layout: false+ end++ def count+ @dialog = build_dialog(heard: heard_param)+ render partial: 'organisations/meeting_term_corrections/count',+ locals: { meeting: @meeting, token: @modal_token || SecureRandom.hex(8), dialog: @dialog }+ end++ def create+ @dialog = build_dialog(heard: heard_param)+ return refused(notice: :recounted) if @dialog.recounted?+ return refused(errors: [mark_error_text(@dialog)]) unless @dialog.correctable?++ actor = Actors::CorrectMeetingTerm.new(**correction_arguments)+ result = actor.call+ return corrected(actor) if result.success?++ refused_by_actor(result)+ end++ private++ # ProjectController derives the area from the controller name, which is no+ # area, and every action here is a write: the dialog offers only that.+ def determine_access_area+ :meetings+ end++ def determine_required_action+ :write+ end++ # The area gate answers like Pundit here: 403, not a redirect into the frame.+ def handle_access_denied(_area)+ render_forbidden+ end++ def read_modal_token+ @modal_token = scalar_param(:modal_token).to_s[MODAL_TOKEN]+ end++ # Inside the project of the route: a meeting of another project or+ # organisation is not found, as is one moved or deleted meanwhile.+ def set_meeting+ @meeting = @project.meetings.find_by(id: params[:meeting_id].to_s)+ render_not_found unless @meeting+ end++ def authorize_correction+ authorize @meeting, :update?+ end++ def participants+ @participants ||= @meeting.meeting_participants.in_row_order.to_a+ end++ def build_dialog(heard:)+ Meetings::TermCorrectionDialog.new(+ transcript: @meeting.transcript, participants: participants, mark: mark_param, heard: heard,+ displayed_html: helpers.meeting_transcript_html(@meeting, participants), digest: scalar_param(:digest)+ )+ end++ def correction_arguments+ fields = correction_fields+ { meeting: @meeting, project: @project, heard: @dialog.heard, correct: fields[:correct].to_s,+ scope: scalar_param(:scope).to_s, place: @dialog.place, digest: scalar_param(:digest).to_s,+ speaker_id: fields[:speaker_id], to_glossary: fields[:to_glossary] != '0', current_user: current_user }+ end++ # The transcript, drawn again in full (the reader was looking at the place),+ # the summary (replaced on "everywhere"), this opening gone, the flash.+ def corrected(actor)+ @meeting = actor.record+ @participants = @meeting.meeting_participants.in_row_order.to_a+ @summary_replaced = actor.summary_replaced?+ @flash_message = { notice: corrected_message(actor) }+ render 'organisations/meeting_term_corrections/corrected', formats: :turbo_stream+ end++ def corrected_message(actor)+ key = 'views.organisations.meetings.term_correction.flash'+ outcome = { confirmed: "#{key}.confirmed", proposed: "#{key}.proposed" }[actor.glossary_outcome]+ [t("#{key}.replaced", count: actor.replaced_count), (t(outcome) if outcome)].compact.join(' ')+ end++ def refused_by_actor(result)+ return render_not_found(result.errors) if NOT_FOUND_CODES.include?(result.code)+ return render_forbidden if FORBIDDEN_CODES.include?(result.code)+ return refused(notice: :recounted, reload: true) if RECOUNT_CODES.include?(result.code)++ refused(errors: result.errors)+ end++ # The dialog again, in place of the opening that sent it, with what was+ # typed, counted against the transcript stored now.+ def refused(errors: [], notice: nil, reload: false)+ @meeting.reload if reload+ @dialog = build_dialog(heard: heard_param) if reload+ @errors = errors+ @notice = notice+ @fields = correction_fields+ render 'organisations/meeting_term_corrections/refused', formats: :turbo_stream, status: :unprocessable_content+ end++ def mark_error_text(dialog)+ return t("views.organisations.meetings.term_correction.mark_errors.#{dialog.mark_error}") if dialog.mark_error++ t('services.actors.correct_meeting_term.place_gone')+ end++ def render_forbidden+ skip_authorization+ if turbo_frame_request?+ render html: helpers.turbo_frame_tag(request.headers['Turbo-Frame']) {+ helpers.tag.p(t('shared.errors.not_authorized'), class: 'term-correction-gone text-sm text-red-800', role: 'alert')+ }, layout: false, status: :forbidden+ else+ render plain: t('shared.errors.not_authorized'), status: :forbidden+ end+ end++ # The meeting is not in this project (another one, moved or deleted): the+ # frame says so, a stream closes this opening with a flash. Nothing of the+ # meeting is drawn: it may be in a project this request was not checked for.+ def render_not_found(errors = [t('services.actors.correct_meeting_term.not_found')])+ skip_authorization+ @meeting_id = params[:meeting_id].to_s+ @errors = errors+ if turbo_frame_request?+ render 'organisations/meeting_term_corrections/not_found', layout: false, status: :not_found+ else+ render 'organisations/meeting_term_corrections/gone', formats: :turbo_stream, status: :not_found+ end+ end++ # The mark as the browser sent it: three strings and a whole number.+ def mark_param+ raw = params[:mark]+ raw = raw.respond_to?(:to_unsafe_h) ? raw.to_unsafe_h : {}+ mark = MARK_KEYS.index_with { |key| raw[key.to_s].is_a?(String) ? raw[key.to_s] : '' }+ mark[:offset] = raw['offset'].is_a?(String) ? Integer(raw['offset'], 10, exception: false) : nil+ mark+ end++ def heard_param+ value = correction_fields[:heard]+ value.is_a?(String) ? value : nil+ end++ # The fields of the form, each a string or nil.+ def correction_fields+ raw = params[:term_correction]+ raw = raw.respond_to?(:to_unsafe_h) ? raw.to_unsafe_h : {}+ %w[heard correct speaker_id to_glossary].to_h { |key| [key.to_sym, (raw[key] if raw[key].is_a?(String))] }+ end++ # A nested or repeated parameter is no value here.+ def scalar_param(key)+ value = params[key]+ value.is_a?(String) ? value : nil+ end+ end+enddiff --git a/app/helpers/meeting_term_corrections_helper.rb b/app/helpers/meeting_term_corrections_helper.rbnew file mode 100644index 0000000..fc38cc9--- /dev/null+++ b/app/helpers/meeting_term_corrections_helper.rb@@ -0,0 +1,50 @@+# frozen_string_literal: true++# Correcting a misheard word in the transcript of a meeting (K4b,+# Organisations::MeetingTermCorrectionsController). The ids are a shared+# contract between the transcript section, the dialog, its count and the+# controller's streams: they live here once, by the meeting's id (an answer for+# a meeting that is gone from this project has only the id of its route).+module MeetingTermCorrectionsHelper+ # The transcript block of the meeting page; a correction redraws it.+ def meeting_transcript_section_id(meeting)+ dom_id(meeting, :transcript)+ end++ # The frame the dialog loads into, beside the transcript block.+ def term_correction_modal_id(meeting_id)+ "meeting-term-correction-modal-#{meeting_id}"+ end++ # One opening of the dialog: a refused correction replaces exactly it, a+ # correction removes it, a late answer to a dialog closed meanwhile finds nothing.+ def term_correction_modal_instance_id(meeting_id, token)+ "#{term_correction_modal_id(meeting_id)}-#{token}"+ end++ # The count of one opening and its buttons, reloaded when the heard form changes.+ def term_correction_count_id(meeting_id, token)+ "meeting-term-correction-count-#{meeting_id}-#{token}"+ end++ # The button over the mark: it opens the dialog, and the focus goes back to it.+ def term_correction_trigger_id(meeting_id)+ "meeting-term-correction-trigger-#{meeting_id}"+ end++ # The digest the page shows the transcript in: the dialog counts against it+ # and a correction refuses another (Actors::CorrectMeetingTerm).+ def meeting_transcript_digest(meeting)+ Digest::SHA256.hexdigest(meeting.transcript.to_s)+ end++ # The terms the dialog suggests while typing: the glossary of the+ # organisation without rejected terms, only for a reader of the glossary+ # (view_glossary, E2), at most Meetings::TermCorrectionDialog::SUGGESTIONS.+ def term_correction_suggestions+ return [] unless GlossaryPolicy.view_allowed?(current_user, current_organisation)++ policy_scope(GlossaryTerm).where.not(status: 'rejected').order(:normalized_term, :id)+ .limit(Meetings::TermCorrectionDialog::SUGGESTIONS).pluck(:term)+ end+enddiff --git a/app/javascript/controllers/term_correction_modal_controller.js b/app/javascript/controllers/term_correction_modal_controller.jsnew file mode 100644index 0000000..80254b0--- /dev/null+++ b/app/javascript/controllers/term_correction_modal_controller.js@@ -0,0 +1,39 @@+import TicketRelationModalController from "controllers/ticket_relation_modal_controller"+import { countQuery, withQuery } from "transcript_mark"++/**+ * Term Correction Modal Controller+ *+ * The dialog "Begriff korrigieren" beside the transcript of a meeting (K4b, markup in+ * organisations/meeting_term_corrections/_modal.html.erb). The same frame-content modal as the+ * ticket relation modal, so it IS that controller: opening on connect, one id per opening,+ * focus trap, closing on the backdrop and on Escape, the focus back to the button over the+ * mark. What it adds: the focus on the right form, and the count of the heard form, asked+ * again (meeting_term_corrections#count, its own frame) once its typing rests.+ */+export default class extends TicketRelationModalController {+ static targets = ["card", "form", "heard", "correct"]+ static values = { countUrl: String, countFrame: String, countDelay: { type: Number, default: 250 } }++ connect() {+ super.connect()+ if (!this.discarded && this.hasCorrectTarget) this.correctTarget.focus()+ }++ disconnect() {+ clearTimeout(this.timer)+ super.disconnect()+ }++ recount() {+ clearTimeout(this.timer)+ this.timer = setTimeout(() => this.reloadCount(), this.countDelayValue)+ }++ reloadCount() {+ const frame = document.getElementById(this.countFrameValue)+ if (!frame || !this.hasFormTarget) return++ frame.src = withQuery(this.countUrlValue, countQuery(new FormData(this.formTarget).entries()))+ }+}diff --git a/app/javascript/controllers/transcript_selection_controller.js b/app/javascript/controllers/transcript_selection_controller.jsnew file mode 100644index 0000000..545c971--- /dev/null+++ b/app/javascript/controllers/transcript_selection_controller.js@@ -0,0 +1,92 @@+import { Controller } from "@hotwired/stimulus"+import { buildMark, markQuery, withQuery } from "transcript_mark"++/**+ * Transcript Selection Controller+ *+ * The transcript of a meeting page for someone who may edit the meeting (K4b, plan §5.1):+ * a mark in it (a double click, a drag, a long press on a phone) shows "Korrigieren" over it.+ * The button is a link into the dialog's frame (README_MODAL_PATTERN.md); this controller only+ * keeps its address current: the mark, a little of the text around it, its offset in the text+ * the page shows, and the digest of the transcript (lib/transcript_mark.js). Where the mark+ * lies in the stored transcript is the server's to find, never a position of this page: the+ * page shows Markdown.+ *+ * On a touch screen the system's own menu (copy, look up) stands above the mark, so the button+ * goes below it there. A mousedown on the button keeps the mark (it would collapse it first).+ *+ * Mounted by organisations/meetings/_transcript_section, never in the panel beside a ticket.+ */+export default class extends Controller {+ static targets = ["content", "button"]+ // context, maxLength: Meetings::TranscriptMark::CONTEXT_LENGTH and GlossaryTerm::MAX_LENGTH.+ static values = { url: String, digest: String, context: { type: Number, default: 40 }, maxLength: { type: Number, default: 255 } }++ connect() {+ this.follow = this.follow.bind(this)+ document.addEventListener("selectionchange", this.follow)+ }++ disconnect() {+ document.removeEventListener("selectionchange", this.follow)+ clearTimeout(this.timer)+ }++ // A drag changes the selection at every step: the button follows once it rests.+ follow() {+ clearTimeout(this.timer)+ this.timer = setTimeout(() => this.place(), 120)+ }++ place() {+ const root = this.textRoot()+ const selection = window.getSelection()+ if (!root || !selection || selection.rangeCount === 0 || selection.isCollapsed) return this.hide()++ const range = selection.getRangeAt(0)+ if (!root.contains(range.startContainer) || !root.contains(range.endContainer)) return this.hide()++ const mark = buildMark(this.pieces(root, range), { context: this.contextValue, maxLength: this.maxLengthValue })+ if (!mark) return this.hide()++ this.buttonTarget.href = withQuery(this.urlValue, markQuery(mark, this.digestValue))+ this.show(range)+ }++ // The text before, inside and after the mark, as the browser holds it: text nodes in order,+ // which is what the server reads out of the same HTML.+ pieces(root, range) {+ const before = document.createRange()+ before.selectNodeContents(root)+ before.setEnd(range.startContainer, range.startOffset)+ const after = document.createRange()+ after.selectNodeContents(root)+ after.setStart(range.endContainer, range.endOffset)+ return { prefix: before.toString(), selected: range.toString(), suffix: after.toString() }+ }++ // The prose block of Neo::MarkdownPreviewComponent, with or without its clamp.+ textRoot() {+ return this.hasContentTarget ? this.contentTarget.querySelector(".md-preview") : null+ }++ show(range) {+ const button = this.buttonTarget+ button.classList.remove("hidden")+ const mark = range.getBoundingClientRect()+ const host = this.element.getBoundingClientRect()+ const touch = window.matchMedia("(pointer: coarse)").matches+ const top = touch ? mark.bottom - host.top + 8 : mark.top - host.top - button.offsetHeight - 6+ const left = Math.min(Math.max(mark.left - host.left, 0), Math.max(host.width - button.offsetWidth, 0))+ button.style.top = `${Math.max(top, 0)}px`+ button.style.left = `${left}px`+ }++ hide() {+ if (this.hasButtonTarget) this.buttonTarget.classList.add("hidden")+ }++ keepSelection(event) {+ event.preventDefault()+ }+}diff --git a/app/javascript/lib/transcript_mark.js b/app/javascript/lib/transcript_mark.jsnew file mode 100644index 0000000..7b34c09--- /dev/null+++ b/app/javascript/lib/transcript_mark.js@@ -0,0 +1,57 @@+// What the "Korrigieren" button over the transcript sends for a mark of the+// reader (K4b): the marked text, a little of the text the page shows before+// and after it, and how many characters of that text stand before it. The+// server finds the place in the stored transcript from these+// (Meetings::TranscriptMark) and refuses what it cannot place; this only cuts+// the pieces and decides whether the button shows at all.+//+// Characters, not UTF-16 units: Ruby counts code points, and an emoji before+// the mark would shift the offset by one per emoji otherwise. The context and+// the longest mark come from the page (Meetings::TranscriptMark::CONTEXT_LENGTH,+// GlossaryTerm::MAX_LENGTH), never as numbers of their own here.++// prefix, selected, suffix: the text of the transcript before, inside and+// after the mark, as the browser holds it (Range#toString). null when there is+// nothing to correct: a blank mark, one over a line break, one too long.+export function buildMark({ prefix, selected, suffix }, { context, maxLength }) {+ const text = String(selected ?? "")+ const core = text.trim()+ if (core === "" || /[\r\n]/.test(core) || [...core].length > maxLength) return null++ const start = text.indexOf(core)+ const before = [...(String(prefix ?? "") + text.slice(0, start))]+ const after = [...(text.slice(start + core.length) + String(suffix ?? ""))]+ return {+ text: core,+ before: before.slice(Math.max(before.length - context, 0)).join(""),+ after: after.slice(0, context).join(""),+ offset: before.length+ }+}++// The query of the dialog's address for a mark and the digest of the+// transcript the page shows.+export function markQuery(mark, digest) {+ const query = new URLSearchParams()+ for (const key of ["text", "before", "after", "offset"]) query.append(`mark[${key}]`, String(mark[key]))+ query.append("digest", digest)+ return query.toString()+}++// The fields of the dialog its count is asked with, out of the form's entries+// ([name, value] pairs): the mark, the digest, the opening and the heard form.+// Nothing else, the authenticity token least of all: a GET puts it in the address.+const COUNT_FIELDS = /^(?:mark\[(?:text|before|after|offset)\]|digest|modal_token|term_correction\[heard\])$/++export function countQuery(entries) {+ const query = new URLSearchParams()+ for (const [name, value] of entries) {+ if (COUNT_FIELDS.test(name) && typeof value === "string") query.append(name, value)+ }+ return query.toString()+}++// The address a base address gets with a query, whether or not it has one.+export function withQuery(base, query) {+ return `${base}${base.includes("?") ? "&" : "?"}${query}`+}diff --git a/app/services/actors/correct_meeting_term.rb b/app/services/actors/correct_meeting_term.rbindex 4e5712c..7aab25e 100644--- a/app/services/actors/correct_meeting_term.rb+++ b/app/services/actors/correct_meeting_term.rb@@ -42,6 +42,12 @@ module Actors# or :proposed (the heard form's status).attr_reader :replaced_count, :glossary_outcome+ # Whether the AI summary got the replacement too ("everywhere", and the+ # word stood in it).+ def summary_replaced?+ @summary_replaced == true+ end+# 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.@@ -124,6 +130,7 @@ module Actorsparams = { transcript: transcript.text }summary = replaced_summary if @scope == 'everywhere'params[:generated_summary] = summary if summary+ @summary_replaced = !summary.nil?@replaced_count = transcript.countsaved = Actors::SaveMeeting.call(project: @project, params: params, id: @meeting.id, current_user: current_user,diff --git a/app/services/meetings/term_correction_dialog.rb b/app/services/meetings/term_correction_dialog.rbnew file mode 100644index 0000000..4a3a3dc--- /dev/null+++ b/app/services/meetings/term_correction_dialog.rb@@ -0,0 +1,88 @@+# frozen_string_literal: true++# What the dialog of a term correction shows (K4b), from what the browser sent+# and the transcript stored now: the mark resolved to its place in the stored+# text (Meetings::TranscriptMark), the heard form as typed and its occurrence+# at that place, how often it stands overall and in the turns of the speaker+# of the marked line (Meetings::TermReplacement), the digest it counted, and+# whether that is another transcript than the one the browser brought+# (recounted?: the page or the dialog was drawn from an older one).+#+# The dialog, its count and the correction itself all build their answer here,+# so what the dialog promised is what the correction is checked against. No+# database: the caller hands in the transcript, the meeting's participants and+# the HTML the page shows of the transcript.+#+# Entry point: new+module Meetings+ class TermCorrectionDialog+ # The most glossary terms the dialog suggests while typing.+ SUGGESTIONS = 500++ # mark: { text:, before:, after:, offset: } as the browser sent it.+ # heard: the heard form as typed, nil for the first opening (the mark itself).+ # digest: the digest the browser brought (the page's, or the dialog's last count).+ def initialize(transcript:, displayed_html:, participants:, mark:, heard:, digest:)+ @transcript = transcript.to_s+ @displayed_html = displayed_html+ @participants = participants+ @mark = mark+ @heard = heard.nil? ? mark[:text].to_s.strip : heard.to_s+ @client_digest = digest.to_s+ end++ attr_reader :heard, :participants, :mark++ def digest+ @digest ||= Digest::SHA256.hexdigest(@transcript)+ end++ def recounted?+ @client_digest.present? && @client_digest != digest+ end++ # mark_error: nil, or why the mark has no place (Meetings::TranscriptMark's+ # codes). place: the marked span in the stored transcript, or nil.+ delegate :error, :place, to: :mark_result, prefix: false+ alias mark_error error++ def heard_blank?+ @heard.strip.empty?+ end++ # The occurrence of the heard form at the mark, or nil: then nothing can+ # be replaced (the form was changed into one that does not stand there).+ def occurrence+ return if place.nil? || heard_blank?++ @occurrence ||= replacement.at(**place.to_h)+ end++ def correctable?+ !occurrence.nil?+ end++ delegate :count, to: :replacement++ # Who spoke the marked line, a participant or nil.+ def speaker+ place && replacement.speaker_of(place.line_index)+ end++ # How often the form stands in the turns of that speaker.+ def speaker_count+ speaker && replacement.count_by_speaker.fetch(speaker, 0)+ end++ private++ def mark_result+ @mark_result ||= TranscriptMark.resolve(transcript: @transcript, displayed_html: @displayed_html,+ participants: @participants, **@mark.slice(:text, :before, :after, :offset))+ end++ def replacement+ @replacement ||= TermReplacement.new(text: @transcript, heard: @heard, participants: @participants)+ end+ end+enddiff --git a/app/views/organisations/meeting_term_corrections/_count.html.erb b/app/views/organisations/meeting_term_corrections/_count.html.erbnew file mode 100644index 0000000..f066ecf--- /dev/null+++ b/app/views/organisations/meeting_term_corrections/_count.html.erb@@ -0,0 +1,41 @@+<%# locals: (meeting:, token:, dialog:) %>+<%# The count of one opening of the dialog and its buttons (plan §5.1, §5.2): how often the heard+ form stands and how often in the turns of the speaker of the marked line, from the same list+ the correction replaces (Meetings::TermReplacement). Its own frame, reloaded by+ meeting_term_corrections#count while the heard form is typed; it carries the digest of the+ transcript it counted, so a correction of another transcript is counted again, never made.+ No button where the heard form does not stand at the mark. %>+<% tc = 'views.organisations.meetings.term_correction' %>+<%= turbo_frame_tag term_correction_count_id(meeting.id, token), class: 'term-correction-count block space-y-3' do %>+ <%= hidden_field_tag :digest, dialog.digest, id: nil %>+ <% if dialog.recounted? %>+ <p class="term-correction-notice text-sm text-amber-900" role="status"><%= t("#{tc}.recounted") %></p>+ <% end %>+ <p class="text-sm text-cream-800" aria-live="polite">+ <% if dialog.heard_blank? %>+ <%= t("#{tc}.count.heard_blank") %>+ <% elsif !dialog.correctable? %>+ <%= t("#{tc}.count.not_at_mark") %>+ <% elsif dialog.speaker %>+ <%= t("#{tc}.count.found_by_speaker", count: dialog.count, speaker_count: dialog.speaker_count,+ speaker: dialog.speaker.display_name) %>+ <% else %>+ <%= t("#{tc}.count.found", count: dialog.count) %>+ <% end %>+ </p>+ <div class="flex flex-wrap justify-end gap-2 border-t border-cream-200 pt-3">+ <button type="button"+ class="h-9 rounded border border-cream-300 bg-cream-100 px-4 text-sm font-medium text-cream-800 hover:bg-cream-200"+ data-action="click->term-correction-modal#close">+ <%= t("#{tc}.cancel") %>+ </button>+ <% if dialog.correctable? %>+ <%= render Neo::Buttons::ButtonComponent.new(variant: :secondary, size: :medium, type: 'submit', name: 'scope', value: 'here') do %>+ <%= t("#{tc}.here") %>+ <% end %>+ <%= render Neo::Buttons::ButtonComponent.new(variant: :primary, size: :medium, type: 'submit', name: 'scope', value: 'everywhere') do %>+ <%= t("#{tc}.everywhere", count: dialog.count) %>+ <% end %>+ <% end %>+ </div>+<% end %>diff --git a/app/views/organisations/meeting_term_corrections/_modal.html.erb b/app/views/organisations/meeting_term_corrections/_modal.html.erbnew file mode 100644index 0000000..7710ffd--- /dev/null+++ b/app/views/organisations/meeting_term_corrections/_modal.html.erb@@ -0,0 +1,126 @@+<%# locals: (meeting:, token:, dialog:, fields: {}, errors: [], notice: nil) %>+<%# The dialog "Begriff korrigieren" (K4b, plan §5.1). Lives in the frame beside the transcript;+ the button over a mark loads meeting_term_corrections#new into it. The root carries the id of+ THIS opening (token): a refused correction replaces exactly it, a correction removes it. Shape+ and lifecycle after README_MODAL_PATTERN.md (reference: the ticket relation modal).++ The mark rides along as hidden fields, the place is the server's (Meetings::TermCorrectionDialog).+ The count and the two buttons sit in a frame of their own (_count): it reloads when the heard+ form changes, with the digest of the transcript it counted. Glossary suggestions only with+ view_glossary; the box says "propose" without manage_glossary (E2). %>+<% tc = 'views.organisations.meetings.term_correction' %>+<% modal_id = term_correction_modal_id(meeting.id) %>+<% manage = GlossaryPolicy.manage_allowed?(current_user, current_organisation) %>+<% suggestions = term_correction_suggestions %>+<% field_class = 'w-full rounded border border-cream-300 bg-surface-raised px-3 py-2 text-sm focus:border-ink focus:outline-none focus:ring-1 focus:ring-ink' %>+<% selected_speaker = fields[:speaker_id].nil? ? dialog.speaker&.id : fields[:speaker_id] %>+<div id="<%= term_correction_modal_instance_id(meeting.id, token) %>"+ data-controller="term-correction-modal"+ data-term-correction-modal-return-id-value="<%= term_correction_trigger_id(meeting.id) %>"+ data-term-correction-modal-count-url-value="<%= count_organisation_project_meeting_term_correction_path(current_organisation, meeting.project, meeting) %>"+ data-term-correction-modal-count-frame-value="<%= term_correction_count_id(meeting.id, token) %>"+ data-action="keydown@window->term-correction-modal#closeOnEscape keydown@window->term-correction-modal#trapFocus">+ <div class="fixed inset-0 z-50 overflow-y-auto"+ data-action="click->term-correction-modal#closeOnBackdrop">+ <div class="fixed inset-0 bg-gray-500 bg-opacity-60 backdrop-blur-sm" aria-hidden="true"></div>+ <div class="relative flex min-h-screen items-center justify-center p-4"+ data-action="click->term-correction-modal#closeOnBackdrop">+ <div class="term-correction-modal relative w-full rounded-lg border border-slate-200 bg-surface-raised shadow-xl"+ role="dialog" aria-modal="true" aria-labelledby="<%= modal_id %>-title"+ data-term-correction-modal-target="card">+ <div class="flex items-start justify-between gap-3 border-b border-slate-200 p-4">+ <h3 id="<%= modal_id %>-title" class="text-lg font-bold text-cream-900">+ <i class="bi bi-spellcheck mr-1" aria-hidden="true"></i>+ <%= t("#{tc}.title") %>+ </h3>+ <button type="button" class="text-gray-400 hover:text-gray-600"+ title="<%= t("#{tc}.close") %>" aria-label="<%= t("#{tc}.close") %>"+ data-action="click->term-correction-modal#close">+ <i class="bi bi-x-lg" aria-hidden="true"></i>+ </button>+ </div>++ <div class="space-y-3 p-5">+ <% if notice %>+ <div class="term-correction-notice rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900" role="status">+ <%= t("#{tc}.#{notice}") %>+ </div>+ <% end %>+ <% if errors.any? %>+ <div class="term-correction-error rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800" role="alert">+ <% errors.each do |message| %>+ <p><%= message %></p>+ <% end %>+ </div>+ <% end %>++ <% if dialog.mark_error %>+ <p class="term-correction-error text-sm text-red-800" role="alert">+ <%= t("#{tc}.mark_errors.#{dialog.mark_error}") %>+ </p>+ <div class="flex justify-end border-t border-cream-200 pt-3">+ <button type="button"+ class="h-9 rounded border border-cream-300 bg-cream-100 px-4 text-sm font-medium text-cream-800 hover:bg-cream-200"+ data-action="click->term-correction-modal#close">+ <%= t("#{tc}.close") %>+ </button>+ </div>+ <% else %>+ <%= form_with url: organisation_project_meeting_term_correction_path(current_organisation, meeting.project, meeting),+ method: :post, class: 'space-y-3', data: { term_correction_modal_target: 'form' } do %>+ <%= hidden_field_tag :modal_token, token, id: nil %>+ <% dialog.mark.slice(:text, :before, :after, :offset).each do |key, value| %>+ <%= hidden_field_tag "mark[#{key}]", value, id: nil %>+ <% end %>++ <div>+ <label for="<%= modal_id %>-heard" class="mb-1 block text-sm font-medium text-cream-800"><%= t("#{tc}.heard_label") %></label>+ <%= text_field_tag 'term_correction[heard]', fields[:heard] || dialog.heard,+ id: "#{modal_id}-heard", autocomplete: 'off', class: field_class,+ data: { term_correction_modal_target: 'heard', action: 'input->term-correction-modal#recount' } %>+ </div>++ <div>+ <label for="<%= modal_id %>-correct" class="mb-1 block text-sm font-medium text-cream-800"><%= t("#{tc}.correct_label") %></label>+ <%= text_field_tag 'term_correction[correct]', fields[:correct],+ id: "#{modal_id}-correct", autocomplete: 'off', required: true, class: field_class,+ placeholder: t("#{tc}.correct_placeholder"),+ list: ("#{modal_id}-suggestions" if suggestions.any?),+ data: { term_correction_modal_target: 'correct' } %>+ <% if suggestions.any? %>+ <datalist id="<%= modal_id %>-suggestions">+ <% suggestions.each do |term| %>+ <option value="<%= term %>"></option>+ <% end %>+ </datalist>+ <% end %>+ </div>++ <div>+ <label for="<%= modal_id %>-speaker" class="mb-1 block text-sm font-medium text-cream-800"><%= t("#{tc}.speaker_label") %></label>+ <%= select_tag 'term_correction[speaker_id]',+ options_for_select(dialog.participants.map { |participant| [participant.display_name, participant.id] }, selected_speaker),+ include_blank: t("#{tc}.no_speaker"), id: "#{modal_id}-speaker", class: field_class %>+ </div>++ <div>+ <label class="flex items-center gap-2 text-sm text-cream-800">+ <%= hidden_field_tag 'term_correction[to_glossary]', '0', id: nil %>+ <%= check_box_tag 'term_correction[to_glossary]', '1', fields[:to_glossary] != '0', id: "#{modal_id}-glossary" %>+ <%= manage ? t("#{tc}.to_glossary_confirm") : t("#{tc}.to_glossary_propose") %>+ </label>+ <% unless manage %>+ <p class="mt-1 text-xs text-cream-500"><%= t("#{tc}.propose_hint") %></p>+ <% end %>+ </div>++ <p class="text-xs text-cream-500"><%= t("#{tc}.hint") %></p>++ <%= render 'organisations/meeting_term_corrections/count', meeting: meeting, token: token, dialog: dialog %>+ <% end %>+ <% end %>+ </div>+ </div>+ </div>+ </div>+</div>diff --git a/app/views/organisations/meeting_term_corrections/corrected.turbo_stream.erb b/app/views/organisations/meeting_term_corrections/corrected.turbo_stream.erbnew file mode 100644index 0000000..e552349--- /dev/null+++ b/app/views/organisations/meeting_term_corrections/corrected.turbo_stream.erb@@ -0,0 +1,15 @@+<%# Corrected: the transcript drawn again, in full (the reader was looking at the place), the+ summary when the correction replaced the word in it too ("everywhere"), this opening of the+ dialog gone, and a flash with the number of places and what the glossary learnt. %>+<%= turbo_stream.replace meeting_transcript_section_id(@meeting) do %>+ <%= render 'organisations/meetings/transcript_section',+ meeting: @meeting, participants: @participants, clamp: false, correctable: true %>+<% end %>+<% if @summary_replaced %>+ <%= turbo_stream.replace "#{dom_id(@meeting)}_summary_section",+ partial: 'organisations/meetings/summary_section', locals: { meeting: @meeting } %>+<% end %>+<% if @modal_token %>+ <%= turbo_stream.remove term_correction_modal_instance_id(@meeting.id, @modal_token) %>+<% end %>+<%= turbo_stream.prepend 'flash', partial: 'layouts/flash', locals: { flash: @flash_message } %>diff --git a/app/views/organisations/meeting_term_corrections/gone.turbo_stream.erb b/app/views/organisations/meeting_term_corrections/gone.turbo_stream.erbnew file mode 100644index 0000000..d56f6ea--- /dev/null+++ b/app/views/organisations/meeting_term_corrections/gone.turbo_stream.erb@@ -0,0 +1,7 @@+<%# Not found: the meeting moved or was deleted (before the request: the lookup; during it: the+ lock). The dialog opening goes and the reason comes as a flash. Nothing of the meeting is+ drawn again: it may be in a project this request was not checked for. %>+<% if @modal_token %>+ <%= turbo_stream.remove term_correction_modal_instance_id(@meeting_id, @modal_token) %>+<% end %>+<%= turbo_stream.prepend 'flash', partial: 'layouts/flash', locals: { flash: { alert: @errors.to_sentence } } %>diff --git a/app/views/organisations/meeting_term_corrections/new.html.erb b/app/views/organisations/meeting_term_corrections/new.html.erbnew file mode 100644index 0000000..ce16d3a--- /dev/null+++ b/app/views/organisations/meeting_term_corrections/new.html.erb@@ -0,0 +1,5 @@+<%# The dialog "Begriff korrigieren", loaded into its frame by the button over a mark in the+ transcript (layout: false, only the frame counts). See _modal. %>+<%= turbo_frame_tag term_correction_modal_id(@meeting.id) do %>+ <%= render 'organisations/meeting_term_corrections/modal', meeting: @meeting, token: @modal_token, dialog: @dialog %>+<% end %>diff --git a/app/views/organisations/meeting_term_corrections/not_found.html.erb b/app/views/organisations/meeting_term_corrections/not_found.html.erbnew file mode 100644index 0000000..749b1ad--- /dev/null+++ b/app/views/organisations/meeting_term_corrections/not_found.html.erb@@ -0,0 +1,6 @@+<%# The meeting is no longer in this project (moved or deleted while the page was open). The+ answer goes into the dialog's frame, by the meeting id of the route, so the page says why+ instead of Turbo's "Content missing". Nothing of the meeting is drawn. %>+<%= turbo_frame_tag term_correction_modal_id(@meeting_id) do %>+ <p class="term-correction-gone mt-1 text-sm text-red-800" role="alert"><%= @errors.to_sentence %></p>+<% end %>diff --git a/app/views/organisations/meeting_term_corrections/refused.turbo_stream.erb b/app/views/organisations/meeting_term_corrections/refused.turbo_stream.erbnew file mode 100644index 0000000..a9025fa--- /dev/null+++ b/app/views/organisations/meeting_term_corrections/refused.turbo_stream.erb@@ -0,0 +1,13 @@+<%# The correction was refused, or the transcript changed since the dialog counted: the dialog+ again, in place of the opening that sent it, with what was typed and the count of the+ transcript stored now. A dialog closed meanwhile has no such element and stays closed.+ Without a usable token there is no opening to fill: the reason goes out as a flash. %>+<% if @modal_token %>+ <%= turbo_stream.replace term_correction_modal_instance_id(@meeting.id, @modal_token) do %>+ <%= render 'organisations/meeting_term_corrections/modal',+ meeting: @meeting, token: @modal_token, dialog: @dialog, fields: @fields, errors: @errors, notice: @notice %>+ <% end %>+<% else %>+ <% message = @notice ? t("views.organisations.meetings.term_correction.#{@notice}") : @errors.to_sentence %>+ <%= turbo_stream.prepend 'flash', partial: 'layouts/flash', locals: { flash: { alert: message } } %>+<% end %>diff --git a/app/views/organisations/meetings/_meeting_reading.html.erb b/app/views/organisations/meetings/_meeting_reading.html.erbindex 51a331e..71cfe32 100644--- a/app/views/organisations/meetings/_meeting_reading.html.erb+++ b/app/views/organisations/meetings/_meeting_reading.html.erb@@ -37,20 +37,14 @@<% end %><% if meeting.transcript.present? %>- <section>- <h3 class="text-xs font-mono uppercase tracking-wider text-cream-600 mb-2">- <%= t('views.organisations.meetings.show.transcript_heading') %>- </h3>- <% if panel || meeting.generated_summary.present? || meeting.notes.present? %>- <%= render Neo::MarkdownPreviewComponent.new(- markdown: meeting_transcript_source(meeting, participants),- clamp: :tall,- more_label: t('views.organisations.meetings.show.transcript_show_full'),- less_label: t('views.organisations.meetings.show.transcript_collapse')) %>- <% else %>- <%= render Neo::MarkdownPreviewComponent.new(markdown: meeting_transcript_source(meeting, participants)) %>- <% end %>- </section>+ <%# Correcting a misheard word (K4b) only on the meeting page, never in the panel. %>+ <% correctable = can_write && !panel %>+ <%= render 'organisations/meetings/transcript_section',+ meeting: meeting, participants: participants, correctable: correctable,+ clamp: panel || meeting.generated_summary.present? || meeting.notes.present? %>+ <% if correctable %>+ <%= turbo_frame_tag term_correction_modal_id(meeting.id) %>+ <% end %><% end %><% end %></div>diff --git a/app/views/organisations/meetings/_transcript_section.html.erb b/app/views/organisations/meetings/_transcript_section.html.erbnew file mode 100644index 0000000..4c8f14f--- /dev/null+++ b/app/views/organisations/meetings/_transcript_section.html.erb@@ -0,0 +1,42 @@+<%# locals: (meeting:, participants:, clamp:, correctable: false) %>+<%# The transcript of a meeting, rendered through Markdown (Neo::MarkdownPreviewComponent), with+ its speaker turns bolded against the participant list. clamp: collapsed to its tall preview.+ correctable (the meeting page with write access, never the panel beside a ticket): a mark in+ the transcript shows "Korrigieren" (transcript_selection_controller), which opens the dialog+ of a term correction (K4b) in the frame _meeting_reading puts beside this section. The section+ carries the digest of the transcript it shows; a correction redraws it in full. %>+<% source = meeting_transcript_source(meeting, participants) %>+<% tc = 'views.organisations.meetings.term_correction' %>+<% data = if correctable+ { controller: 'transcript-selection',+ transcript_selection_url_value: new_organisation_project_meeting_term_correction_path(current_organisation, meeting.project, meeting),+ transcript_selection_digest_value: meeting_transcript_digest(meeting) }+ else+ {}+ end %>+<%= tag.section id: meeting_transcript_section_id(meeting), class: ('transcript-section relative' if correctable), data: data do %>+ <h3 class="text-xs font-mono uppercase tracking-wider text-cream-600 mb-2">+ <%= t('views.organisations.meetings.show.transcript_heading') %>+ </h3>+ <%= tag.div data: ({ transcript_selection_target: 'content' } if correctable) do %>+ <% if clamp %>+ <%= render Neo::MarkdownPreviewComponent.new(+ markdown: source,+ clamp: :tall,+ more_label: t('views.organisations.meetings.show.transcript_show_full'),+ less_label: t('views.organisations.meetings.show.transcript_collapse')) %>+ <% else %>+ <%= render Neo::MarkdownPreviewComponent.new(markdown: source) %>+ <% end %>+ <% end %>+ <% if correctable %>+ <%= link_to new_organisation_project_meeting_term_correction_path(current_organisation, meeting.project, meeting),+ id: term_correction_trigger_id(meeting.id),+ class: 'transcript-correct hidden rounded border-2 border-ink bg-lime-300 px-2.5 py-1 text-[13px] font-semibold text-ink shadow-[2px_2px_0_0_#000] hover:bg-lime-400',+ title: t("#{tc}.trigger_label"),+ data: { turbo_frame: term_correction_modal_id(meeting.id), transcript_selection_target: 'button',+ action: 'mousedown->transcript-selection#keepSelection' } do %>+ <i class="bi bi-spellcheck" aria-hidden="true"></i><%= t("#{tc}.trigger") %>+ <% end %>+ <% end %>+<% end %>diff --git a/config/importmap.rb b/config/importmap.rbindex 18ee952..1d824cf 100644--- a/config/importmap.rb+++ b/config/importmap.rb@@ -113,6 +113,9 @@ pin 'custom_period', to: 'lib/custom_period.js'# could see it (review of #693).pin 'filter_menu_search', to: 'lib/filter_menu_search.js'pin 'menu_fit', to: 'lib/menu_fit.js'+# What the button over a mark in the transcript sends (K4b): the mark, its context and+# offset in characters, and the fields the dialog counts with. Pure, node:test.+pin 'transcript_mark', to: 'lib/transcript_mark.js'# Development: Load controllers from source directoryif Rails.env.development?@@ -252,6 +255,7 @@ elsepin 'controllers/tabs_controller', to: 'controllers/tabs_controller.js'pin 'controllers/tag_input_controller', to: 'controllers/tag_input_controller.js'pin 'controllers/team_member_edit_controller', to: 'controllers/team_member_edit_controller.js'+ pin 'controllers/term_correction_modal_controller', to: 'controllers/term_correction_modal_controller.js'pin 'controllers/ticket_bulk_panel_controller', to: 'controllers/ticket_bulk_panel_controller.js'pin 'controllers/ticket_description_collapse_controller', to: 'controllers/ticket_description_collapse_controller.js'pin 'controllers/ticket_direct_navigation_controller', to: 'controllers/ticket_direct_navigation_controller.js'@@ -269,6 +273,7 @@ elsepin 'controllers/time_sessions_index_controller', to: 'controllers/time_sessions_index_controller.js'pin 'controllers/timeline_filter_controller', to: 'controllers/timeline_filter_controller.js'pin 'controllers/toggle_controller', to: 'controllers/toggle_controller.js'+ pin 'controllers/transcript_selection_controller', to: 'controllers/transcript_selection_controller.js'pin 'controllers/turbo_cache_controller', to: 'controllers/turbo_cache_controller.js'pin 'controllers/undefined_url_guard_controller', to: 'controllers/undefined_url_guard_controller.js'pin 'controllers/upload_progress_controller', to: 'controllers/upload_progress_controller.js'diff --git a/config/locales/views/meetings.de.yml b/config/locales/views/meetings.de.ymlindex 3a74e1b..0c46ff6 100644--- a/config/locales/views/meetings.de.yml+++ b/config/locales/views/meetings.de.yml@@ -151,6 +151,49 @@ de:link: "%{name} mit Person verknüpfen"change: "Verknüpfung von %{name} ändern"open_person: "%{name}: Person öffnen"+ # Correcting a misheard word in the transcript (K4b).+ term_correction:+ trigger: Korrigieren+ trigger_label: "Markiertes Wort korrigieren"+ title: Begriff korrigieren+ close: Schließen+ cancel: Abbrechen+ heard_label: Gehört+ correct_label: Richtig+ correct_placeholder: Richtige Schreibweise+ speaker_label: Sprecher+ no_speaker: Unbekannt+ to_glossary_confirm: Ins Glossar übernehmen+ to_glossary_propose: Fürs Glossar vorschlagen+ propose_hint: Wer das Glossar pflegt, bestätigt oder verwirft den Vorschlag. Bis dahin wirkt er nirgends.+ hint: Ersetzt werden nur ganze Wörter, Groß- und Kleinschreibung wie markiert. Der Name des Sprechers am Zeilenanfang bleibt.+ here: Nur hier ersetzen+ everywhere:+ one: "Überall ersetzen (1)"+ other: "Überall ersetzen (%{count})"+ recounted: Das Transkript hat sich inzwischen geändert. Die Zahl ist neu gezählt, bitte noch einmal wählen.+ count:+ found:+ one: Kommt 1-mal vor.+ other: "Kommt %{count}-mal vor."+ found_by_speaker:+ one: "Kommt 1-mal vor, bei %{speaker}."+ other: "Kommt %{count}-mal vor, davon %{speaker_count}-mal bei %{speaker}."+ not_at_mark: Diese Form steht nicht an der markierten Stelle. Ändere sie oder markiere neu.+ heard_blank: Bitte die gehörte Form eingeben.+ mark_errors:+ not_found: Diese Stelle lässt sich im Transkript nicht finden. Lade die Seite neu und markiere noch einmal.+ not_a_word: Bitte ein ganzes Wort markieren, nicht nur einen Teil davon.+ ambiguous: Diese Form steht im Transkript anders, als die Seite sie zeigt (etwa in einem Link). Ändere sie über „Bearbeiten“.+ speaker_label: Der Name des Sprechers gehört zur Teilnehmerliste und lässt sich hier nicht korrigieren.+ line_break: Bitte nur innerhalb einer Zeile markieren.+ too_long: Die Markierung ist zu lang, höchstens 255 Zeichen.+ flash:+ replaced:+ one: 1 Stelle ersetzt.+ other: "%{count} Stellen ersetzt."+ confirmed: Ins Glossar übernommen.+ proposed: Fürs Glossar vorgeschlagen.shared:duration_minutes: "%{count} Min"participant_type:diff --git a/config/locales/views/meetings.en.yml b/config/locales/views/meetings.en.ymlindex bb9ede0..d3d2c6a 100644--- a/config/locales/views/meetings.en.yml+++ b/config/locales/views/meetings.en.yml@@ -150,6 +150,49 @@ en:link: "Link %{name} to a person"change: "Change the link of %{name}"open_person: "%{name}: open person"+ # Correcting a misheard word in the transcript (K4b).+ term_correction:+ trigger: Correct+ trigger_label: "Correct the marked word"+ title: Correct a term+ close: Close+ cancel: Cancel+ heard_label: Heard+ correct_label: Right+ correct_placeholder: Right spelling+ speaker_label: Speaker+ no_speaker: Unknown+ to_glossary_confirm: Add to the glossary+ to_glossary_propose: Propose for the glossary+ propose_hint: Whoever keeps the glossary confirms or rejects the proposal. Until then it works nowhere.+ hint: Only whole words are replaced, upper and lower case as marked. The speaker's name at the start of a line stays.+ here: Replace only here+ everywhere:+ one: "Replace everywhere (1)"+ other: "Replace everywhere (%{count})"+ recounted: The transcript has changed in the meantime. The number is counted again, please choose again.+ count:+ found:+ one: Appears once.+ other: "Appears %{count} times."+ found_by_speaker:+ one: "Appears once, by %{speaker}."+ other: "Appears %{count} times, %{speaker_count} of them by %{speaker}."+ not_at_mark: This form does not stand at the marked place. Change it or mark again.+ heard_blank: Please enter the heard form.+ mark_errors:+ not_found: This place cannot be found in the transcript. Reload the page and mark again.+ not_a_word: Please mark a whole word, not only a part of it.+ ambiguous: This form stands differently in the transcript than the page shows it (in a link, for example). Change it through "Edit".+ speaker_label: The speaker's name belongs to the participant list and cannot be corrected here.+ line_break: Please mark within one line.+ too_long: The mark is too long, at most 255 characters.+ flash:+ replaced:+ one: 1 place replaced.+ other: "%{count} places replaced."+ confirmed: Added to the glossary.+ proposed: Proposed for the glossary.shared:duration_minutes: "%{count} min"participant_type:diff --git a/config/routes.rb b/config/routes.rbindex ab90326..2f22a5b 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -812,6 +812,11 @@ Rails.application.routes.draw doresources :participants, only: [] doresource :link, only: %i[new create destroy], controller: 'meeting_participant_links'end+ # Correcting a misheard word in the transcript (K4b): new renders the dialog into+ # its frame, count redraws its count, create corrects and learns it for the glossary.+ resource :term_correction, only: %i[new create], controller: 'meeting_term_corrections' do+ get :count+ endcollection do# LLM participant detection (Slice 5): runs BEFORE save on the raw# transcript payload (scoping via @project, no persisted meeting);diff --git a/spec/architecture/meeting_lock_guard_spec.rb b/spec/architecture/meeting_lock_guard_spec.rbindex a85b624..3872b90 100644--- a/spec/architecture/meeting_lock_guard_spec.rb+++ b/spec/architecture/meeting_lock_guard_spec.rb@@ -53,7 +53,8 @@ module MeetingLockGuardCONTROLLERS = {'organisations/meetings' => 'app/controllers/organisations/meetings_controller.rb','organisations/meeting_ticket_links' => 'app/controllers/organisations/meeting_ticket_links_controller.rb',- 'organisations/meeting_participant_links' => 'app/controllers/organisations/meeting_participant_links_controller.rb'+ 'organisations/meeting_participant_links' => 'app/controllers/organisations/meeting_participant_links_controller.rb',+ 'organisations/meeting_term_corrections' => 'app/controllers/organisations/meeting_term_corrections_controller.rb'}.freezeCONTROLLER_LOCK = 'with_meeting_in_project'diff --git a/spec/javascript/lib/transcript_mark.test.js b/spec/javascript/lib/transcript_mark.test.jsnew file mode 100644index 0000000..aa0fca3--- /dev/null+++ b/spec/javascript/lib/transcript_mark.test.js@@ -0,0 +1,57 @@+// What: the pieces the transcript's "Korrigieren" button sends for a mark (K4b).+// Type: node:test unit spec, no browser.+// Why: the server finds the place from the mark, its context and its offset+// in the text the page shows (Meetings::TranscriptMark). An offset in UTF-16+// units, whitespace kept in the mark, or a context cut in the middle of an+// emoji would make it refuse marks it could place, or pick another place.+import { test } from "node:test"+import assert from "node:assert/strict"+import { buildMark, countQuery, markQuery, withQuery } from "../../../app/javascript/lib/transcript_mark.js"++const limits = { context: 40, maxLength: 255 }++test("cuts the mark, its context and its offset in characters", () => {+ const mark = buildMark({ prefix: "Anna: Grüße 👋 und ", selected: "Lalabeis", suffix: " heute." }, limits)++ assert.deepEqual(mark, { text: "Lalabeis", before: "Anna: Grüße 👋 und ", after: " heute.", offset: 18 })+})++test("moves whitespace around the mark into the context", () => {+ const mark = buildMark({ prefix: "Ben:", selected: " Lalabeis ", suffix: "kann" }, limits)++ assert.deepEqual(mark, { text: "Lalabeis", before: "Ben: ", after: " kann", offset: 5 })+})++test("keeps at most the context on each side, never half a character", () => {+ const prefix = "x".repeat(50) + "😀"+ const mark = buildMark({ prefix, selected: "Lalabeis", suffix: "😀".repeat(60) }, { context: 5, maxLength: 255 })++ assert.equal(mark.before, "xxxx😀")+ assert.equal(mark.after, "😀😀😀😀😀")+ assert.equal(mark.offset, 51)+})++test("offers nothing for a blank mark, one over a line break, or one too long", () => {+ assert.equal(buildMark({ prefix: "", selected: " ", suffix: "" }, limits), null)+ assert.equal(buildMark({ prefix: "", selected: "Lala\nbeis", suffix: "" }, limits), null)+ assert.equal(buildMark({ prefix: "", selected: "x".repeat(256), suffix: "" }, limits), null)+ assert.notEqual(buildMark({ prefix: "", selected: "😀".repeat(255), suffix: "" }, limits), null)+})++test("puts the mark and the digest into the dialog's address", () => {+ const query = markQuery({ text: "Lala & Beis", before: "a", after: "b", offset: 3 }, "f".repeat(64))++ assert.equal(withQuery("/m/term_correction/new", query),+ `/m/term_correction/new?mark%5Btext%5D=Lala+%26+Beis&mark%5Bbefore%5D=a&mark%5Bafter%5D=b&mark%5Boffset%5D=3&digest=${"f".repeat(64)}`)+ assert.equal(withQuery("/m/count?x=1", "a=b"), "/m/count?x=1&a=b")+})++test("asks the count with the mark, the digest, the opening and the heard form only", () => {+ const entries = [+ ["authenticity_token", "geheim"], ["modal_token", "abcd"], ["mark[text]", "Lalabeis"], ["mark[offset]", "4"],+ ["digest", "d"], ["term_correction[heard]", "Lala beis"], ["term_correction[correct]", "Lalabase"], ["scope", "here"]+ ]++ assert.equal(countQuery(entries),+ "modal_token=abcd&mark%5Btext%5D=Lalabeis&mark%5Boffset%5D=4&digest=d&term_correction%5Bheard%5D=Lala+beis")+})diff --git a/spec/requests/organisations/meeting_term_corrections_spec.rb b/spec/requests/organisations/meeting_term_corrections_spec.rbnew file mode 100644index 0000000..6349462--- /dev/null+++ b/spec/requests/organisations/meeting_term_corrections_spec.rb@@ -0,0 +1,359 @@+# frozen_string_literal: true++require 'rails_helper'++# Correcting a misheard word in a meeting (K4b): the dialog (new), its count+# (count) and the correction (create). Rights in both directions: the meeting+# write opens all three (E2), anything less answers 403, a meeting of another+# project or organisation 404. What the dialog offers hangs on the glossary+# right: suggestions only with view_glossary, the box says "propose" without+# manage_glossary. Every negative claim stands next to proof that the dialog+# itself was rendered. Invented words and names only.+RSpec.describe 'Organisations::MeetingTermCorrections', :ci_guard, type: :request 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) { "Anna: Wir testen Lalabeis heute.\nBen: Lalabeis kann viel.\nUnd Lalabeis-Konten auch." }+ 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!(:anna) { create(:meeting_participant, meeting: meeting, display_name: 'Anna Ananas') }+ let!(:ben) { create(:meeting_participant, meeting: meeting, display_name: 'Ben Birne') }+ let(:tc) { 'views.organisations.meetings.term_correction' }+ let(:frame) { { 'Turbo-Frame' => "meeting-term-correction-modal-#{meeting.id}" } }+ let(:stream) { { 'Accept' => 'text/vnd.turbo-stream.html' } }+ let(:modal_token) { SecureRandom.hex(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)+ user = create(:user, first_name: 'Max', last_name: "Muster#{SecureRandom.hex(2)}")+ create(:membership, user: user, organisation: organisation, role: role, active: true)+ user+ end++ def writer(*glossary_actions, access: :read_write)+ member_with(role_with(*glossary_actions)).tap do |user|+ create(:project_permission, user: user, project: project, meetings_access: access)+ end+ end++ def digest+ Digest::SHA256.hexdigest(meeting.reload.transcript.to_s)+ end++ # What the browser sends for the nth place of `text` in the text the page shows.+ def browser_mark(text = 'Lalabeis', nth: 1)+ html = ApplicationController.helpers.meeting_transcript_html(meeting.reload, meeting.meeting_participants.in_row_order.to_a)+ shown = Nokogiri::HTML5.fragment(html).text+ start = shown.to_enum(:scan, text).map { Regexp.last_match.begin(0) }.fetch(nth)+ { text: text, before: shown[[start - 40, 0].max...start], after: shown[start + text.length, 40], offset: start }+ end++ def new_path(mark: browser_mark, in_project: project, on: meeting)+ new_organisation_project_meeting_term_correction_path(organisation, in_project, on, mark: mark, digest: digest)+ end++ def count_path(heard: 'Lalabeis', mark: browser_mark, token: modal_token)+ count_organisation_project_meeting_term_correction_path(organisation, project, meeting, mark: mark, digest: digest,+ modal_token: token,+ term_correction: { heard: heard })+ end++ def correction_params(scope: 'everywhere', correct: 'Lalabase', heard: 'Lalabeis', speaker_id: ben.id, to_glossary: '1',+ with_digest: digest)+ { modal_token: modal_token, mark: browser_mark, digest: with_digest, scope: scope,+ term_correction: { heard: heard, correct: correct, speaker_id: speaker_id, to_glossary: to_glossary } }+ end++ def post_correction(**options)+ post organisation_project_meeting_term_correction_path(organisation, project, meeting),+ params: correction_params(**options), headers: stream+ end++ def page_markup+ Capybara.string(response.body)+ end++ # The markup one stream of the answer carries (its <template>).+ def stream_markup(action, target)+ node = Nokogiri::HTML(response.body).at_css(%(turbo-stream[action="#{action}"][target="#{target}"]))+ raise "no #{action} stream for #{target} in the answer" unless node++ Capybara.string(node.at_css('template').inner_html)+ end++ describe 'the meeting page' do+ def show_meeting+ get organisation_project_meeting_path(organisation, project, meeting, frame: 'content'),+ headers: { 'Turbo-Frame' => Organisations::MeetingsController::DETAIL_FRAME_ID }+ end++ it 'offers the correction to a writer of the meeting, with the digest of the transcript it shows' do+ sign_in writer+ show_meeting++ expect(response).to have_http_status(:ok)+ section = page_markup.find("##{ActionView::RecordIdentifier.dom_id(meeting, :transcript)}")+ expect(section['data-controller']).to include('transcript-selection')+ expect(section['data-transcript-selection-digest-value']).to eq(digest)+ expect(page_markup).to have_css("turbo-frame#meeting-term-correction-modal-#{meeting.id}")+ expect(page_markup).to have_css("#meeting-term-correction-trigger-#{meeting.id}", visible: :all)+ end++ it 'offers nothing to a reader of the meeting' do+ sign_in writer(access: :read_only)+ show_meeting++ expect(response.body).to include('Lalabeis kann viel')+ expect(response.body).not_to include('transcript-selection')+ expect(response.body).not_to include("meeting-term-correction-modal-#{meeting.id}")+ end+ end++ describe 'the dialog' do+ it 'opens in its frame with the heard form, the speaker of the line and the count' do+ sign_in writer+ get new_path, headers: frame++ expect(response).to have_http_status(:ok)+ dialog = page_markup.find("turbo-frame#meeting-term-correction-modal-#{meeting.id}")+ expect(dialog).to have_field('term_correction[heard]', with: 'Lalabeis')+ expect(dialog).to have_select('term_correction[speaker_id]', selected: 'Ben Birne')+ expect(dialog).to have_text(I18n.t("#{tc}.count.found_by_speaker", count: 3, speaker_count: 2, speaker: 'Ben Birne'))+ expect(dialog).to have_button(I18n.t("#{tc}.everywhere", count: 3))+ expect(dialog).to have_button(I18n.t("#{tc}.here"))+ expect(dialog).to have_css("input[name='digest'][value='#{digest}']", visible: :all)+ end++ it 'names the box "propose" without manage_glossary and "take over" with it' do+ sign_in writer('view_glossary')+ get new_path, headers: frame+ expect(page_markup).to have_field(I18n.t("#{tc}.to_glossary_propose"), checked: true)+ expect(page_markup).not_to have_field(I18n.t("#{tc}.to_glossary_confirm"))++ sign_in writer('manage_glossary')+ get new_path, headers: frame+ expect(page_markup).to have_field(I18n.t("#{tc}.to_glossary_confirm"), checked: true)+ end++ it 'suggests terms of the glossary only with view_glossary' do+ create(:glossary_term, organisation: organisation, term: 'Lalabase')+ create(:glossary_term, :rejected, organisation: organisation, term: 'Verworfenes Wort')++ sign_in writer('view_glossary')+ get new_path, headers: frame+ expect(page_markup).to have_css('datalist option[value="Lalabase"]', visible: :all)+ expect(response.body).not_to include('Verworfenes Wort')++ sign_in writer+ get new_path, headers: frame+ expect(page_markup).to have_field('term_correction[correct]')+ expect(response.body).not_to include('<datalist')+ expect(response.body).not_to include('Lalabase')+ end++ it 'says why, and offers no form, for a mark it cannot place' do+ sign_in writer+ get new_path(mark: browser_mark('Lalabei', nth: 0)), headers: frame++ expect(response).to have_http_status(:ok)+ expect(page_markup).to have_text(I18n.t("#{tc}.mark_errors.not_a_word"))+ expect(page_markup).not_to have_field('term_correction[correct]')+ end++ it 'counts again for a transcript changed since the page was drawn, and says so' do+ sign_in writer+ mark = browser_mark+ meeting.update_columns(transcript: "#{transcript}\nAnna: Lalabeis zum Schluss.")++ get new_organisation_project_meeting_term_correction_path(organisation, project, meeting, mark: mark,+ digest: Digest::SHA256.hexdigest(transcript)),+ headers: frame++ expect(page_markup).to have_text(I18n.t("#{tc}.recounted"))+ expect(page_markup).to have_button(I18n.t("#{tc}.everywhere", count: 4))+ expect(page_markup).to have_css("input[name='digest'][value='#{digest}']", visible: :all)+ end+ end++ describe 'the count' do+ it 'counts the heard form as typed, in its own frame' do+ sign_in writer+ get count_path(heard: 'Lalabeis'), headers: { 'Turbo-Frame' => "meeting-term-correction-count-#{meeting.id}-#{modal_token}" }++ expect(response).to have_http_status(:ok)+ expect(page_markup).to have_css("turbo-frame#meeting-term-correction-count-#{meeting.id}-#{modal_token}")+ expect(page_markup).to have_button(I18n.t("#{tc}.everywhere", count: 3))+ end++ it 'offers no button where the changed form does not stand at the mark' do+ sign_in writer+ get count_path(heard: 'Konten')++ expect(page_markup).to have_text(I18n.t("#{tc}.count.not_at_mark"))+ expect(page_markup).not_to have_button(I18n.t("#{tc}.here"))+ end+ end++ describe 'correcting' do+ it 'replaces everywhere, redraws the transcript, closes this opening and says how often' do+ sign_in writer('manage_glossary')+ post_correction++ expect(response).to have_http_status(:ok)+ expect(meeting.reload.transcript).to eq("Anna: Wir testen Lalabase heute.\nBen: Lalabase kann viel.\nUnd Lalabase-Konten auch.")+ expect(stream_markup('replace', ActionView::RecordIdentifier.dom_id(meeting, :transcript))).to have_text('Lalabase kann viel')+ expect(response.body).to include(%(<turbo-stream action="remove" target="meeting-term-correction-modal-#{meeting.id}-#{modal_token}">))+ expect(stream_markup('prepend', 'flash')).to have_text(I18n.t("#{tc}.flash.replaced", count: 3))+ expect(stream_markup('prepend', 'flash')).to have_text(I18n.t("#{tc}.flash.confirmed"))+ expect(stream_markup('replace', "#{ActionView::RecordIdentifier.dom_id(meeting)}_summary_section"))+ .to have_text('Lalabase wurde vorgestellt.')+ end++ it 'proposes for the glossary without manage_glossary, and says so' do+ sign_in writer+ post_correction(scope: 'here')++ expect(meeting.reload.transcript).to include('Ben: Lalabase kann viel.')+ expect(TermCorrection.last).to be_proposed+ expect(stream_markup('prepend', 'flash')).to have_text(I18n.t("#{tc}.flash.replaced", count: 1))+ expect(stream_markup('prepend', 'flash')).to have_text(I18n.t("#{tc}.flash.proposed"))+ end++ it 'writes the transcript only when the box is off' do+ sign_in writer('manage_glossary')+ post_correction(to_glossary: '0')++ expect(meeting.reload.transcript).to include('Lalabase')+ expect(TermCorrection.count).to eq(0)+ end++ it 'shows the dialog again, counted anew, for a transcript changed since it counted, and writes nothing' do+ sign_in writer('manage_glossary')+ old_digest = digest+ meeting.update_columns(transcript: "#{transcript}\nAnna: Lalabeis zum Schluss.")++ post_correction(with_digest: old_digest)++ expect(response).to have_http_status(:unprocessable_content)+ instance = stream_markup('replace', "meeting-term-correction-modal-#{meeting.id}-#{modal_token}")+ expect(instance).to have_text(I18n.t("#{tc}.recounted"))+ expect(instance).to have_button(I18n.t("#{tc}.everywhere", count: 4))+ expect(meeting.reload.transcript).not_to include('Lalabase')+ expect(TermCorrection.count).to eq(0)+ end++ it 'shows the dialog again with the reason for a refused correction' do+ sign_in writer('manage_glossary')+ post_correction(correct: ' ')++ expect(response).to have_http_status(:unprocessable_content)+ instance = stream_markup('replace', "meeting-term-correction-modal-#{meeting.id}-#{modal_token}")+ expect(instance).to have_text(I18n.t('services.actors.correct_meeting_term.correct_blank'))+ expect(meeting.reload.transcript).to eq(transcript)+ end+ end++ describe 'who may not correct' do+ def requests+ {+ 'the dialog' => -> { get new_path, headers: frame },+ 'the count' => -> { get count_path },+ 'the correction' => -> { post_correction }+ }+ end++ ['the dialog', 'the count', 'the correction'].each do |name|+ it "answers 403 to a reader of the meeting on #{name}" do+ sign_in writer('manage_glossary', access: :read_only)+ instance_exec(&requests.fetch(name))++ expect(response).to have_http_status(:forbidden)+ expect(meeting.reload.transcript).to eq(transcript)+ end++ it "answers 403 to a member without access to the project on #{name}" do+ sign_in member_with(role_with('manage_glossary'))+ instance_exec(&requests.fetch(name))++ expect(response).to have_http_status(:forbidden)+ expect(meeting.reload.transcript).to eq(transcript)+ end+ end++ it 'answers 403 in an archived project to a writer' do+ user = writer('manage_glossary')+ project.update_columns(archived_at: Time.current)+ sign_in user++ post_correction+ expect(response).to have_http_status(:forbidden)+ get new_path, headers: frame+ expect(response).to have_http_status(:forbidden)+ expect(meeting.reload.transcript).to eq(transcript)+ end++ it 'finds no meeting of another project' do+ other_project = create(:project, organisation: organisation)+ user = writer('manage_glossary')+ create(:project_permission, user: user, project: other_project, meetings_access: :read_write)+ sign_in user++ get new_organisation_project_meeting_term_correction_path(organisation, other_project, meeting, mark: browser_mark,+ digest: digest),+ headers: frame+ expect(response).to have_http_status(:not_found)+ post organisation_project_meeting_term_correction_path(organisation, other_project, meeting),+ params: correction_params, headers: stream+ expect(response).to have_http_status(:not_found)+ expect(meeting.reload.transcript).to eq(transcript)+ end++ # A forged id: the meeting of another organisation under the own address.+ it 'answers 404 for a meeting of another organisation' do+ other = create(:organisation)+ foreign = ActsAsTenant.with_tenant(other) do+ create(:meeting, organisation: other, project: create(:project, organisation: other), creator: creator,+ transcript: transcript)+ end+ sign_in writer('manage_glossary')++ get new_organisation_project_meeting_term_correction_path(organisation, project, foreign.id, mark: browser_mark,+ digest: digest),+ headers: frame+ expect(response).to have_http_status(:not_found)+ post organisation_project_meeting_term_correction_path(organisation, project, foreign.id),+ params: correction_params, headers: stream+ expect(response).to have_http_status(:not_found)+ expect(ActsAsTenant.without_tenant { foreign.reload.transcript }).to eq(transcript)+ end++ it 'refuses a member of another organisation' do+ stranger_org = create(:organisation)+ stranger = ActsAsTenant.with_tenant(stranger_org) do+ user = create(:user)+ create(:membership, user: user, organisation: stranger_org,+ role: create(:role, organisation: stranger_org, title: Role::ACCOUNT_ADMIN_TITLE), active: true)+ user+ end+ sign_in stranger++ get new_path, headers: frame+ expect(response.status).to be_in([302, 404])+ post_correction+ expect(response.status).to be_in([302, 404])+ expect(meeting.reload.transcript).to eq(transcript)+ expect(TermCorrection.count).to eq(0)+ end+ end+end