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
fix(notifications): find project event recipients by the event's area
Guido Boyke0bfa08b83f53
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.ymlindex 409388f..12a8031 100644--- a/.github/workflows/guards.yml+++ b/.github/workflows/guards.yml@@ -600,6 +600,7 @@ jobs:spec/services/notifications/area_rights_spec.rbspec/services/notifications/fanout_service_area_gate_spec.rbspec/services/notifications/project_event_area_spec.rb+ spec/services/notifications/fanout_service_project_event_recipients_spec.rbspec/requests/api/project_event_notifications_spec.rbspec/services/tickets/serializer_spec.rbspec/services/tickets/resolve_columns_spec.rbdiff --git a/app/models/concerns/notifications/constants.rb b/app/models/concerns/notifications/constants.rbindex a8d5298..0eea597 100644--- a/app/models/concerns/notifications/constants.rb+++ b/app/models/concerns/notifications/constants.rb@@ -250,6 +250,9 @@ module Notifications'ticket.ticket_commented' => EVENT_TYPE_TICKET_COMMENTED,'post.created' => EVENT_TYPE_TICKET_COMMENTED,'project.note_created' => EVENT_TYPE_DOCUMENT_ADDED,+ # Project news like project.updated. The action fallback below would make it a+ # system message: score 80 and more, so a mail at once to every account admin.+ 'project.created' => EVENT_TYPE_PROJECT_ANNOUNCEMENT,'mention.created' => EVENT_TYPE_MENTION,'ticket.moved' => EVENT_TYPE_SYSTEM_MESSAGE,diff --git a/app/models/project.rb b/app/models/project.rbindex c4858f9..c470f33 100644--- a/app/models/project.rb+++ b/app/models/project.rb@@ -119,6 +119,12 @@ class Project < ApplicationRecordAccessCheck::ProjectAccessService.users_with_access(self, action, area)end+ # Everybody with read access in at least one area (any area will do, the question+ # project news ask) — delegates to ProjectAccessService.+ def users_with_any_access+ AccessCheck::ProjectAccessService.users_with_any_access(self)+ end+# Who may be ASSIGNED to (or made to watch) a ticket of this project: whoever# may read its tickets, among the ACTIVE members. users_with_access answers# who has access and keeps a deactivated member, whose permission rows stay;diff --git a/app/services/access_check/project_access_service.rb b/app/services/access_check/project_access_service.rbindex a56fcd0..10d72fd 100644--- a/app/services/access_check/project_access_service.rb+++ b/app/services/access_check/project_access_service.rb@@ -323,6 +323,14 @@ module AccessCheckUser.where(id: all_user_ids)end+ # Inverse of can_access_project?: everybody with read access to the project in at+ # least one area of ProjectPermission (the counterpart of openable_project_ids).+ # Like users_with_access it still names a deactivated member; a caller that acts on+ # the list asks can_access_project? for each of them.+ def users_with_any_access(project)+ User.where(id: ProjectPermission.access_areas.flat_map { |area| users_with_access(project, :read, area).pluck(:id) })+ end+# All people the given user "knows": every person with access to at least# one of the projects accessible to this user (= union of users_with_access# over accessible_projects). Org admins/owners see the whole organisation. Suppliesdiff --git a/app/services/notifications/CLAUDE.md b/app/services/notifications/CLAUDE.mdindex eee6219..5335dbd 100644--- a/app/services/notifications/CLAUDE.md+++ b/app/services/notifications/CLAUDE.md@@ -1,4 +1,4 @@-# Karte: app/services/notifications (Stand: 2026-10-08)+# Karte: app/services/notifications (Stand: 2026-10-31)Verarbeitet OutboxEvents zu Notifications. Die Gesamtkette (Trackable → Activity → OutboxEvent →OutboxConsumeJob → hier) ist kartiert in `docs/architektur/seiteneffekt_ketten.md`.@@ -54,10 +54,18 @@ OutboxConsumeJob → hier) ist kartiert in `docs/architektur/seiteneffekt_ketten`EmailLog#check_and_disable_notifications`). Sie ist unsichtbar, weil JEDER Inbox-Leserauf `channel_in_app` filtert: ein neuer Leser ohne diesen Filter würde sie zeigen. Wächter: `area_rights_spec.rb`,`fanout_service_area_gate_spec.rb`, `project_event_area_spec.rb`,- `spec/requests/api/project_event_notifications_spec.rb`. ⚠️ Projekt-Ereignisse finden- ihre Empfänger heute nur über das Projekt-Abo: `find_generic_recipients` fragt- `users_with_access(:read, :general)`, das wirft, und der `rescue` liefert `[]` (auch ohne- die Kontoadmins). **Jeder Leser** (Liste, Zahl,+ `spec/requests/api/project_event_notifications_spec.rb`. **Wen ein Projekt-Ereignis+ erreicht** (seit 31.10.2026, davor wegen eines nicht existierenden Bereichs nur+ Abonnenten): jeden, der den Bereich des Ereignisses lesen darf, Kontoadmins und Rollen mit+ Recht auf alle Projekte eingeschlossen, dazu die Abonnenten; Projektnachrichten jeden mit+ irgendeinem Recht im Projekt (`Project#users_with_any_access`). Die Suche kennt kein+ `rescue`: schlägt sie fehl, schlägt das Ereignis fehl und `OutboxEvent#mark_failed` plant+ neu.+ Abschalten geht je Ereignistyp in den Einstellungen, stumm bleibt ein Abo im Modus+ `mute`. ⚠️ Für diese Empfänger ist das nur die Inbox: eine Mail geht ab Score 80 sofort+ raus, und ohne Abo erreicht kein Projekt-Ereignis diese Zahl. Dafür ist `project.created`+ ein `project_announcement` und kein `system_message` (Grundwert 80). Ein neues Ereignis+ gehört in die Tabelle von `fanout_service_project_event_recipients_spec.rb`. **Jeder Leser** (Liste, Zahl,Badge, Punkt) geht über `inbox_unread` / `accessible_for` / `policy_scope`, nie über einnacktes `user.notifications` oder `Notification.where`: erzwungen von`spec/architecture/notification_read_guard_spec.rb` (Ausnahmeliste mit Anzahl je Datei,diff --git a/app/services/notifications/fanout_service.rb b/app/services/notifications/fanout_service.rbindex 0477248..2c0d23a 100644--- a/app/services/notifications/fanout_service.rb+++ b/app/services/notifications/fanout_service.rb@@ -214,7 +214,7 @@ module Notificationscase notifiablewhen Project- project_members = find_project_members_with_access_optimized(notifiable, :general)+ project_members = find_project_members_with_access_optimized(notifiable, gated_area_for(notifiable))recipients.merge(project_members)recipients.merge(active_subscriber_users)@@ -538,32 +538,19 @@ module Notifications.where(users: { active: true })end+ # Everybody who may read `area` of the project, account admins included. nil is+ # project news, any area will do (Notification.area_for). An event without a rule+ # has no area to look up and reaches nobody (see #with_current_access).+ #+ # Deliberately no rescue. Until 2026-10-31 one answered with an empty list here,+ # so a lookup that raised on every project event passed as a success. Nothing is+ # written yet at this point: a failure leaves the event to its retry+ # (OutboxEvent#mark_failed).def find_project_members_with_access_optimized(project, area)- return [] unless project-- begin- admin_user_ids = @organisation.memberships- .joins(:user, :role)- .where(active: true, roles: { title: 'account_admin' })- .pluck(:user_id)-- project_user_ids = []- if project.respond_to?(:users_with_access)- project_users = project.users_with_access(:read, area)- project_user_ids = project_users.respond_to?(:pluck) ? project_users.pluck(:id) : []- end-- all_user_ids = (admin_user_ids + project_user_ids).uniq- return [] if all_user_ids.empty?+ return [] if project.nil? || area == Notification::UNMAPPED_EVENT- User.active- .includes(:memberships, :roles)- .where(id: all_user_ids)- .to_a- rescue StandardError => e- Rails.logger.warn "Failed to find project members (optimized): #{e.message}"- []- end+ readers = area ? project.users_with_access(:read, area) : project.users_with_any_access+ User.active.includes(:memberships, :roles).where(id: readers.select(:id)).to_aenddef derive_event_typediff --git a/spec/models/concerns/notifications/constants_derive_event_type_spec.rb b/spec/models/concerns/notifications/constants_derive_event_type_spec.rbindex 23fbbfa..b34d515 100644--- a/spec/models/concerns/notifications/constants_derive_event_type_spec.rb+++ b/spec/models/concerns/notifications/constants_derive_event_type_spec.rb@@ -25,6 +25,15 @@ RSpec.describe Notifications::Constants, '.derive_event_type' doendend+ # A key beats the action fallback: a new project is project news, not a system message+ # (fanout_service_project_event_recipients_spec.rb says what that keeps from happening).+ describe 'a new project' do+ let(:key) { 'project.created' }+ let(:action) { 'created' }++ it { is_expected.to eq('project_announcement') }+ end+describe 'explicit overrides (action fallback)' dolet(:key) { nil }diff --git a/spec/services/access_check/project_access_service_spec.rb b/spec/services/access_check/project_access_service_spec.rbindex d21d2a6..a132f96 100644--- a/spec/services/access_check/project_access_service_spec.rb+++ b/spec/services/access_check/project_access_service_spec.rb@@ -422,6 +422,60 @@ RSpec.describe AccessCheck::ProjectAccessService doendend+ # The other direction of .can_access_project?, for project news ("any area will do").+ # Two versions of one rule drift, so they are held against each other, person by person.+ describe '.users_with_any_access (the inverse of .can_access_project?)' do+ def member(role: regular_role, active: true)+ create(:user).tap do |person|+ create(:membership, user: person, organisation: organisation, role: role, active: active)+ end+ end++ def role_reading(area)+ create(:role, organisation: organisation).tap do |role|+ create(:permission, role: role, category: 'projects', action: "read_access_#{area}_all_projects", allowed: true)+ end+ end++ it 'names exactly the people .can_access_project? lets in' do+ ActsAsTenant.with_tenant(organisation) do+ through_role = member(role: role_reading(:notes))+ direct = member.tap { |person| create(:project_permission, user: person, project: project, documents_access: 'read_only') }+ blocked = member(role: role_reading(:notes)).tap { |person| create(:project_permission, user: person, project: project) }+ empty_row = member.tap { |person| create(:project_permission, user: person, project: project) }+ people = [admin_user, through_role, direct, blocked, empty_row, user]++ listed = described_class.users_with_any_access(project).where(id: people.map(&:id))++ expect(listed).to contain_exactly(admin_user, through_role, direct)+ expect(people.select { |person| described_class.can_access_project?(person, project) })+ .to contain_exactly(*listed)+ end+ end++ it 'finds a reader of each area alone' do+ ActsAsTenant.with_tenant(organisation) do+ readers = ProjectPermission.access_areas.index_with do |area|+ member.tap { |person| create(:project_permission, user: person, project: project, "#{area}_access": 'read_only') }+ end++ expect(described_class.users_with_any_access(project)).to include(*readers.values)+ end+ end++ # Like .users_with_access: the list is who holds a right, and who may act on it is+ # asked of each person. Notifications::FanoutService#with_current_access does.+ it 'still names a deactivated member, whom .can_access_project? refuses' do+ ActsAsTenant.with_tenant(organisation) do+ deactivated = member(active: false)+ create(:project_permission, user: deactivated, project: project, tickets_access: 'read_only')++ expect(described_class.users_with_any_access(project)).to include(deactivated)+ expect(described_class.can_access_project?(deactivated, project)).to be(false)+ end+ end+ end+# .users_with_access — the inverse query (who can access THIS project). It had# no direct coverage here; the existing tests live in project_spec.rb (via# Project#users_with_access) and cover admin + global-role + direct-permissiondiff --git a/spec/services/notifications/fanout_service_project_event_recipients_spec.rb b/spec/services/notifications/fanout_service_project_event_recipients_spec.rbnew file mode 100644index 0000000..2d510f1--- /dev/null+++ b/spec/services/notifications/fanout_service_project_event_recipients_spec.rb@@ -0,0 +1,297 @@+# frozen_string_literal: true++require 'rails_helper'++# WHO an event on a project reaches. project_event_area_spec.rb holds the other half, who+# may see it: the gate that every recipient passes.+#+# Until 2026-10-31 the lookup asked for an area that does not exist. It raised on every+# event, a rescue answered with an empty list, and only people with a subscription to the+# project were left: never an account admin, never someone reading through a role. The+# only sign of it was a warning in the log. The lookup now asks for the area of the event,+# and a failure stays a failure.+RSpec.describe Notifications::FanoutService, 'recipients of a project event', :ci_guard do+ let(:organisation) { create(:organisation) }+ let(:project) { create(:project, organisation: organisation) }+ let(:admin_role) { create(:admin_role, organisation: organisation) }++ before { ActsAsTenant.current_tenant = organisation }++ let!(:actor) { account_admin }++ after do+ ActsAsTenant.current_tenant = nil+ Current.reset+ end++ def account_admin(active: true)+ create(:user).tap do |user|+ create(:membership, user: user, organisation: organisation, role: admin_role, active: active)+ end+ end++ # Reads through a role with a right on all projects, without a row on this project.+ def role_reader(*areas)+ role = create(:role, organisation: organisation)+ areas.each do |area|+ create(:permission, role: role, category: 'projects', action: "read_access_#{area}_all_projects", allowed: true)+ end+ create(:user).tap do |user|+ create(:membership, user: user, organisation: organisation, role: role, active: true)+ end+ end++ # A direct member who, unlike one added the normal way, has no subscription.+ def member_without_subscription(*areas)+ create(:user).tap do |user|+ create(:membership, user: user, organisation: organisation, role: create(:role, organisation: organisation), active: true)+ create(:project_permission, user: user, project: project, skip_auto_subscribe: true,+ **areas.to_h { |area| [:"#{area}_access", 'read_only'] })+ end+ end++ def fan_out(action)+ activity = create(:activity, organisation: organisation, trackable: project, actor: actor, action: action,+ key: "project.#{action}", parameters: {})+ Prosopite.pause { described_class.new(OutboxEvent.find_by!(activity: activity)).call }+ end++ def received(user, action, channel: 'in_app')+ Notification.where(recipient: user, notifiable: project, channel: channel)+ .where(Arel.sql("payload->>'action' = :action"), action: action)+ end++ describe 'an account admin without a subscription' do+ let!(:admin) { account_admin }++ %w[updated created ticket_moved_in note_created document_created meeting_created member_added].each do |action|+ it "receives #{action}" do+ expect(fan_out(action)).to include(success: true)+ expect(received(admin, action)).to exist+ end+ end++ it 'does not hear about their own action' do+ fan_out('updated')++ expect(received(actor, 'updated')).not_to exist+ end++ # Someone who has worked on the project: a mute also lowers the score, and for them+ # that alone stays above the threshold, so the mute itself has to hold.+ it 'is told by a muted project to stay out of it, in the inbox and by mail' do+ create(:activity, organisation: organisation, trackable: project, actor: admin, action: 'updated',+ key: 'project.updated', skip_notifications: true)+ NotificationSubscription.create!(user: admin, subscribable: project, mode: 'mute')++ fan_out('updated')++ expect(Notification.where(recipient: admin)).not_to exist+ end++ # There is no project switch on any page: the event type in the notification settings+ # is how an admin turns this down. Per type, so the other type still arrives.+ it 'can turn an event type off in the notification settings' do+ create(:notification_preference, user: admin, organisation: organisation, event_type: 'project_announcement',+ channel: 'in_app', enabled: false, frequency: 'never')++ fan_out('updated')+ fan_out('note_created')++ expect(received(admin, 'updated')).not_to exist+ expect(received(admin, 'note_created')).to exist+ end+ end++ describe 'a deactivated account admin' do+ it 'receives nothing, while an active one does' do+ deactivated = account_admin(active: false)+ active = account_admin++ fan_out('updated')++ expect(received(active, 'updated')).to exist+ expect(Notification.where(recipient: deactivated)).not_to exist+ end+ end++ # Not the membership but the account: can_access_project? only knows the membership,+ # so here the check on the user is the only thing left.+ describe 'an account admin whose user is switched off' do+ it 'receives nothing, while an active one does' do+ switched_off = account_admin.tap { |user| user.update_column(:active, false) }+ active = account_admin++ fan_out('updated')++ expect(received(active, 'updated')).to exist+ expect(Notification.where(recipient: switched_off)).not_to exist+ end+ end++ describe 'a reader through a role, without a row on the project' do+ let!(:notes_reader) { role_reader(:notes) }++ it 'receives the events of their area and no others' do+ fan_out('note_created')+ fan_out('ticket_moved_in')++ expect(received(notes_reader, 'note_created')).to exist+ expect(received(notes_reader, 'ticket_moved_in')).not_to exist+ end++ it 'receives project news, which ask for any area' do+ fan_out('updated')++ expect(received(notes_reader, 'updated')).to exist+ end++ # Actors::RevokeProjectMember keeps a row of nothing but no_access, because the right+ # of the role would take over without it.+ it 'receives nothing once blocked on this project' do+ create(:project_permission, user: notes_reader, project: project, skip_auto_subscribe: true)++ fan_out('note_created')+ fan_out('updated')++ expect(Notification.where(recipient: notes_reader)).not_to exist+ end+ end++ describe 'a direct member without a subscription' do+ let!(:tickets_reader) { member_without_subscription(:tickets) }++ it 'has no subscription to start from' do+ expect(NotificationSubscription.where(user: tickets_reader)).not_to exist+ end++ it 'receives the events of their area and no others' do+ fan_out('ticket_moved_in')+ fan_out('note_created')++ expect(received(tickets_reader, 'ticket_moved_in')).to exist+ expect(received(tickets_reader, 'note_created')).not_to exist+ end++ it 'receives project news' do+ fan_out('updated')++ expect(received(tickets_reader, 'updated')).to exist+ end+ end++ # Which event belongs to which area, written out here and not read from+ # Activities::AreaRegistry: the table is what the registry is held against. Every event+ # a project really emits, with one reader per area and nobody else in the running.+ describe 'each event, among one reader per area' do+ let!(:readers) { %i[tickets notes documents meetings members].index_with { |area| member_without_subscription(area) } }++ {+ 'ticket_moved_in' => :tickets, 'ticket_moved_out' => :tickets,+ 'note_created' => :notes, 'document_created' => :documents,+ 'meeting_created' => :meetings, 'meeting_deleted' => :meetings,+ 'meeting_moved_in' => :meetings, 'meeting_moved_out' => :meetings,+ 'member_added' => :members, 'member_removed' => :members, 'permission_changed' => :members,+ 'updated' => nil, 'created' => nil+ }.each do |action, area|+ it "reaches #{area ? "the reader of #{area}" : 'all of them'} with #{action}" do+ fan_out(action)++ reached = readers.select { |_area, reader| received(reader, action).exists? }.keys+ expect(reached).to match_array(area ? [area] : readers.keys)+ end+ end+ end++ describe 'a member of the organisation with no right on the project' do+ it 'receives nothing, while a reader does' do+ outsider = member_without_subscription+ reader = member_without_subscription(:tickets)++ fan_out('updated')++ expect(received(reader, 'updated')).to exist+ expect(Notification.where(recipient: outsider)).not_to exist+ end+ end++ # A mail goes out at once from score 80 (Notification#should_send_immediately?). Who is+ # here by role alone has no subscription bonus, so nothing about a project may reach+ # that line, also not for someone who has worked on the project before. Every event a+ # project really emits is listed: a new one belongs here.+ describe 'mail to a recipient without a subscription' do+ let!(:admin) { account_admin }++ before do+ create(:activity, organisation: organisation, trackable: project, actor: admin, action: 'updated',+ key: 'project.updated', skip_notifications: true)+ end++ %w[created updated member_added member_removed permission_changed ticket_moved_in ticket_moved_out+ document_created note_created meeting_created meeting_deleted meeting_moved_in meeting_moved_out].each do |action|+ it "is not sent at once for #{action}" do+ fan_out(action)++ row = received(admin, action, channel: 'email').first+ expect(row).to be_present+ expect(row.should_send_immediately?).to be(false), "score #{row.score}, type #{row.event_type}"+ end+ end++ it 'stays what a subscription buys: the line can be crossed' do+ NotificationSubscription.create!(user: admin, subscribable: project, mode: 'follow')++ fan_out('updated')++ expect(received(admin, 'updated', channel: 'email').first.should_send_immediately?).to be(true)+ end+ end++ # Through the real write, not a hand-built activity. The event type decides the mail, and+ # a project's "created" used to fall back on the action alone: a system message, score+ # 80 and more, a mail at once to every admin, and that mail does not even render.+ describe 'a new project' do+ let!(:admin) { account_admin }++ it 'reaches the other admins as project news, not as a system message' do+ Current.user = actor+ new_project = create(:project, organisation: organisation)+ Prosopite.pause { OutboxEvent.where(processed_at: nil).find_each { |event| described_class.new(event).call } }++ rows = Notification.where(recipient: admin, notifiable: new_project)+ expect(rows.pluck(:channel)).to contain_exactly('in_app', 'email')+ expect(rows.pluck(:event_type).uniq).to eq(['project_announcement'])+ expect(rows.map(&:should_send_immediately?)).to all(be(false))+ end+ end++ # A rescue that answered with [] made every failure a success. A lookup that fails+ # writes nothing, so a retry starts clean.+ describe 'a failing lookup' do+ let!(:subscriber) { member_without_subscription(:tickets) }+ let(:activity) do+ create(:activity, organisation: organisation, trackable: project, actor: actor, action: 'ticket_moved_in',+ key: 'project.ticket_moved_in', parameters: {})+ end+ let(:event) { OutboxEvent.find_by!(activity: activity) }++ before do+ NotificationSubscription.system_subscribe(user: subscriber, item: project)+ allow(AccessCheck::ProjectAccessService).to receive(:users_with_access).and_raise('connection lost')+ end++ it 'is a failure of the event, and nobody gets half of it' do+ result = Prosopite.pause { described_class.new(event).call }++ expect(result).to include(success: false, error: 'connection lost')+ expect(Notification.where(notifiable: project)).not_to exist+ end++ it 'leaves the event to its retry' do+ Prosopite.pause { event.process! }++ expect(event.reload).to have_attributes(processed_at: nil, retry_count: 1)+ expect(event.available_at).to be > Time.current+ end+ end+enddiff --git a/spec/services/notifications/fanout_service_project_id_spec.rb b/spec/services/notifications/fanout_service_project_id_spec.rbindex 785cc0f..8f30140 100644--- a/spec/services/notifications/fanout_service_project_id_spec.rb+++ b/spec/services/notifications/fanout_service_project_id_spec.rb@@ -169,11 +169,6 @@ RSpec.describe Notifications::FanoutService, type: :service doendit 'sets project_id for Project notifications' do- # Subscribe user to project so they receive notifications- # (find_project_members_with_access_optimized has a bug where users_with_access(:read, :general)- # raises NoMethodError, which causes the entire method to return [] including admin users)- NotificationSubscription.create!(user: user, subscribable: project, mode: 'follow')-activity = create(:activity,organisation: organisation,trackable: project,diff --git a/spec/support/prosopite.rb b/spec/support/prosopite.rbindex d50756b..a046b3f 100644--- a/spec/support/prosopite.rb+++ b/spec/support/prosopite.rb@@ -53,6 +53,7 @@ Prosopite.allow_stack_paths = ['extract_plain_text_content', # Note before_save: per-record ActionText to_plain_text → embeds_attachments'validate_project_default_uniqueness', # DashboardConfiguration: per-record uniqueness validation'validate_custom_attributes', # CustomAttributable: per-record validation loads the project's attribute definitions once per ticket/record save; one query per saved record (not a request N+1) — surfaces only when a spec creates several status-bearing records in one example+ 'users_with_any_access', # ProjectAccessService: one users_with_access lookup per ProjectPermission area (7) for one project, bounded by the area list, the inverse of openable_project_ids — not a data N+1'knowledge_creator_options', # KnowledgeFilterHelper: a constant ONE users_with_access lookup per knowledge area (2) for the creator filter pool — bounded, not a data N+1'backfill_tenant', # Wiki::NoteBackfill: one batched notes scan per organisation (bounded by tenant count) — the repeated identical SQL is the per-tenant loop, not a per-record N+1'ensure_due_date', # DueDateBackfillService: one due_date find_by per project in a one-time backfill loop (bounded by project count), not a request N+1