-
Notifications
You must be signed in to change notification settings - Fork 2
feat(model): Add manager takeover for Chat and manager role for Messa… #168
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dapi
wants to merge
44
commits into
master
Choose a base branch
from
feature/103-manager-reply-from-dashboard
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
44 commits
Select commit
Hold shift + click to select a range
0a9428c
feat(model): Add manager takeover for Chat and manager role for Messa…
dapi 33ef4cb
feat(services): Add manager takeover services (#155) (#166)
dapi 2e27777
feat(api): Add REST endpoints for manager takeover (#156)
dapi be40a13
fix(api): Add JSON error responses and improve test coverage
dapi 07bf862
fix(api): Add ErrorLogger and improve error handling
dapi 6555814
fix(api): Re-raise fatal DB errors per CLAUDE.md guidelines
dapi 54ea8d9
fix(chats): Use preloaded messages in view instead of new query
dapi 4f80aa6
fix(api): Add validation and tests for manager release
dapi f90d6ff
test(api): Add test for unrecognized notify_client values
dapi d582969
feat(chat): Integrate manager mode with bot (#158)
dapi 99b74fc
fix: Improve error handling and logging for manager mode
dapi 5e1e6bd
fix: Improve broadcast and add I18n key for error message
dapi c35136c
feat(chat): UI для отправки сообщений менеджером (#157)
dapi 9ccab9b
fix: Address PR review issues for manager takeover feature
dapi 0281ab4
fix: Address PR review round 2 - important issues 1-4
dapi 4e795ce
fix: Address PR review round 2 - issues 5-6
dapi c5902ae
fix: Fix flaky timezone test in dashboard_stats_service_test
dapi fd8771b
fix: Address critical PR review issues
dapi 11af0de
fix: Address important PR review issues
dapi 03fade9
fix: Address PR review findings for manager mode
dapi e85b476
fix: Resolve 3 critical issues from PR review
dapi d79f44c
style: Fix rubocop Layout offenses
dapi 9ff952f
fix: Address PR review issues 2, 5, 6, 7
dapi 83ade0d
feat: Auto-allow HOST subdomains in development
dapi e70f001
fix: Correct message form field name for manager controller
dapi 5757f2d
refactor: Simplify error handling and move broadcast to Message model
dapi 3378c2c
refactor: Add TenantChatsChannel with tenant authorization
dapi 62331de
refactor: Consolidate manager takeover migrations
dapi da1bccf
refactor: Broadcast all message types to dashboard
dapi 62081b7
refactor: Use Turbo 8 morphing for real-time updates
dapi bb37a32
fix: Address PR review comments
dapi 13be973
refactor: Apply service validation pattern from PR review
dapi 2586ed8
docs: Add rule about not catching programming errors
dapi b3ebada
refactor: Remove unnecessary rescue blocks around analytics
dapi 7d722c6
v0.39.0
dapi 9a53298
feat: Add feature toggle for manager takeover
dapi 1353e26
docs: Add Hotwire guide for AI agents
dapi aaf31af
refactor: Extract TakeoverDurationCalculator and add index on chats.mode
dapi e984e02
style: Fix empty lines at class body end
dapi e470ee7
feat: Replace pagination with infinite scroll in chat sidebar (#172) …
dapi 0923229
fix: Fix chat takeover buttons not responding to clicks (#174)
dapi be347d1
wip: Local changes before rebase
dapi bc620c9
changes
dapi 171160c
Fix .envrc
dapi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| --- | ||
| :major: 0 | ||
| :minor: 38 | ||
| :patch: 1 | ||
| :minor: 39 | ||
| :patch: 0 | ||
| :special: '' | ||
| :metadata: '' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| module ApplicationCable | ||
| # Base channel class for application channels | ||
| class Channel < ActionCable::Channel::Base | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| module ApplicationCable | ||
| # Base ActionCable connection with user authentication | ||
| # | ||
| # Identifies the WebSocket connection by current_user, | ||
| # allowing channels to access the authenticated user. | ||
| # | ||
| # @example Accessing current_user in a channel | ||
| # class MyChannel < ApplicationCable::Channel | ||
| # def subscribed | ||
| # if current_user.has_access_to?(some_resource) | ||
| # stream_from "my_stream" | ||
| # else | ||
| # reject | ||
| # end | ||
| # end | ||
| # end | ||
| # | ||
| class Connection < ActionCable::Connection::Base | ||
| identified_by :current_user | ||
|
|
||
| def connect | ||
| self.current_user = find_verified_user | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def find_verified_user | ||
| user_id = request.session[:user_id] | ||
| user = User.find_by(id: user_id) if user_id | ||
|
|
||
| user || reject_unauthorized_connection | ||
| end | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| # Channel for streaming chat messages with tenant authorization | ||
| # | ||
| # Extends Turbo::StreamsChannel to add tenant-based access control. | ||
| # Only users with access to the chat's tenant can subscribe. | ||
| # | ||
| # @example In views | ||
| # = turbo_stream_from chat, channel: TenantChatsChannel | ||
| # | ||
| # @example In models (broadcasts) | ||
| # broadcasts_to ->(message) { message.chat }, inserts_by: :append | ||
| # | ||
| class TenantChatsChannel < Turbo::StreamsChannel | ||
| def subscribed | ||
| if authorized? | ||
| super | ||
| else | ||
| reject | ||
| end | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def authorized? | ||
| return false unless current_user | ||
| return false unless chat | ||
|
|
||
| current_user.has_access_to?(chat.tenant) | ||
| end | ||
|
|
||
| def chat | ||
| return @chat if defined?(@chat) | ||
|
|
||
| @chat = find_chat_from_stream_name | ||
| end | ||
|
|
||
| # Decodes the signed stream name to find the Chat | ||
| # | ||
| # Stream name is a base64-encoded GlobalID (e.g., "Z2lkOi8vdmFsZXJhL0NoYXQvMQ") | ||
| # Decoded format: "gid://valera/Chat/1" | ||
| # | ||
| # @return [Chat, nil] | ||
| def find_chat_from_stream_name | ||
| stream_name = verified_stream_name_from_params | ||
| return nil unless stream_name | ||
|
|
||
| # Decode the base64-encoded GlobalID | ||
| decoded = Base64.urlsafe_decode64(stream_name) | ||
| gid = GlobalID.parse(decoded) | ||
| return nil unless gid | ||
|
|
||
| record = gid.find | ||
| record.is_a?(Chat) ? record : nil | ||
| rescue ActiveRecord::RecordNotFound, ArgumentError, URI::InvalidURIError => e | ||
| Rails.logger.warn "[TenantChatsChannel] Failed to parse stream name: #{e.class} - #{e.message}" | ||
| nil | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| module Tenants | ||
| module Chats | ||
| # Контроллер для управления режимом менеджера в чате | ||
| # | ||
| # Использует Turbo Streams для обновления UI без перезагрузки страницы. | ||
| # Все endpoints требуют авторизации (owner или member tenant'а). | ||
| # | ||
| # @example Перехват чата | ||
| # POST /chats/:chat_id/manager/takeover | ||
| # | ||
| # @example Отправка сообщения | ||
| # POST /chats/:chat_id/manager/messages | ||
| # { message: { content: "Текст сообщения" } } | ||
| # | ||
| # @example Возврат боту | ||
| # POST /chats/:chat_id/manager/release | ||
| # | ||
| # @since 0.38.0 | ||
| class ManagerController < Tenants::ApplicationController | ||
| include ErrorLogger | ||
|
|
||
| before_action :ensure_manager_takeover_enabled | ||
| before_action :set_chat | ||
|
|
||
| # POST /chats/:chat_id/manager/takeover | ||
| # | ||
| # Менеджер берёт контроль над чатом. | ||
| # После takeover бот перестаёт отвечать, все сообщения | ||
| # от клиента будут видны только в dashboard. | ||
| def takeover | ||
| result = Manager::TakeoverService.call( | ||
| chat: @chat, | ||
| user: current_user, | ||
| timeout_minutes: params[:timeout_minutes].presence&.to_i, | ||
| notify_client: notify_client_param | ||
| ) | ||
|
|
||
| if result.success? | ||
| @chat.reload | ||
| # renders takeover.turbo_stream.slim | ||
| else | ||
| render_turbo_stream_error(result.error) | ||
| end | ||
| end | ||
|
|
||
| # POST /chats/:chat_id/manager/messages | ||
| # | ||
| # Отправляет сообщение от имени менеджера клиенту в Telegram. | ||
| # Требует чтобы чат был в режиме менеджера и | ||
| # текущий пользователь был активным менеджером. | ||
| # | ||
| # @param content [String] текст сообщения (обязательный) | ||
| def create_message | ||
| content = message_params[:content] | ||
|
|
||
| if content.blank? | ||
| return render_turbo_stream_error(t('.content_required')) | ||
| end | ||
|
|
||
| result = Manager::MessageService.call( | ||
| chat: @chat, | ||
| user: current_user, | ||
| content: | ||
| ) | ||
|
|
||
| if result.success? | ||
| @message = result.message | ||
| # renders create_message.turbo_stream.slim | ||
| else | ||
| render_turbo_stream_error(result.error) | ||
| end | ||
| end | ||
|
|
||
| # POST /chats/:chat_id/manager/release | ||
| # | ||
| # Возвращает чат боту. После release бот снова | ||
| # начинает отвечать на сообщения клиента. | ||
| def release | ||
| result = Manager::ReleaseService.call( | ||
| chat: @chat, | ||
| user: current_user, | ||
| notify_client: notify_client_param | ||
| ) | ||
|
|
||
| if result.success? | ||
| @chat.reload | ||
| # renders release.turbo_stream.slim | ||
| else | ||
| render_turbo_stream_error(result.error) | ||
| end | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def set_chat | ||
| @chat = current_tenant.chats.find(params[:chat_id]) | ||
| rescue ActiveRecord::RecordNotFound => e | ||
| log_error(e, error_context) | ||
| render_turbo_stream_error(t('.chat_not_found'), status: :not_found) | ||
| end | ||
|
|
||
| # Парсит параметр notify_client как boolean | ||
| # По умолчанию true, если параметр не передан, nil, или нераспознанное значение | ||
| def notify_client_param | ||
| value = params[:notify_client] | ||
| return true if value.nil? | ||
|
|
||
| result = ActiveModel::Type::Boolean.new.cast(value) | ||
| result.nil? ? true : result | ||
| end | ||
|
|
||
| def message_params | ||
| params.require(:message).permit(:content) | ||
| end | ||
|
|
||
| def error_context | ||
| { | ||
| controller: self.class.name, | ||
| action: action_name, | ||
| chat_id: params[:chat_id], | ||
| user_id: current_user&.id, | ||
| tenant_id: current_tenant&.id | ||
| } | ||
| end | ||
|
|
||
| # Проверяет что функция manager takeover включена в конфигурации | ||
| def ensure_manager_takeover_enabled | ||
| return if ApplicationConfig.manager_takeover_enabled | ||
|
|
||
| render_turbo_stream_error(t('.feature_disabled'), status: :not_found) | ||
| end | ||
|
|
||
| # Рендерит ошибку через Turbo Stream в flash контейнер | ||
| def render_turbo_stream_error(message, status: :unprocessable_entity) | ||
| render turbo_stream: turbo_stream.update( | ||
| 'flash', | ||
| partial: 'tenants/shared/flash', | ||
| locals: { message:, type: :error } | ||
| ), status: | ||
| end | ||
| end | ||
| end | ||
| end |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.