Compare commits

...
Author SHA1 Message Date
Sojan Jose 0f914fa2ab Merge branch 'release/4.10.0'
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
2026-01-15 22:20:22 -08:00
Sojan Jose aee0740bcc Bump version to 4.10.0 2026-01-15 22:19:33 -08:00
96b5780ea7 fix: Respect survey label rules for WhatsApp CSAT template (#13285)
Ensure CSAT survey label rules are evaluated once in CsatSurveyService
before any channel-specific sending (including WhatsApp/Twilio
templates), remove the duplicated rule check from the template builder,
and cover the blocking-label scenario in service specs while simplifying
the template specs accordingly.

Co-authored-by: Sojan Jose <sojan@pepalo.com>
2026-01-15 22:16:00 -08:00
d451615811 fix: prevent NoMethodError in mute helpers when contact is nil (#13277)
## Linear Ticket

https://linear.app/chatwoot/issue/CW-4569/nomethoderror-undefined-method-blocked-for-nil-nomethoderror

## Description
Fixes NoMethodError in ConversationMuteHelpers that occurs during
contact deletion race condition.
When a contact is deleted, there's a brief window (~50-150ms) where
contact_id becomes nil but conversations still exist. If ResolutionJob
runs during this window, the muted? method crashes trying to call
blocked? on nil.Fixes # (issue)

## Type of change

- [ ] Bug fix (non-breaking change which fixes an issue)

## How Has This Been Tested?

- Created orphaned conversations (contact_id = nil)
- Called muted?, mute!, unmute! - all return gracefully
- Verified async deletion still works correctly

## Checklist:

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my code
- [ ] I have commented on my code, particularly in hard-to-understand
areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published in downstream
modules



Co-authored-by: Sojan Jose <sojan@pepalo.com>
2026-01-15 22:00:09 -08:00
7d68c25c97 chore: upgrade node to v24.13 (#13291)
- upgrade node to v24.13

Co-authored-by: Sojan Jose <sojan@pepalo.com>
2026-01-15 20:28:13 -08:00
3e560cb4cc chore: Remove year in review from sidebar UI (#13292)
Remove the Year In review from the UI

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 19:57:01 -08:00
PranavandGitHub a8b302d4cd feat(ee): Review Notes for CSAT Reports (#13289)
CSAT scores are helpful, but on their own they rarely tell the full
story. A drop in rating can come from delayed timelines, unclear
expectations, or simple misunderstandings, even when the issue itself
was handled correctly.

Review Notes for CSAT let admins/report manager roles add internal-only
context next to each CSAT response. This makes it easier to interpret
scores properly and focus on patterns and root causes, not just numbers.


<img width="2170" height="1680" alt="image"
src="https://github.com/user-attachments/assets/56df7fab-d0a7-4a94-95b9-e4c459ad33d5"
/>


### Why this matters

* Capture the real context behind individual CSAT ratings
* Clarify whether a low score points to a genuine service issue or a
process gap
* Spot recurring themes across conversations and teams
* Make CSAT reviews more useful for leadership reviews and
retrospectives

### How Review Notes work

**View CSAT responses**
Open the CSAT report to see overall metrics, rating distribution, and
individual responses.

**Add a Review Note**
For any CSAT entry, managers can add a Review Note directly below the
customer’s feedback.

**Document internal insights**
Use Review Notes to capture things like:

* Why a score was lower or higher than expected
* Patterns you are seeing across similar cases
* Observations around communication, timelines, or customer expectations

Review Notes are visible only to administrators and people with report
access only. We may expand visibility to agents in the future based on
feedback. However, customers never see them.

Each note clearly shows who added it and when, making it easy to review
context and changes over time.
2026-01-15 19:53:57 -08:00
Gabriel JablonskiandGitHub da42a4e4a1 ci: fixed bundler version to avoid bundler 4.0.4 incompatibility (#13290)
### Problem

Docker builds started failing with a misleading dependency resolution
error:
```
Could not find compatible versions
Because every version of devise-secure_password depends on railties >= 5.0.0, < 8.0.0
...
```

### Root Cause

[Bundler
4.0.4](https://github.com/ruby/rubygems/releases/tag/bundler-v4.0.4) was
released on January 14, 2026. The Dockerfile used `gem install bundler`
without version pinning, which installed the latest (4.0.4) instead of
the version specified in `Gemfile.lock` (2.5.16).

### Fix

- Pin Bundler installation to match `Gemfile.lock`: `gem install bundler
-v "$BUNDLER_VERSION"`
- Update `BUNDLER_VERSION` from 2.5.11 to 2.5.16

### ⚠️ Note

Fix found by Claude while checking why the deploy was failing, and have
not yet checked for alternatives which might be more appropriate, so
further investigation might be required.
2026-01-15 19:51:16 -08:00
Muhsin KelothandGitHub 8eb0558b0a fix: Case-insensitive language matching for WhatsApp template messages (#13269)
Fixes https://github.com/chatwoot/chatwoot/issues/13257
When sending WhatsApp template messages via API with `processed_params`,
users receiving error `(#132000) Number of parameters does not match the
expected number of params` from WhatsApp. The find template method
performed case-sensitive string comparison on language codes. If a user
sent `language: "ES"` but the template was stored as `language: "es"`,
the template wouldn't be found, resulting in empty `components: []`
being sent to WhatsApp.
2026-01-14 17:33:02 +04:00
Tanmay Deep SharmaandGitHub ee7187d2ed fix: prevent deserialization error on deletion (#13264) 2026-01-14 18:00:12 +05:30
4e0b091ef8 fix: Prevent unsupported file types on clipboard paste (#13182)
# Pull Request Template

## Description

This PR adds file type validation for clipboard-pasted attachments and
prevents unsupported file types from being attached across channels.

https://developers.chatwoot.com/self-hosted/supported-features#outgoing-attachments-supported-file-types

Fixes
https://linear.app/chatwoot/issue/CW-6233/bug-unsupported-file-types-allowed-via-clipboard-paste

## Type of change

- [x] Bug fix (non-breaking change which fixes an issue)

## How Has This Been Tested?

**Loom video**

**Before**
https://www.loom.com/share/882c335be4894d86b9e149d9f7560e72

**After**
https://www.loom.com/share/90ad9605fc4446afb94a5b8bbe48f7db


## Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my code
- [x] I have commented on my code, particularly in hard-to-understand
areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published in downstream
modules

---------

Co-authored-by: Muhsin Keloth <muhsinkeramam@gmail.com>
2026-01-14 13:07:46 +04:00
Sivin VargheseandGitHub daaa18b18a chore: Use widget color for chat input focus state (#13214) 2026-01-14 14:33:56 +05:30
Aakash BakhleandGitHub bddf06907b fix: double counting in langfuse instrumentation (#13202) 2026-01-13 18:52:38 +05:30
1a220b2982 chore: Improve compose new conversation form (#13176)
Co-authored-by: Muhsin Keloth <muhsinkeramam@gmail.com>
2026-01-13 18:52:10 +05:30
c483034a07 feat: Add support for sending CSAT surveys via templates (Whatsapp Twilio) (#13143)
Fixes
https://linear.app/chatwoot/issue/CW-6189/support-for-sending-csat-surveys-via-approved-whatsapp

---------

Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com>
Co-authored-by: Vinay Keerthi <11478411+stonecharioteer@users.noreply.github.com>
Co-authored-by: iamsivin <iamsivin@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-01-13 16:32:02 +04:00
Shivam MishraandGitHub 7b51939f07 fix: country_code should be checked against the contact (#13186) 2026-01-13 14:47:27 +05:30
821a5b85c2 feat: Add conversations summary CSV export (#13110)
# Pull Request Template

## Description

This PR adds support for exporting conversation summary reports as CSV.
Previously, the Conversations report incorrectly showed an option to
download agent reports; this has now been fixed to export
conversation-level data instead.

Fixes
https://linear.app/chatwoot/issue/CW-6176/conversation-reports-export-button-exports-agent-reports-instead

## Type of change

- [x] Bug fix (non-breaking change which fixes an issue)
- [x] New feature (non-breaking change which adds functionality)

## How Has This Been Tested?

### Screenshot
<img width="1859" height="1154" alt="image"
src="https://github.com/user-attachments/assets/419d26f4-fda9-4782-aea6-55ffad0c37ab"
/>



## Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my code
- [ ] I have commented on my code, particularly in hard-to-understand
areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published in downstream
modules

Co-authored-by: Muhsin Keloth <muhsinkeramam@gmail.com>
2026-01-13 12:30:26 +04:00
PranavandGitHub 0917e1a646 feat: Add an API to support querying metrics by ChannelType (#13255)
This API gives you how many conversations exist per channel, broken down
by status in a given time period. The max time period is capped to 6
months for now.

**Input Params:**
- **since:** Unix timestamp (seconds) - start of date range
- **until:** Unix timestamp (seconds) - end of date range


**Response Payload:**

```json
{
  "Channel::Sms": {
    "resolved": 85,
    "snoozed": 10,
    "open": 5,
    "pending": 5,
    "total": 100
  },
  "Channel::Email": {
    "resolved": 72,
    "snoozed": 15,
    "open": 13,
    "pending": 13,
    "total": 100
  },
  "Channel::WebWidget": {
    "resolved": 90,
    "snoozed": 7,
    "open": 3,
    "pending": 3,
    "total": 100
  }
}
```

**Definitons:**
resolved = Number of conversations created within the selected time
period that are currently marked as resolved.
snoozed = Number of conversations created within the selected time
period that are currently marked as snoozed.
pending = Number of conversations created within the selected time
period that are currently marked as pending.
open = Number of conversations created within the selected time period
that are currently open.
total = Total number of conversations created within the selected time
period, across all statuses.
2026-01-12 23:18:47 -08:00
Sojan Jose 9407cc2ad5 Merge branch 'hotfix/4.9.2' into develop 2026-01-12 09:15:23 -08:00
Sojan Jose 59663dd558 Merge branch 'hotfix/4.9.2'
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
2026-01-12 09:15:17 -08:00
Sojan Jose ff68c3a74f Bump version to 4.9.2 2026-01-12 09:14:25 -08:00
Shivam MishraandGitHub 58cec84b93 feat: sanitize html before assiging it to tempDiv (#13252) 2026-01-12 22:41:37 +05:30
Sojan Jose 8311657f9c Merge branch 'release/4.9.1'
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
2025-12-22 18:56:05 -08:00
Sojan Jose 73140998ff Merge branch 'release/4.9.0'
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
2025-12-19 19:12:55 -08:00
Sojan Jose 4e9f644646 Merge branch 'release/4.8.0'
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
2025-11-18 18:41:51 -08:00
Sojan Jose bfa8a8ed60 Merge branch 'release/4.7.0'
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
2025-10-15 22:11:02 -07:00
Sojan Jose 7ab60d9f9c Merge branch 'release/4.6.0'
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
2025-09-19 13:44:30 +05:30
Sojan Jose faac1486e9 Merge branch 'release/4.5.2'
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
2025-08-20 21:45:34 +02:00
Sojan Jose 8340bd615c Merge branch 'release/4.5.1'
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
2025-08-20 16:25:15 +02:00
Sojan Jose 75d3569f22 Merge branch 'release/4.5.0'
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
2025-08-18 18:40:04 +02:00
Sojan Jose 545453537f Merge branch 'release/4.4.0'
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
2025-07-16 00:10:42 -07:00
Sojan d75702c6b2 Merge branch 'release/4.3.0'
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
2025-06-17 17:29:27 -07:00
Sojan b76ec878f1 Merge branch 'release/4.2.0'
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
2025-05-20 00:12:06 -07:00
Sojan a954e1eaca Merge branch 'release/4.1.0'
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
2025-04-16 23:10:46 -07:00
Sojan bc5f1722e1 Merge branch 'release/4.0.4'
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
2025-03-21 18:55:06 -07:00
Sojan 8f39e62570 Merge branch 'release/4.0.3'
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
2025-02-27 21:05:35 -08:00
Sojan 7520ca7a99 Merge branch 'release/4.0.2'
Publish Chatwoot EE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot EE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot EE docker images / merge (push) Blocked by required conditions
Publish Chatwoot CE docker images / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Chatwoot CE docker images / build (linux/arm64, ubuntu-22.04-arm) (push) Waiting to run
Publish Chatwoot CE docker images / merge (push) Blocked by required conditions
2025-02-21 17:04:31 -08:00
Sojan 35f4e63605 Merge branch 'release/4.0.1'
Publish Chatwoot CE docker images / build (push) Waiting to run
2025-01-17 01:13:27 +05:30
Sojan 5773089865 Merge branch 'release/4.0.0'
Publish Chatwoot CE docker images / build (push) Waiting to run
2025-01-16 17:11:45 +05:30
Sojan d01c7d3fa7 Merge branch 'release/3.16.0'
Publish Chatwoot CE docker images / build (push) Waiting to run
2024-12-17 23:03:24 +05:30
Sojan 959d2c0d8c Merge branch 'release/3.15.0'
Publish Chatwoot CE docker images / build (push) Waiting to run
2024-11-19 18:02:07 +08:00
Vishnu Narayanan 622f29a0b7 Merge branch 'hotfix/3.14.1'
Publish Chatwoot CE docker images / build (push) Waiting to run
2024-10-22 16:03:47 +05:30
126 changed files with 3788 additions and 776 deletions
+3 -3
View File
@@ -76,7 +76,7 @@ jobs:
bundle install
- node/install:
node-version: '24.12'
node-version: '24.13'
- node/install-pnpm
- node/install-packages:
pkg-manager: pnpm
@@ -117,7 +117,7 @@ jobs:
steps:
- checkout
- node/install:
node-version: '24.12'
node-version: '24.13'
- node/install-pnpm
- node/install-packages:
pkg-manager: pnpm
@@ -148,7 +148,7 @@ jobs:
steps:
- checkout
- node/install:
node-version: '24.12'
node-version: '24.13'
- node/install-pnpm
- node/install-packages:
pkg-manager: pnpm
+1 -1
View File
@@ -10,7 +10,7 @@ services:
dockerfile: .devcontainer/Dockerfile.base
args:
VARIANT: 'ubuntu-22.04'
NODE_VERSION: '24.12.0'
NODE_VERSION: '24.13.0'
RUBY_VERSION: '3.4.4'
# On Linux, you may need to update USER_UID and USER_GID below if not your local UID is not 1000.
USER_UID: '1000'
+1 -1
View File
@@ -11,7 +11,7 @@ services:
dockerfile: .devcontainer/Dockerfile
args:
VARIANT: 'ubuntu-22.04'
NODE_VERSION: '24.12.0'
NODE_VERSION: '24.13.0'
RUBY_VERSION: '3.4.4'
# On Linux, you may need to update USER_UID and USER_GID below if not your local UID is not 1000.
USER_UID: '1000'
+1 -1
View File
@@ -1 +1 @@
24.12.0
24.13.0
+1 -1
View File
@@ -1 +1 @@
4.9.1
4.10.0
@@ -0,0 +1,38 @@
class V2::Reports::ChannelSummaryBuilder
include DateRangeHelper
pattr_initialize [:account!, :params!]
def build
conversations_by_channel_and_status.transform_values { |status_counts| build_channel_stats(status_counts) }
end
private
def conversations_by_channel_and_status
account.conversations
.joins(:inbox)
.where(created_at: range)
.group('inboxes.channel_type', 'conversations.status')
.count
.each_with_object({}) do |((channel_type, status), count), grouped|
grouped[channel_type] ||= {}
grouped[channel_type][status] = count
end
end
def build_channel_stats(status_counts)
open_count = status_counts['open'] || 0
resolved_count = status_counts['resolved'] || 0
pending_count = status_counts['pending'] || 0
snoozed_count = status_counts['snoozed'] || 0
{
open: open_count,
resolved: resolved_count,
pending: pending_count,
snoozed: snoozed_count,
total: open_count + resolved_count + pending_count + snoozed_count
}
end
end
@@ -50,3 +50,5 @@ class Api::V1::Accounts::CsatSurveyResponsesController < Api::V1::Accounts::Base
@current_page = params[:page] || 1
end
end
Api::V1::Accounts::CsatSurveyResponsesController.prepend_mod_with('Api::V1::Accounts::CsatSurveyResponsesController')
@@ -1,38 +1,27 @@
class Api::V1::Accounts::InboxCsatTemplatesController < Api::V1::Accounts::BaseController
DEFAULT_BUTTON_TEXT = 'Please rate us'.freeze
DEFAULT_LANGUAGE = 'en'.freeze
before_action :fetch_inbox
before_action :validate_whatsapp_channel
def show
template = @inbox.csat_config&.dig('template')
return render json: { template_exists: false } unless template
service = CsatTemplateManagementService.new(@inbox)
result = service.template_status
template_name = template['name'] || Whatsapp::CsatTemplateNameService.csat_template_name(@inbox.id)
status_result = @inbox.channel.provider_service.get_template_status(template_name)
render_template_status_response(status_result, template_name)
rescue StandardError => e
Rails.logger.error "Error fetching CSAT template status: #{e.message}"
render json: { error: e.message }, status: :internal_server_error
if result[:service_error]
render json: { error: result[:service_error] }, status: :internal_server_error
else
render json: result
end
end
def create
template_params = extract_template_params
return render_missing_message_error if template_params[:message].blank?
# Delete existing template even though we are using a new one.
# We don't want too many templates in the business portfolio, but the create operation shouldn't fail if deletion fails.
delete_existing_template_if_needed
result = create_template_via_provider(template_params)
service = CsatTemplateManagementService.new(@inbox)
result = service.create_template(template_params)
render_template_creation_result(result)
rescue ActionController::ParameterMissing
render json: { error: 'Template parameters are required' }, status: :unprocessable_entity
rescue StandardError => e
Rails.logger.error "Error creating CSAT template: #{e.message}"
render json: { error: 'Template creation failed' }, status: :internal_server_error
end
private
@@ -43,9 +32,9 @@ class Api::V1::Accounts::InboxCsatTemplatesController < Api::V1::Accounts::BaseC
end
def validate_whatsapp_channel
return if @inbox.whatsapp?
return if @inbox.whatsapp? || @inbox.twilio_whatsapp?
render json: { error: 'CSAT template operations only available for WhatsApp channels' },
render json: { error: 'CSAT template operations only available for WhatsApp and Twilio WhatsApp channels' },
status: :bad_request
end
@@ -57,35 +46,36 @@ class Api::V1::Accounts::InboxCsatTemplatesController < Api::V1::Accounts::BaseC
render json: { error: 'Message is required' }, status: :unprocessable_entity
end
def create_template_via_provider(template_params)
template_config = {
message: template_params[:message],
button_text: template_params[:button_text] || DEFAULT_BUTTON_TEXT,
base_url: ENV.fetch('FRONTEND_URL', 'http://localhost:3000'),
language: template_params[:language] || DEFAULT_LANGUAGE,
template_name: Whatsapp::CsatTemplateNameService.csat_template_name(@inbox.id)
}
@inbox.channel.provider_service.create_csat_template(template_config)
end
def render_template_creation_result(result)
if result[:success]
render_successful_template_creation(result)
elsif result[:service_error]
render json: { error: result[:service_error] }, status: :internal_server_error
else
render_failed_template_creation(result)
end
end
def render_successful_template_creation(result)
render json: {
template: {
name: result[:template_name],
template_id: result[:template_id],
status: 'PENDING',
language: result[:language] || DEFAULT_LANGUAGE
}
}, status: :created
if @inbox.twilio_whatsapp?
render json: {
template: {
friendly_name: result[:friendly_name],
content_sid: result[:content_sid],
status: result[:status] || 'pending',
language: result[:language] || 'en'
}
}, status: :created
else
render json: {
template: {
name: result[:template_name],
template_id: result[:template_id],
status: 'PENDING',
language: result[:language] || 'en'
}
}, status: :created
end
end
def render_failed_template_creation(result)
@@ -98,45 +88,6 @@ class Api::V1::Accounts::InboxCsatTemplatesController < Api::V1::Accounts::BaseC
}, status: :unprocessable_entity
end
def delete_existing_template_if_needed
template = @inbox.csat_config&.dig('template')
return true if template.blank?
template_name = template['name']
return true if template_name.blank?
template_status = @inbox.channel.provider_service.get_template_status(template_name)
return true unless template_status[:success]
deletion_result = @inbox.channel.provider_service.delete_csat_template(template_name)
if deletion_result[:success]
Rails.logger.info "Deleted existing CSAT template '#{template_name}' for inbox #{@inbox.id}"
true
else
Rails.logger.warn "Failed to delete existing CSAT template '#{template_name}' for inbox #{@inbox.id}: #{deletion_result[:response_body]}"
false
end
rescue StandardError => e
Rails.logger.error "Error during template deletion for inbox #{@inbox.id}: #{e.message}"
false
end
def render_template_status_response(status_result, template_name)
if status_result[:success]
render json: {
template_exists: true,
template_name: template_name,
status: status_result[:template][:status],
template_id: status_result[:template][:id]
}
else
render json: {
template_exists: false,
error: 'Template not found'
}
end
end
def parse_whatsapp_error(response_body)
return { user_message: nil, technical_details: nil } if response_body.blank?
@@ -176,7 +176,7 @@ class Api::V1::Accounts::InboxesController < Api::V1::Accounts::BaseController
:lock_to_single_conversation, :portal_id, :sender_name_type, :business_name,
{ csat_config: [:display_type, :message, :button_text, :language,
{ survey_rules: [:operator, { values: [] }],
template: [:name, :template_id, :created_at, :language] }] }]
template: [:name, :template_id, :friendly_name, :content_sid, :approval_sid, :created_at, :language, :status] }] }]
end
def permitted_params(channel_attributes = [])
@@ -38,6 +38,11 @@ class Api::V2::Accounts::ReportsController < Api::V1::Accounts::BaseController
generate_csv('teams_report', 'api/v2/accounts/reports/teams')
end
def conversations_summary
@report_data = generate_conversations_report
generate_csv('conversations_summary_report', 'api/v2/accounts/reports/conversations_summary')
end
def conversation_traffic
@report_data = generate_conversations_heatmap_report
timezone_offset = (params[:timezone_offset] || 0).to_f
@@ -1,6 +1,6 @@
class Api::V2::Accounts::SummaryReportsController < Api::V1::Accounts::BaseController
before_action :check_authorization
before_action :prepare_builder_params, only: [:agent, :team, :inbox, :label]
before_action :prepare_builder_params, only: [:agent, :team, :inbox, :label, :channel]
def agent
render_report_with(V2::Reports::AgentSummaryBuilder)
@@ -18,6 +18,12 @@ class Api::V2::Accounts::SummaryReportsController < Api::V1::Accounts::BaseContr
render_report_with(V2::Reports::LabelSummaryBuilder)
end
def channel
return render_could_not_create_error(I18n.t('errors.reports.date_range_too_long')) if date_range_too_long?
render_report_with(V2::Reports::ChannelSummaryBuilder)
end
private
def check_authorization
@@ -40,4 +46,12 @@ class Api::V2::Accounts::SummaryReportsController < Api::V1::Accounts::BaseContr
def permitted_params
params.permit(:since, :until, :business_hours)
end
def date_range_too_long?
return false if permitted_params[:since].blank? || permitted_params[:until].blank?
since_time = Time.zone.at(permitted_params[:since].to_i)
until_time = Time.zone.at(permitted_params[:until].to_i)
(until_time - since_time) > 6.months
end
end
@@ -46,6 +46,13 @@ module Api::V2::Accounts::ReportsHelper
end
end
def generate_conversations_report
builder = V2::Reports::Conversations::MetricBuilder.new(Current.account, build_params(type: :account))
summary = builder.summary
[generate_conversation_report_metrics(summary)]
end
private
def build_params(base_params)
@@ -71,4 +78,16 @@ module Api::V2::Accounts::ReportsHelper
report[:resolved_conversations_count]
]
end
def generate_conversation_report_metrics(summary)
[
summary[:conversations_count],
summary[:incoming_messages_count],
summary[:outgoing_messages_count],
Reports::TimeFormatPresenter.new(summary[:avg_first_response_time]).format,
Reports::TimeFormatPresenter.new(summary[:avg_resolution_time]).format,
summary[:resolutions_count],
Reports::TimeFormatPresenter.new(summary[:reply_time]).format
]
end
end
+6
View File
@@ -61,6 +61,12 @@ class ReportsAPI extends ApiClient {
});
}
getConversationsSummaryReports({ from: since, to: until, businessHours }) {
return axios.get(`${this.url}/conversations_summary`, {
params: { since, until, business_hours: businessHours },
});
}
getConversationTrafficCSV({ daysBefore = 6 } = {}) {
return axios.get(`${this.url}/conversation_traffic`, {
params: { timezone_offset: getTimeOffset(), days_before: daysBefore },
@@ -5,6 +5,7 @@ import WootEditor from 'dashboard/components/widgets/WootWriter/Editor.vue';
const props = defineProps({
modelValue: { type: String, default: '' },
editorKey: { type: String, default: '' },
label: { type: String, default: '' },
placeholder: { type: String, default: '' },
focusOnMount: { type: Boolean, default: false },
@@ -96,6 +97,7 @@ watch(
]"
>
<WootEditor
:editor-id="editorKey"
:model-value="modelValue"
:placeholder="placeholder"
:focus-on-mount="focusOnMount"
@@ -152,6 +154,13 @@ watch(
}
}
}
.ProseMirror-menubar {
width: fit-content !important;
position: relative !important;
top: unset !important;
@apply ltr:left-[-0.188rem] rtl:right-[-0.188rem] !important;
}
}
}
}
@@ -44,6 +44,12 @@ const emit = defineEmits([
const { t } = useI18n();
const attachmentId = ref(0);
const generateUid = () => {
attachmentId.value += 1;
return `attachment-${attachmentId.value}`;
};
const uploadAttachment = ref(null);
const isEmojiPickerOpen = ref(false);
@@ -176,7 +182,8 @@ const onPaste = e => {
.filter(file => file.size > 0)
.forEach(file => {
const { name, type, size } = file;
onFileUpload({ file, name, type, size });
// Add unique ID for clipboard-pasted files
onFileUpload({ file, name, type, size, id: generateUid() });
});
};
@@ -7,6 +7,7 @@ import {
appendSignature,
removeSignature,
getEffectiveChannelType,
stripUnsupportedMarkdown,
} from 'dashboard/helper/editorHelper';
import {
buildContactableInboxesList,
@@ -47,6 +48,8 @@ const emit = defineEmits([
'createConversation',
]);
const DEFAULT_FORMATTING = 'Context::Default';
const showContactsDropdown = ref(false);
const showInboxesDropdown = ref(false);
const showCcEmailsDropdown = ref(false);
@@ -198,10 +201,22 @@ const setSelectedContact = async ({ value, action, ...rest }) => {
showInboxesDropdown.value = true;
};
const handleInboxAction = ({ value, action, ...rest }) => {
const stripMessageFormatting = channelType => {
if (!state.message || !channelType) return;
state.message = stripUnsupportedMarkdown(state.message, channelType, false);
};
const handleInboxAction = ({ value, action, channelType, medium, ...rest }) => {
v$.value.$reset();
state.message = '';
emit('updateTargetInbox', { ...rest });
// Strip unsupported formatting when changing the target inbox
if (channelType) {
const newChannelType = getEffectiveChannelType(channelType, medium);
stripMessageFormatting(newChannelType);
}
emit('updateTargetInbox', { ...rest, channelType, medium });
showInboxesDropdown.value = false;
state.attachedFiles = [];
};
@@ -221,7 +236,9 @@ const removeSignatureFromMessage = () => {
const removeTargetInbox = value => {
v$.value.$reset();
removeSignatureFromMessage();
state.message = '';
stripMessageFormatting(DEFAULT_FORMATTING);
emit('updateTargetInbox', value);
state.attachedFiles = [];
};
@@ -324,67 +341,68 @@ const shouldShowMessageEditor = computed(() => {
<template>
<div
class="w-[42rem] divide-y divide-n-strong overflow-visible transition-all duration-300 ease-in-out top-full justify-between flex flex-col bg-n-alpha-3 border border-n-strong shadow-sm backdrop-blur-[100px] rounded-xl min-w-0"
class="w-[42rem] divide-y divide-n-strong overflow-visible transition-all duration-300 ease-in-out top-full flex flex-col bg-n-alpha-3 border border-n-strong shadow-sm backdrop-blur-[100px] rounded-xl min-w-0 max-h-[calc(100vh-8rem)]"
>
<ContactSelector
:contacts="contacts"
:selected-contact="selectedContact"
:show-contacts-dropdown="showContactsDropdown"
:is-loading="isLoading"
:is-creating-contact="isCreatingContact"
:contact-id="contactId"
:contactable-inboxes-list="contactableInboxesList"
:show-inboxes-dropdown="showInboxesDropdown"
:has-errors="validationStates.isContactInvalid"
@search-contacts="handleContactSearch"
@set-selected-contact="setSelectedContact"
@clear-selected-contact="clearSelectedContact"
@update-dropdown="handleDropdownUpdate"
/>
<InboxEmptyState v-if="showNoInboxAlert" />
<InboxSelector
v-else
:target-inbox="targetInbox"
:selected-contact="selectedContact"
:show-inboxes-dropdown="showInboxesDropdown"
:contactable-inboxes-list="contactableInboxesList"
:has-errors="validationStates.isInboxInvalid"
@update-inbox="removeTargetInbox"
@toggle-dropdown="showInboxesDropdown = $event"
@handle-inbox-action="handleInboxAction"
/>
<div class="flex-1 overflow-y-auto divide-y divide-n-strong">
<ContactSelector
:contacts="contacts"
:selected-contact="selectedContact"
:show-contacts-dropdown="showContactsDropdown"
:is-loading="isLoading"
:is-creating-contact="isCreatingContact"
:contact-id="contactId"
:contactable-inboxes-list="contactableInboxesList"
:show-inboxes-dropdown="showInboxesDropdown"
:has-errors="validationStates.isContactInvalid"
@search-contacts="handleContactSearch"
@set-selected-contact="setSelectedContact"
@clear-selected-contact="clearSelectedContact"
@update-dropdown="handleDropdownUpdate"
/>
<InboxEmptyState v-if="showNoInboxAlert" />
<InboxSelector
v-else
:target-inbox="targetInbox"
:selected-contact="selectedContact"
:show-inboxes-dropdown="showInboxesDropdown"
:contactable-inboxes-list="contactableInboxesList"
:has-errors="validationStates.isInboxInvalid"
@update-inbox="removeTargetInbox"
@toggle-dropdown="showInboxesDropdown = $event"
@handle-inbox-action="handleInboxAction"
/>
<EmailOptions
v-if="inboxTypes.isEmail"
v-model:cc-emails="state.ccEmails"
v-model:bcc-emails="state.bccEmails"
v-model:subject="state.subject"
:contacts="contacts"
:show-cc-emails-dropdown="showCcEmailsDropdown"
:show-bcc-emails-dropdown="showBccEmailsDropdown"
:is-loading="isLoading"
:has-errors="validationStates.isSubjectInvalid"
@search-cc-emails="searchCcEmails"
@search-bcc-emails="searchBccEmails"
@update-dropdown="handleDropdownUpdate"
/>
<EmailOptions
v-if="inboxTypes.isEmail"
v-model:cc-emails="state.ccEmails"
v-model:bcc-emails="state.bccEmails"
v-model:subject="state.subject"
:contacts="contacts"
:show-cc-emails-dropdown="showCcEmailsDropdown"
:show-bcc-emails-dropdown="showBccEmailsDropdown"
:is-loading="isLoading"
:has-errors="validationStates.isSubjectInvalid"
@search-cc-emails="searchCcEmails"
@search-bcc-emails="searchBccEmails"
@update-dropdown="handleDropdownUpdate"
/>
<MessageEditor
v-if="shouldShowMessageEditor"
v-model="state.message"
:message-signature="messageSignature"
:send-with-signature="sendWithSignature"
:has-errors="validationStates.isMessageInvalid"
:has-attachments="state.attachedFiles.length > 0"
:channel-type="inboxChannelType"
:medium="targetInbox?.medium || ''"
/>
<MessageEditor
v-if="shouldShowMessageEditor"
v-model="state.message"
:message-signature="messageSignature"
:send-with-signature="sendWithSignature"
:has-errors="validationStates.isMessageInvalid"
:channel-type="inboxChannelType"
:medium="targetInbox?.medium || ''"
/>
<AttachmentPreviews
v-if="state.attachedFiles.length > 0"
:attachments="state.attachedFiles"
@update:attachments="state.attachedFiles = $event"
/>
<AttachmentPreviews
v-if="state.attachedFiles.length > 0"
:attachments="state.attachedFiles"
@update:attachments="state.attachedFiles = $event"
/>
</div>
<ActionButtons
:attached-files="state.attachedFiles"
@@ -83,7 +83,7 @@ const targetInboxLabel = computed(() => {
<DropdownMenu
v-if="contactableInboxesList?.length > 0 && showInboxesDropdown"
:menu-items="contactableInboxesList"
class="ltr:left-0 rtl:right-0 z-[100] top-8 overflow-y-auto max-h-60 w-fit max-w-sm dark:!outline-n-slate-5"
class="ltr:left-0 rtl:right-0 z-[100] top-8 overflow-y-auto max-h-56 w-fit max-w-sm dark:!outline-n-slate-5"
@action="emit('handleInboxAction', $event)"
/>
</div>
@@ -6,7 +6,6 @@ import Editor from 'dashboard/components-next/Editor/Editor.vue';
const props = defineProps({
hasErrors: { type: Boolean, default: false },
hasAttachments: { type: Boolean, default: false },
sendWithSignature: { type: Boolean, default: false },
messageSignature: { type: String, default: '' },
channelType: { type: String, default: '' },
@@ -24,14 +23,14 @@ const modelValue = defineModel({
</script>
<template>
<div class="flex-1 h-full" :class="[!hasAttachments && 'min-h-[200px]']">
<div class="flex-1 h-full">
<Editor
:key="editorKey"
v-model="modelValue"
:editor-key="editorKey"
:placeholder="
t('COMPOSE_NEW_CONVERSATION.FORM.MESSAGE_EDITOR.PLACEHOLDER')
"
class="[&>div]:!border-transparent [&>div]:px-4 [&>div]:py-4 [&>div]:!bg-transparent h-full [&_.ProseMirror-woot-style]:!max-h-[200px]"
class="[&>div]:!border-transparent [&>div]:px-4 [&>div]:py-4 [&>div]:!bg-transparent h-full [&_.ProseMirror-woot-style]:!max-h-[12.5rem] [&_.ProseMirror-woot-style]:!min-h-[10rem] [&_.ProseMirror-menubar]:!pt-0 [&_.mention--box]:-top-[7.5rem] [&_.mention--box]:bottom-[unset]"
:class="
hasErrors
? '[&_.empty-node]:before:!text-n-ruby-9 [&_.empty-node]:dark:before:!text-n-ruby-9'
@@ -11,7 +11,6 @@ export const CONVERSATION_ATTRIBUTES = {
CAMPAIGN_ID: 'campaign_id',
LABELS: 'labels',
BROWSER_LANGUAGE: 'browser_language',
COUNTRY_CODE: 'country_code',
REFERER: 'referer',
CREATED_AT: 'created_at',
LAST_ACTIVITY_AT: 'last_activity_at',
@@ -7,7 +7,6 @@ import {
buildAttributesFilterTypes,
CONVERSATION_ATTRIBUTES,
} from './helper/filterHelper';
import countries from 'shared/constants/countries.js';
import languages from 'dashboard/components/widgets/conversation/advancedFilterItems/languages.js';
/**
@@ -218,17 +217,6 @@ export function useConversationFilterContext() {
filterOperators: equalityOperators.value,
attributeModel: 'additional',
},
{
attributeKey: CONVERSATION_ATTRIBUTES.COUNTRY_CODE,
value: CONVERSATION_ATTRIBUTES.COUNTRY_CODE,
attributeName: t('FILTER.ATTRIBUTES.COUNTRY_NAME'),
label: t('FILTER.ATTRIBUTES.COUNTRY_NAME'),
inputType: 'searchSelect',
options: countries,
dataType: 'text',
filterOperators: equalityOperators.value,
attributeModel: 'additional',
},
{
attributeKey: CONVERSATION_ATTRIBUTES.REFERER,
value: CONVERSATION_ATTRIBUTES.REFERER,
@@ -15,7 +15,6 @@ import Button from 'dashboard/components-next/button/Button.vue';
import SidebarGroup from './SidebarGroup.vue';
import SidebarProfileMenu from './SidebarProfileMenu.vue';
import SidebarChangelogCard from './SidebarChangelogCard.vue';
import YearInReviewBanner from '../year-in-review/YearInReviewBanner.vue';
import ChannelLeaf from './ChannelLeaf.vue';
import SidebarAccountSwitcher from './SidebarAccountSwitcher.vue';
import Logo from 'next/icon/Logo.vue';
@@ -661,7 +660,6 @@ const menuItems = computed(() => {
<div
class="pointer-events-none absolute inset-x-0 -top-[31px] h-8 bg-gradient-to-t from-n-solid-2 to-transparent"
/>
<YearInReviewBanner />
<SidebarChangelogCard
v-if="isOnChatwootCloud && !isACustomBrandedInstance"
/>
@@ -1,13 +1,11 @@
<script setup>
import { ref, computed } from 'vue';
import { computed } from 'vue';
import Auth from 'dashboard/api/auth';
import { useMapGetter } from 'dashboard/composables/store';
import { useI18n } from 'vue-i18n';
import { useUISettings } from 'dashboard/composables/useUISettings';
import Avatar from 'next/avatar/Avatar.vue';
import SidebarProfileMenuStatus from './SidebarProfileMenuStatus.vue';
import { FEATURE_FLAGS } from 'dashboard/featureFlags';
import YearInReviewModal from 'dashboard/components-next/year-in-review/YearInReviewModal.vue';
import {
DropdownContainer,
@@ -24,7 +22,6 @@ defineOptions({
});
const { t } = useI18n();
const { uiSettings } = useUISettings();
const currentUser = useMapGetter('getCurrentUser');
const currentUserAvailability = useMapGetter('getCurrentUserAvailability');
@@ -34,29 +31,6 @@ const isFeatureEnabledonAccount = useMapGetter(
'accounts/isFeatureEnabledonAccount'
);
const showYearInReviewModal = ref(false);
const bannerClosedKey = computed(() => {
return `yir_closed_${accountId.value}_2025`;
});
const isBannerClosed = computed(() => {
return uiSettings.value?.[bannerClosedKey.value] === true;
});
const showYearInReviewMenuItem = computed(() => {
return isBannerClosed.value;
});
const openYearInReviewModal = () => {
showYearInReviewModal.value = true;
emit('close');
};
const closeYearInReviewModal = () => {
showYearInReviewModal.value = false;
};
const showChatSupport = computed(() => {
return (
isFeatureEnabledonAccount.value(
@@ -68,13 +42,6 @@ const showChatSupport = computed(() => {
const menuItems = computed(() => {
return [
{
show: showYearInReviewMenuItem.value,
showOnCustomBrandedInstance: false,
label: t('SIDEBAR_ITEMS.YEAR_IN_REVIEW'),
icon: 'i-lucide-gift',
click: openYearInReviewModal,
},
{
show: showChatSupport.value,
showOnCustomBrandedInstance: false,
@@ -190,9 +157,4 @@ const allowedMenuItems = computed(() => {
</template>
</DropdownBody>
</DropdownContainer>
<YearInReviewModal
:show="showYearInReviewModal"
@close="closeYearInReviewModal"
/>
</template>
@@ -230,7 +230,7 @@ const handleBlur = e => emit('blur', e);
v-if="showDropdownMenu"
:menu-items="filteredMenuItems"
:is-searching="isLoading"
class="ltr:left-0 rtl:right-0 z-[100] top-8 overflow-y-auto max-h-60 w-[inherit] max-w-md dark:!outline-n-slate-5"
class="ltr:left-0 rtl:right-0 z-[100] top-8 overflow-y-auto max-h-56 w-[inherit] max-w-md dark:!outline-n-slate-5"
@action="handleDropdownAction"
/>
</div>
@@ -206,10 +206,14 @@ const emitDateRange = () => {
emit('dateRangeChanged', [selectedStartDate.value, selectedEndDate.value]);
}
};
const closeDatePicker = () => {
showDatePicker.value = false;
};
</script>
<template>
<div class="relative font-inter">
<div v-on-clickaway="closeDatePicker" class="relative font-inter">
<DatePickerButton
:selected-start-date="selectedStartDate"
:selected-end-date="selectedEndDate"
@@ -38,7 +38,7 @@ const toggleShowMore = () => {
<button
v-if="text.length > limit"
class="text-n-brand !p-0 !border-0 align-top"
@click="toggleShowMore"
@click.stop="toggleShowMore"
>
{{ buttonLabel }}
</button>
@@ -45,6 +45,7 @@ import {
removeSignature,
getEffectiveChannelType,
} from 'dashboard/helper/editorHelper';
import { isFileTypeAllowedForChannel } from 'shared/helpers/FileHelper';
import { LOCAL_STORAGE_KEYS } from 'dashboard/constants/localStorage';
import { LocalStorage } from 'shared/helpers/localStorage';
@@ -637,6 +638,25 @@ export default {
// Filter valid files (non-zero size)
Array.from(e.clipboardData.files)
.filter(file => file.size > 0)
.filter(file => {
const isAllowed = isFileTypeAllowedForChannel(file, {
channelType: this.channelType || this.inbox?.channel_type,
medium: this.inbox?.medium,
conversationType: this.conversationType,
isInstagramChannel: this.isAnInstagramChannel,
isOnPrivateNote: this.isOnPrivateNote,
});
if (!isAllowed) {
useAlert(
this.$t('CONVERSATION.FILE_TYPE_NOT_SUPPORTED', {
fileName: file.name,
})
);
}
return isAllowed;
})
.forEach(file => {
const { name, type, size } = file;
this.onFileUpload({ name, type, size, file });
@@ -78,14 +78,6 @@ const filterTypes = [
filterOperators: OPERATOR_TYPES_1,
attributeModel: 'additional',
},
{
attributeKey: 'country_code',
attributeI18nKey: 'COUNTRY_NAME',
inputType: 'search_select',
dataType: 'text',
filterOperators: OPERATOR_TYPES_1,
attributeModel: 'additional',
},
{
attributeKey: 'referer',
attributeI18nKey: 'REFERER_LINK',
@@ -171,10 +163,6 @@ export const filterAttributeGroups = [
key: 'browser_language',
i18nKey: 'BROWSER_LANGUAGE',
},
{
key: 'country_code',
i18nKey: 'COUNTRY_NAME',
},
{
key: 'referer',
i18nKey: 'REFERER_LINK',
@@ -38,9 +38,14 @@ export function extractTextFromMarkdown(markdown) {
*
* @param {string} markdown - markdown text to process
* @param {string} channelType - The channel type to check supported formatting
* @param {boolean} cleanWhitespace - Whether to clean up extra whitespace and blank lines (default: true for signatures)
* @returns {string} - The markdown with unsupported formatting removed
*/
export function stripUnsupportedSignatureMarkdown(markdown, channelType) {
export function stripUnsupportedMarkdown(
markdown,
channelType,
cleanWhitespace = true
) {
if (!markdown) return '';
const { marks = [], nodes = [] } = FORMATTING[channelType] || {};
@@ -55,6 +60,9 @@ export function stripUnsupportedSignatureMarkdown(markdown, channelType) {
);
}, markdown);
if (!cleanWhitespace) return result;
// Clean whitespace for signatures
return result
.split('\n')
.map(line => line.trim())
@@ -155,7 +163,7 @@ export function getEffectiveChannelType(channelType, medium) {
export function appendSignature(body, signature, channelType) {
// Strip only unsupported formatting based on channel capabilities
const preparedSignature = channelType
? stripUnsupportedSignatureMarkdown(signature, channelType)
? stripUnsupportedMarkdown(signature, channelType)
: signature;
const cleanedSignature = cleanSignature(preparedSignature);
// if signature is already present, return body
@@ -178,7 +186,7 @@ export function appendSignature(body, signature, channelType) {
export function removeSignature(body, signature, channelType) {
// Build unique list of signature variants to try
const channelStripped = channelType
? cleanSignature(stripUnsupportedSignatureMarkdown(signature, channelType))
? cleanSignature(stripUnsupportedMarkdown(signature, channelType))
: null;
const signaturesToTry = [
cleanSignature(signature),
@@ -1,3 +1,5 @@
import DOMPurify from 'dompurify';
// Quote detection strategies
const QUOTE_INDICATORS = [
'.gmail_quote_container',
@@ -29,7 +31,7 @@ export class EmailQuoteExtractor {
static extractQuotes(htmlContent) {
// Create a temporary DOM element to parse HTML
const tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlContent;
tempDiv.innerHTML = DOMPurify.sanitize(htmlContent);
// Remove elements matching class selectors
QUOTE_INDICATORS.forEach(selector => {
@@ -56,7 +58,7 @@ export class EmailQuoteExtractor {
*/
static hasQuotes(htmlContent) {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlContent;
tempDiv.innerHTML = DOMPurify.sanitize(htmlContent);
// Check for class-based quotes
// eslint-disable-next-line no-restricted-syntax
@@ -1,4 +1,5 @@
import { format, parseISO, isValid as isValidDate } from 'date-fns';
import DOMPurify from 'dompurify';
/**
* Extracts plain text from HTML content
@@ -13,7 +14,7 @@ export const extractPlainTextFromHtml = html => {
return html.replace(/<[^>]*>/g, ' ');
}
const tempDiv = document.createElement('div');
tempDiv.innerHTML = html;
tempDiv.innerHTML = DOMPurify.sanitize(html);
return tempDiv.textContent || tempDiv.innerText || '';
};
@@ -5,7 +5,7 @@ import {
replaceSignature,
cleanSignature,
extractTextFromMarkdown,
stripUnsupportedSignatureMarkdown,
stripUnsupportedMarkdown,
insertAtCursor,
findNodeToInsertImage,
setURLWithQueryAndSize,
@@ -145,25 +145,19 @@ describe('appendSignature', () => {
});
});
describe('stripUnsupportedSignatureMarkdown', () => {
describe('stripUnsupportedMarkdown', () => {
const richSignature =
'**Bold** _italic_ [link](http://example.com) ![](http://localhost:3000/image.png)';
it('keeps all formatting for Email channel (supports image, link, strong, em)', () => {
const result = stripUnsupportedSignatureMarkdown(
richSignature,
'Channel::Email'
);
const result = stripUnsupportedMarkdown(richSignature, 'Channel::Email');
expect(result).toContain('**Bold**');
expect(result).toContain('_italic_');
expect(result).toContain('[link](http://example.com)');
expect(result).toContain('![](http://localhost:3000/image.png)');
});
it('strips images but keeps bold/italic for Api channel', () => {
const result = stripUnsupportedSignatureMarkdown(
richSignature,
'Channel::Api'
);
const result = stripUnsupportedMarkdown(richSignature, 'Channel::Api');
expect(result).toContain('**Bold**');
expect(result).toContain('_italic_');
expect(result).toContain('link'); // link text kept
@@ -171,20 +165,14 @@ describe('stripUnsupportedSignatureMarkdown', () => {
expect(result).not.toContain('![]('); // image removed
});
it('strips images but keeps bold/italic/link for Telegram channel', () => {
const result = stripUnsupportedSignatureMarkdown(
richSignature,
'Channel::Telegram'
);
const result = stripUnsupportedMarkdown(richSignature, 'Channel::Telegram');
expect(result).toContain('**Bold**');
expect(result).toContain('_italic_');
expect(result).toContain('[link](http://example.com)');
expect(result).not.toContain('![](');
});
it('strips all formatting for SMS channel', () => {
const result = stripUnsupportedSignatureMarkdown(
richSignature,
'Channel::Sms'
);
const result = stripUnsupportedMarkdown(richSignature, 'Channel::Sms');
expect(result).toContain('Bold');
expect(result).toContain('italic');
expect(result).toContain('link');
@@ -194,8 +182,52 @@ describe('stripUnsupportedSignatureMarkdown', () => {
expect(result).not.toContain('![](');
});
it('returns empty string for empty input', () => {
expect(stripUnsupportedSignatureMarkdown('', 'Channel::Api')).toBe('');
expect(stripUnsupportedSignatureMarkdown(null, 'Channel::Api')).toBe('');
expect(stripUnsupportedMarkdown('', 'Channel::Api')).toBe('');
expect(stripUnsupportedMarkdown(null, 'Channel::Api')).toBe('');
});
describe('with cleanWhitespace parameter', () => {
const textWithWhitespace =
'**Bold** text\n\nWith multiple\n\nLine breaks\n\n And spaces ';
it('cleans whitespace when cleanWhitespace=true (default)', () => {
const result = stripUnsupportedMarkdown(
textWithWhitespace,
'Channel::Api',
true
);
expect(result).toBe(
'**Bold** text\nWith multiple\nLine breaks\nAnd spaces'
);
expect(result).not.toContain('\n\n');
expect(result).not.toContain(' ');
});
it('preserves whitespace when cleanWhitespace=false', () => {
const result = stripUnsupportedMarkdown(
textWithWhitespace,
'Channel::Api',
false
);
expect(result).toContain('\n\n');
expect(result).toContain(' And spaces ');
expect(result).toBe(
'**Bold** text\n\nWith multiple\n\nLine breaks\n\n And spaces '
);
});
it('strips formatting but preserves whitespace for messages', () => {
const messageWithFormatting = '**Bold**\n\n`code`\n\nNormal text';
const result = stripUnsupportedMarkdown(
messageWithFormatting,
'Channel::Sms',
false
);
expect(result).toBe('Bold\n\ncode\n\nNormal text');
expect(result).toContain('\n\n');
expect(result).not.toContain('**');
expect(result).not.toContain('`');
});
});
});
@@ -96,4 +96,58 @@ describe('EmailQuoteExtractor', () => {
it('detects quotes for trailing blockquotes even when signatures follow text', () => {
expect(EmailQuoteExtractor.hasQuotes(EMAIL_WITH_SIGNATURE)).toBe(true);
});
describe('HTML sanitization', () => {
it('removes onerror handlers from img tags in extractQuotes', () => {
const maliciousHtml = '<p>Hello</p><img src="x" onerror="alert(1)">';
const cleanedHtml = EmailQuoteExtractor.extractQuotes(maliciousHtml);
expect(cleanedHtml).not.toContain('onerror');
expect(cleanedHtml).toContain('<p>Hello</p>');
});
it('removes onerror handlers from img tags in hasQuotes', () => {
const maliciousHtml = '<p>Hello</p><img src="x" onerror="alert(1)">';
// Should not throw and should safely check for quotes
const result = EmailQuoteExtractor.hasQuotes(maliciousHtml);
expect(result).toBe(false);
});
it('removes script tags in extractQuotes', () => {
const maliciousHtml =
'<p>Content</p><script>alert("xss")</script><p>More</p>';
const cleanedHtml = EmailQuoteExtractor.extractQuotes(maliciousHtml);
expect(cleanedHtml).not.toContain('<script');
expect(cleanedHtml).not.toContain('alert');
expect(cleanedHtml).toContain('<p>Content</p>');
expect(cleanedHtml).toContain('<p>More</p>');
});
it('removes onclick handlers in extractQuotes', () => {
const maliciousHtml = '<p onclick="alert(1)">Click me</p>';
const cleanedHtml = EmailQuoteExtractor.extractQuotes(maliciousHtml);
expect(cleanedHtml).not.toContain('onclick');
expect(cleanedHtml).toContain('Click me');
});
it('removes javascript: URLs in extractQuotes', () => {
const maliciousHtml = '<a href="javascript:alert(1)">Link</a>';
const cleanedHtml = EmailQuoteExtractor.extractQuotes(maliciousHtml);
// eslint-disable-next-line no-script-url
expect(cleanedHtml).not.toContain('javascript:');
expect(cleanedHtml).toContain('Link');
});
it('removes encoded payloads with event handlers in extractQuotes', () => {
const maliciousHtml =
'<img src="x" id="PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==" onerror="eval(atob(this.id))">';
const cleanedHtml = EmailQuoteExtractor.extractQuotes(maliciousHtml);
expect(cleanedHtml).not.toContain('onerror');
expect(cleanedHtml).not.toContain('eval');
});
});
});
@@ -33,6 +33,26 @@ describe('quotedEmailHelper', () => {
expect(result).toContain('Line 1');
expect(result).toContain('Line 2');
});
it('sanitizes onerror handlers from img tags', () => {
const html = '<p>Hello</p><img src="x" onerror="alert(1)">';
const result = extractPlainTextFromHtml(html);
expect(result).toBe('Hello');
});
it('sanitizes script tags', () => {
const html = '<p>Safe</p><script>alert(1)</script><p>Content</p>';
const result = extractPlainTextFromHtml(html);
expect(result).toContain('Safe');
expect(result).toContain('Content');
expect(result).not.toContain('alert');
});
it('sanitizes onclick handlers', () => {
const html = '<p onclick="alert(1)">Click me</p>';
const result = extractPlainTextFromHtml(html);
expect(result).toBe('Click me');
});
});
describe('getEmailSenderName', () => {
@@ -247,6 +247,7 @@
"SUCCESS_DELETE_CONVERSATION": "Conversation deleted successfully",
"FAIL_DELETE_CONVERSATION": "Couldn't delete conversation! Try again",
"FILE_SIZE_LIMIT": "File exceeds the {MAXIMUM_SUPPORTED_FILE_UPLOAD_SIZE} MB attachment limit",
"FILE_TYPE_NOT_SUPPORTED": "This {fileName} file type is not supported in this conversation",
"MESSAGE_ERROR": "Unable to send this message, please try again later",
"SENT_BY": "Sent by:",
"BOT": "Bot",
@@ -3,7 +3,7 @@
"HEADER": "Conversations",
"LOADING_CHART": "Loading chart data...",
"NO_ENOUGH_DATA": "We've not received enough data points to generate report, Please try again later.",
"DOWNLOAD_AGENT_REPORTS": "Download agent reports",
"DOWNLOAD_CONVERSATION_REPORTS": "Download conversation reports",
"DATA_FETCHING_FAILED": "Failed to fetch data, please try again later.",
"SUMMARY_FETCHING_FAILED": "Failed to fetch summary, please try again later.",
"METRICS": {
@@ -402,22 +402,48 @@
},
"CSAT_REPORTS": {
"HEADER": "CSAT Reports",
"NO_RECORDS": "There are no CSAT survey responses available.",
"NO_RECORDS": "No responses yet",
"NO_RECORDS_DESCRIPTION": "CSAT survey responses will appear here once customers start providing feedback.",
"DOWNLOAD": "Download CSAT Reports",
"DOWNLOAD_FAILED": "Failed to download CSAT Reports",
"FILTERS": {
"ADD_FILTER": "Add filter",
"CLEAR_ALL": "Clear all",
"NO_FILTER": "No filters available",
"INPUT_PLACEHOLDER": {
"AGENTS": "Search agents",
"INBOXES": "Search inboxes",
"TEAMS": "Search teams",
"RATINGS": "Search ratings"
},
"AGENTS": {
"PLACEHOLDER": "Choose Agents"
"LABEL": "Agent"
},
"INBOXES": {
"LABEL": "Inbox"
},
"TEAMS": {
"LABEL": "Team"
},
"RATINGS": {
"LABEL": "Rating"
}
},
"TABLE": {
"HEADER": {
"CONTACT_NAME": "Contact",
"AGENT_NAME": "Assigned agent",
"AGENT_NAME": "Agent",
"RATING": "Rating",
"FEEDBACK_TEXT": "Feedback comment"
}
"FEEDBACK_TEXT": "Feedback comment",
"CONVERSATION": "Conversation",
"CUSTOMER": "Customer",
"RESPONSE": "Response",
"HANDLED_BY": "Handled by"
},
"UNKNOWN_CUSTOMER": "Unknown customer"
},
"NO_AGENT": "No assigned agent",
"NO_FEEDBACK": "No feedback provided",
"METRIC": {
"TOTAL_RESPONSES": {
"LABEL": "Total responses",
@@ -430,6 +456,25 @@
"RESPONSE_RATE": {
"LABEL": "Response rate",
"TOOLTIP": "Total number of responses / Total number of CSAT survey messages sent * 100"
},
"RATING_DISTRIBUTION": "Rating distribution"
},
"REVIEW_NOTES": {
"TITLE": "Review notes",
"PLACEHOLDER": "Add review notes about this rating...",
"SAVE": "Save",
"CANCEL": "Cancel",
"SAVING": "Saving...",
"SAVED": "Notes saved successfully",
"SAVE_ERROR": "Failed to save notes",
"UPDATED_BY": "Updated by {name} {time}",
"UPDATED_BY_LABEL": "Updated by",
"PAYWALL": {
"TITLE": "Upgrade to add review notes",
"AVAILABLE_ON": "The review notes feature is only available in the Business and Enterprise plans.",
"UPGRADE_PROMPT": "Add internal context to every CSAT response with review notes. Capture what really happened, spot patterns faster, and make better decisions from your feedback.",
"UPGRADE_NOW": "Upgrade now",
"CANCEL_ANYTIME": "You can change or cancel your plan anytime"
}
}
},
@@ -370,7 +370,7 @@ onUnmounted(() => {
/>
</div>
<section class="flex flex-col flex-grow w-full h-full overflow-hidden">
<div class="w-full max-w-5xl mx-auto z-[60]">
<div class="w-full max-w-5xl mx-auto z-30">
<div class="flex flex-col w-full px-4">
<SearchHeader
v-model:filters="filters"
@@ -28,10 +28,15 @@ const { t } = useI18n();
const store = useStore();
const labels = useMapGetter('labels/getLabels');
const { isAWhatsAppCloudChannel: isWhatsAppChannel } = useInbox(
const { isAWhatsAppChannel, isATwilioWhatsAppChannel } = useInbox(
props.inbox?.id
);
// Computed to check if it's any type of WhatsApp channel (Cloud or Twilio)
const isAnyWhatsAppChannel = computed(
() => isAWhatsAppChannel.value || isATwilioWhatsAppChannel.value
);
const isUpdating = ref(false);
const selectedLabelValues = ref([]);
const currentLabel = ref('');
@@ -116,7 +121,9 @@ const templateApprovalStatus = computed(() => {
// Handle existing template with status
if (templateStatus.value?.template_exists && templateStatus.value.status) {
return statusMap[templateStatus.value.status] || statusMap.PENDING;
// Convert status to uppercase for consistency with statusMap keys
const normalizedStatus = templateStatus.value.status.toUpperCase();
return statusMap[normalizedStatus] || statusMap.PENDING;
}
// Default case - no template exists
@@ -155,7 +162,7 @@ const initializeState = () => {
: [];
// Store original template values for change detection
if (isWhatsAppChannel.value) {
if (isAnyWhatsAppChannel.value) {
originalTemplateValues.value = {
message: state.message,
templateButtonText: state.templateButtonText,
@@ -165,7 +172,7 @@ const initializeState = () => {
};
const checkTemplateStatus = async () => {
if (!isWhatsAppChannel.value) return;
if (!isAnyWhatsAppChannel.value) return;
try {
templateLoading.value = true;
@@ -195,7 +202,7 @@ const checkTemplateStatus = async () => {
onMounted(() => {
initializeState();
if (!labels.value?.length) store.dispatch('labels/get');
if (isWhatsAppChannel.value) checkTemplateStatus();
if (isAnyWhatsAppChannel.value) checkTemplateStatus();
});
watch(() => props.inbox, initializeState, { immediate: true });
@@ -225,7 +232,7 @@ const removeLabel = label => {
// Check if template-related fields have changed
const hasTemplateChanges = () => {
if (!isWhatsAppChannel.value) return false;
if (!isAnyWhatsAppChannel.value) return false;
const original = originalTemplateValues.value;
return (
@@ -254,10 +261,28 @@ const shouldCreateTemplate = () => {
// Build template config for saving
const buildTemplateConfig = () => {
if (!hasExistingTemplate()) return null;
if (!hasExistingTemplate()) {
return null;
}
const { template_name, template_id, template, status } =
templateStatus.value || {};
if (isATwilioWhatsAppChannel.value) {
// Twilio WhatsApp format - get from existing template config
const existingTemplate = props.inbox?.csat_config?.template;
return existingTemplate
? {
friendly_name: existingTemplate.friendly_name,
content_sid: existingTemplate.content_sid,
language: existingTemplate.language || state.templateLanguage,
status: existingTemplate.status || status,
}
: null;
}
// WhatsApp Cloud format
return {
name: template_name,
template_id,
@@ -273,11 +298,11 @@ const updateInbox = async attributes => {
...attributes,
};
return store.dispatch('inboxes/updateInbox', payload);
await store.dispatch('inboxes/updateInbox', payload);
};
const createTemplate = async () => {
if (!isWhatsAppChannel.value) return null;
if (!isAnyWhatsAppChannel.value) return null;
const response = await store.dispatch('inboxes/createCSATTemplate', {
inboxId: props.inbox.id,
@@ -298,7 +323,7 @@ const performSave = async () => {
// For WhatsApp channels, create template first if needed
if (
isWhatsAppChannel.value &&
isAnyWhatsAppChannel.value &&
state.csatSurveyEnabled &&
shouldCreateTemplate()
) {
@@ -326,13 +351,25 @@ const performSave = async () => {
// Use new template data if created, otherwise preserve existing template information
if (newTemplateData) {
csatConfig.template = {
name: newTemplateData.name,
template_id: newTemplateData.template_id,
language: newTemplateData.language,
status: newTemplateData.status,
created_at: new Date().toISOString(),
};
if (isATwilioWhatsAppChannel.value) {
// Twilio WhatsApp template format
csatConfig.template = {
friendly_name: newTemplateData.friendly_name,
content_sid: newTemplateData.content_sid,
language: newTemplateData.language,
status: newTemplateData.status,
created_at: new Date().toISOString(),
};
} else {
// WhatsApp Cloud template format
csatConfig.template = {
name: newTemplateData.name,
template_id: newTemplateData.template_id,
language: newTemplateData.language,
status: newTemplateData.status,
created_at: new Date().toISOString(),
};
}
} else {
const templateConfig = buildTemplateConfig();
if (templateConfig) {
@@ -356,8 +393,9 @@ const performSave = async () => {
const saveSettings = async () => {
// Check if we need to show confirmation dialog for WhatsApp template changes
// This applies to both WhatsApp Cloud and Twilio WhatsApp channels
if (
isWhatsAppChannel.value &&
isAnyWhatsAppChannel.value &&
state.csatSurveyEnabled &&
hasExistingTemplate() &&
hasTemplateChanges()
@@ -390,7 +428,7 @@ const handleConfirmTemplateUpdate = async () => {
<div class="grid gap-5">
<!-- Show display type only for non-WhatsApp channels -->
<WithLabel
v-if="!isWhatsAppChannel"
v-if="!isAnyWhatsAppChannel"
:label="$t('INBOX_MGMT.CSAT.DISPLAY_TYPE.LABEL')"
name="display_type"
>
@@ -400,7 +438,7 @@ const handleConfirmTemplateUpdate = async () => {
/>
</WithLabel>
<template v-if="isWhatsAppChannel">
<template v-if="isAnyWhatsAppChannel">
<div
class="flex flex-col gap-4 justify-between w-full lg:flex-row lg:gap-6"
>
@@ -536,7 +574,7 @@ const handleConfirmTemplateUpdate = async () => {
</WithLabel>
<p class="text-sm italic text-n-slate-11">
{{
isWhatsAppChannel
isAnyWhatsAppChannel
? $t('INBOX_MGMT.CSAT.WHATSAPP_NOTE')
: $t('INBOX_MGMT.CSAT.NOTE')
}}
@@ -3,7 +3,7 @@ import { mapGetters } from 'vuex';
import { useAlert, useTrack } from 'dashboard/composables';
import CsatMetrics from './components/CsatMetrics.vue';
import CsatTable from './components/CsatTable.vue';
import ReportFilterSelector from './components/FilterSelector.vue';
import CsatFilters from './components/Csat/CsatFilters.vue';
import { generateFileName } from '../../../../helper/downloadHelper';
import { REPORTS_EVENTS } from '../../../../helper/AnalyticsHelper/events';
import { FEATURE_FLAGS } from '../../../../featureFlags';
@@ -15,7 +15,7 @@ export default {
components: {
CsatMetrics,
CsatTable,
ReportFilterSelector,
CsatFilters,
ReportHeader,
V4Button,
},
@@ -90,7 +90,7 @@ export default {
selectedTeam,
selectedRating,
}) {
// do not track filter change on inital load
// do not track filter change on initial load
if (this.from !== 0 && this.to !== 0) {
useTrack(REPORTS_EVENTS.FILTER_REPORT, {
filterType: 'date',
@@ -121,16 +121,11 @@ export default {
/>
</ReportHeader>
<div class="flex flex-col gap-4">
<ReportFilterSelector
show-agents-filter
show-inbox-filter
show-rating-filter
<div class="flex flex-col gap-6">
<CsatFilters
:show-team-filter="isTeamsEnabled"
:show-business-hours-switch="false"
@filter-change="onFilterChange"
/>
<CsatMetrics :filters="requestPayload" />
<CsatTable :page-index="pageIndex" @page-change="onPageNumberChange" />
</div>
@@ -76,14 +76,14 @@ export default {
businessHours,
};
},
downloadAgentReports() {
downloadConversationReports() {
const { from, to } = this;
const fileName = generateFileName({
type: 'agent',
type: 'conversation',
to,
businessHours: this.businessHours,
});
this.$store.dispatch('downloadAgentReports', {
this.$store.dispatch('downloadConversationsSummaryReports', {
from,
to,
fileName,
@@ -109,10 +109,10 @@ export default {
<template>
<ReportHeader :header-title="$t('REPORT.HEADER')">
<V4Button
:label="$t('REPORT.DOWNLOAD_AGENT_REPORTS')"
:label="$t('REPORT.DOWNLOAD_CONVERSATION_REPORTS')"
icon="i-ph-download-simple"
size="sm"
@click="downloadAgentReports"
@click="downloadConversationReports"
/>
</ReportHeader>
<div class="flex flex-col gap-3">
@@ -1,26 +0,0 @@
<script setup>
import { computed } from 'vue';
const { row } = defineProps({
row: {
type: Object,
required: true,
},
});
const routerParams = computed(() => ({
name: 'inbox_conversation',
params: { conversation_id: row.original.conversationId },
}));
</script>
<template>
<div class="text-right">
<router-link :to="routerParams" class="hover:underline">
{{ `#${row.original.conversationId}` }}
</router-link>
<div v-tooltip="row.original.createdAt" class="text-n-slate-11 text-sm">
{{ row.original.createdAgo }}
</div>
</div>
</template>
@@ -0,0 +1,36 @@
import { CSAT_RATINGS } from 'shared/constants/messages';
export const buildFilterList = (items, type) =>
items.map(item => ({
id: item.id,
name: type === 'ratings' ? item.emoji : item.name,
type,
}));
export const buildRatingsList = t =>
CSAT_RATINGS.map(rating => ({
id: rating.value,
name: `${t(rating.translationKey)}`,
type: 'ratings',
}));
export const getActiveFilter = (filters, type, key) =>
filters.find(item => item.id.toString() === key.toString());
export const getFilterType = (input, direction) => {
const filterMap = {
keyToType: {
user_ids: 'agents',
inbox_id: 'inboxes',
team_id: 'teams',
rating: 'ratings',
},
typeToKey: {
agents: 'user_ids',
inboxes: 'inbox_id',
teams: 'team_id',
ratings: 'rating',
},
};
return filterMap[direction][input];
};
@@ -0,0 +1,267 @@
<script setup>
import { ref, computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useStore } from 'vuex';
import { getUnixStartOfDay, getUnixEndOfDay } from 'helpers/DateHelper';
import {
buildFilterList,
buildRatingsList,
getActiveFilter,
getFilterType,
} from './CsatFilterHelpers';
import FilterButton from 'dashboard/components/ui/Dropdown/DropdownButton.vue';
import ActiveFilterChip from '../Filters/v3/ActiveFilterChip.vue';
import AddFilterChip from '../Filters/v3/AddFilterChip.vue';
import WootDatePicker from 'dashboard/components/ui/DatePicker/DatePicker.vue';
const props = defineProps({
showTeamFilter: {
type: Boolean,
default: false,
},
});
const emit = defineEmits(['filterChange']);
const { t } = useI18n();
const store = useStore();
const showDropdownMenu = ref(false);
const showSubDropdownMenu = ref(false);
const activeFilterType = ref('');
const customDateRange = ref([new Date(), new Date()]);
const appliedFilters = ref({
user_ids: null,
inbox_id: null,
team_id: null,
rating: null,
});
const agents = computed(() => store.getters['agents/getAgents']);
const inboxes = computed(() => store.getters['inboxes/getInboxes']);
const teams = computed(() => store.getters['teams/getTeams']);
const ratings = computed(() => buildRatingsList(t));
const from = computed(() => getUnixStartOfDay(customDateRange.value[0]));
const to = computed(() => getUnixEndOfDay(customDateRange.value[1]));
const getFilterSource = type => {
const sources = {
agents: agents.value,
inboxes: inboxes.value,
teams: teams.value,
ratings: ratings.value,
};
return sources[type] || [];
};
const getFilterOptions = type => {
if (type === 'ratings') {
return ratings.value;
}
return buildFilterList(getFilterSource(type), type);
};
const filterListMenuItems = computed(() => {
const filterTypes = [
{
id: '1',
name: t('CSAT_REPORTS.FILTERS.AGENTS.LABEL'),
type: 'agents',
},
{
id: '2',
name: t('CSAT_REPORTS.FILTERS.INBOXES.LABEL'),
type: 'inboxes',
},
{
id: '3',
name: t('CSAT_REPORTS.FILTERS.RATINGS.LABEL'),
type: 'ratings',
},
];
if (props.showTeamFilter) {
filterTypes.splice(2, 0, {
id: '4',
name: t('CSAT_REPORTS.FILTERS.TEAMS.LABEL'),
type: 'teams',
});
}
const activeFilterKeys = Object.keys(appliedFilters.value).filter(
key => appliedFilters.value[key]
);
const activeFilterTypes = activeFilterKeys.map(key =>
getFilterType(key, 'keyToType')
);
return filterTypes
.filter(({ type }) => !activeFilterTypes.includes(type))
.map(({ id, name, type }) => ({
id,
name,
type,
options: getFilterOptions(type),
}));
});
const activeFilters = computed(() => {
const activeKeys = Object.keys(appliedFilters.value).filter(
key => appliedFilters.value[key]
);
return activeKeys.map(key => {
const filterType = getFilterType(key, 'keyToType');
const items = getFilterSource(filterType);
const item = getActiveFilter(items, filterType, appliedFilters.value[key]);
return {
id: item?.id,
name: item?.name || '',
type: filterType,
options: getFilterOptions(filterType),
};
});
});
const hasActiveFilters = computed(() =>
Object.values(appliedFilters.value).some(value => value !== null)
);
const isAllFilterSelected = computed(() => !filterListMenuItems.value.length);
const emitChange = () => {
emit('filterChange', {
from: from.value,
to: to.value,
selectedAgents: appliedFilters.value.user_ids
? [{ id: appliedFilters.value.user_ids }]
: [],
selectedInbox: appliedFilters.value.inbox_id
? { id: appliedFilters.value.inbox_id }
: null,
selectedTeam: appliedFilters.value.team_id
? { id: appliedFilters.value.team_id }
: null,
selectedRating: appliedFilters.value.rating
? { value: appliedFilters.value.rating }
: null,
});
};
const closeDropdown = () => {
showDropdownMenu.value = false;
};
const closeActiveFilterDropdown = () => {
activeFilterType.value = '';
showSubDropdownMenu.value = false;
};
const resetDropdown = () => {
closeDropdown();
closeActiveFilterDropdown();
};
const addFilter = item => {
const { type, id } = item;
const filterKey = getFilterType(type, 'typeToKey');
appliedFilters.value[filterKey] = id;
emitChange();
resetDropdown();
};
const removeFilter = type => {
const filterKey = getFilterType(type, 'typeToKey');
appliedFilters.value[filterKey] = null;
emitChange();
};
const clearAllFilters = () => {
appliedFilters.value = {
user_ids: null,
inbox_id: null,
team_id: null,
rating: null,
};
emitChange();
resetDropdown();
};
const showDropdown = () => {
showSubDropdownMenu.value = false;
showDropdownMenu.value = !showDropdownMenu.value;
};
const openActiveFilterDropdown = filterType => {
closeDropdown();
activeFilterType.value = filterType;
showSubDropdownMenu.value = !showSubDropdownMenu.value;
};
const onDateRangeChange = value => {
customDateRange.value = value;
emitChange();
};
onMounted(() => {
emitChange();
});
</script>
<template>
<div class="flex flex-col flex-wrap w-full gap-3 md:flex-row">
<WootDatePicker @date-range-changed="onDateRangeChange" />
<div
class="flex flex-col flex-wrap items-start gap-2 md:items-center md:flex-nowrap md:flex-row"
>
<div v-if="hasActiveFilters" class="flex flex-wrap gap-2 md:flex-nowrap">
<ActiveFilterChip
v-for="filter in activeFilters"
v-bind="filter"
:key="filter.type"
:placeholder="
$t(
`CSAT_REPORTS.FILTERS.INPUT_PLACEHOLDER.${filter.type.toUpperCase()}`
)
"
:active-filter-type="activeFilterType"
:show-menu="showSubDropdownMenu"
enable-search
@toggle-dropdown="openActiveFilterDropdown"
@close-dropdown="closeActiveFilterDropdown"
@add-filter="addFilter"
@remove-filter="removeFilter"
/>
</div>
<div
v-if="hasActiveFilters && !isAllFilterSelected"
class="w-full h-px border md:w-px md:h-5 border-n-weak"
/>
<div class="flex items-center gap-2">
<AddFilterChip
v-if="!isAllFilterSelected"
placeholder-i18n-key="CSAT_REPORTS.FILTERS.INPUT_PLACEHOLDER"
:name="$t('CSAT_REPORTS.FILTERS.ADD_FILTER')"
:menu-option="filterListMenuItems"
:show-menu="showDropdownMenu"
:empty-state-message="$t('CSAT_REPORTS.FILTERS.NO_FILTER')"
@toggle-dropdown="showDropdown"
@close-dropdown="closeDropdown"
@add-filter="addFilter"
/>
<div v-if="hasActiveFilters" class="w-px h-5 border border-n-weak" />
<FilterButton
v-if="hasActiveFilters"
:button-text="$t('CSAT_REPORTS.FILTERS.CLEAR_ALL')"
@click="clearAllFilters"
/>
</div>
</div>
</div>
</template>
@@ -0,0 +1,52 @@
<script setup>
import Avatar from 'dashboard/components-next/avatar/Avatar.vue';
defineProps({
contact: {
type: Object,
default: null,
},
conversationId: {
type: Number,
required: true,
},
createdAgo: {
type: String,
default: '',
},
createdAt: {
type: String,
default: '',
},
});
</script>
<template>
<div class="flex items-center gap-2">
<Avatar
:src="contact?.thumbnail || ''"
:name="contact?.name || ''"
:size="32"
rounded-full
/>
<div class="flex flex-col gap-0.5">
<span class="text-sm text-n-slate-12 font-medium capitalize">
{{ contact?.name || '—' }}
</span>
<div
class="flex items-center gap-1 text-xs text-n-slate-10 whitespace-nowrap"
>
<a
:href="`/app/accounts/${$route.params.accountId}/conversations/${conversationId}`"
class="flex items-center text-xs gap-0.5 hover:text-n-brand hover:underline"
target="_blank"
rel="noopener noreferrer nofollow"
>
<span>#{{ conversationId }}</span>
</a>
<span>·</span>
<span :title="createdAt">{{ createdAgo }}</span>
</div>
</div>
</div>
</template>
@@ -0,0 +1,32 @@
<script setup>
defineProps({
title: {
type: String,
required: true,
},
description: {
type: String,
default: '',
},
icon: {
type: String,
default: 'i-lucide-message-square-off',
},
});
</script>
<template>
<div class="flex flex-col items-center justify-center py-16 px-6 text-center">
<div
class="size-16 rounded-full bg-n-alpha-2 flex items-center justify-center mb-4"
>
<i :class="icon" class="size-8 text-n-slate-10" />
</div>
<h3 class="text-base font-medium text-n-slate-12 mb-1">
{{ title }}
</h3>
<p v-if="description" class="text-sm text-n-slate-10 max-w-sm">
{{ description }}
</p>
</div>
</template>
@@ -0,0 +1,162 @@
<script setup>
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useStore } from 'vuex';
import { useAlert } from 'dashboard/composables';
import { useAccount } from 'dashboard/composables/useAccount';
import { useMessageFormatter } from 'shared/composables/useMessageFormatter';
import Button from 'dashboard/components-next/button/Button.vue';
import Editor from 'dashboard/components-next/Editor/Editor.vue';
import CsatReviewNotesPaywall from './CsatReviewNotesPaywall.vue';
import { dynamicTime } from 'shared/helpers/timeHelper';
const props = defineProps({
response: {
type: Object,
required: true,
},
});
const { t } = useI18n();
const store = useStore();
const { isCloudFeatureEnabled, isOnChatwootCloud } = useAccount();
const { formatMessage } = useMessageFormatter();
const isFeatureEnabled = computed(() =>
isCloudFeatureEnabled('csat_review_notes')
);
const showPaywall = computed(
() => !isFeatureEnabled.value && isOnChatwootCloud.value
);
const reviewNotes = ref(props.response.csat_review_notes || '');
const isEditing = ref(!props.response.csat_review_notes);
const isSaving = ref(false);
const hasExistingReviewNotes = computed(
() => !!props.response.csat_review_notes
);
const hasChanges = computed(
() => reviewNotes.value !== (props.response.csat_review_notes || '')
);
const startEditing = () => {
isEditing.value = true;
};
const cancelEditing = () => {
reviewNotes.value = props.response.csat_review_notes || '';
if (hasExistingReviewNotes.value) {
isEditing.value = false;
}
};
const saveReviewNotes = async () => {
isSaving.value = true;
try {
await store.dispatch('csat/update', {
id: props.response.id,
reviewNotes: reviewNotes.value,
});
useAlert(t('CSAT_REPORTS.REVIEW_NOTES.SAVED'));
isEditing.value = false;
} catch {
useAlert(t('CSAT_REPORTS.REVIEW_NOTES.SAVE_ERROR'));
} finally {
isSaving.value = false;
}
};
</script>
<template>
<div class="py-4 px-5 border-t border-n-container bg-n-background">
<CsatReviewNotesPaywall v-if="showPaywall" />
<div v-else-if="isFeatureEnabled" class="flex flex-col gap-3">
<div class="flex items-start gap-4">
<div
class="flex items-center gap-1.5 text-n-slate-11 shrink-0 w-36 pt-3"
>
<i class="i-lucide-notebook-pen size-4" />
<span class="text-sm font-medium">
{{ $t('CSAT_REPORTS.REVIEW_NOTES.TITLE') }}
</span>
</div>
<div class="flex-1 max-w-2xl">
<div
v-if="hasExistingReviewNotes && !isEditing"
class="group flex items-start gap-2 py-2 px-3 rounded-lg hover:bg-n-slate-2 dark:hover:bg-n-solid-3 cursor-pointer transition-colors"
@click.stop="startEditing"
>
<p
v-dompurify-html="formatMessage(response.csat_review_notes || '')"
class="flex-1 text-sm text-n-slate-12 prose-sm prose-p:text-sm prose-p:leading-relaxed prose-p:mb-1 prose-p:mt-0"
/>
<i
class="i-lucide-pencil size-4 text-n-slate-10 opacity-0 group-hover:opacity-100 transition-opacity shrink-0 mt-0.5"
/>
</div>
<div
v-else
class="flex flex-col gap-3 [&_.ProseMirror]:min-h-32 [&_.ProseMirror]:max-h-64 [&_.ProseMirror-menubar]:!mt-0"
@click.stop
>
<Editor
v-model="reviewNotes"
:placeholder="$t('CSAT_REPORTS.REVIEW_NOTES.PLACEHOLDER')"
:show-character-count="false"
:enable-canned-responses="false"
focus-on-mount
>
<template #actions>
<div class="flex items-center gap-2 py-2">
<Button
v-if="hasExistingReviewNotes"
variant="ghost"
size="xs"
:label="$t('CSAT_REPORTS.REVIEW_NOTES.CANCEL')"
@click.stop="cancelEditing"
/>
<Button
:label="$t('CSAT_REPORTS.REVIEW_NOTES.SAVE')"
:disabled="!hasChanges || isSaving"
:loading="isSaving"
size="xs"
@click.stop="saveReviewNotes"
/>
</div>
</template>
</Editor>
</div>
</div>
</div>
<div
v-if="
hasExistingReviewNotes &&
!isEditing &&
response.review_notes_updated_by
"
class="flex items-center gap-4"
>
<div class="flex items-center gap-1.5 text-n-slate-11 shrink-0 w-36">
<i class="i-lucide-user-pen size-4" />
<span class="text-sm font-medium">
{{ $t('CSAT_REPORTS.REVIEW_NOTES.UPDATED_BY_LABEL') }}
</span>
</div>
<div class="flex items-center gap-1 flex-1 max-w-2xl px-3">
<span class="text-sm text-n-slate-12">
{{ response.review_notes_updated_by.name }}
</span>
<span class="text-n-slate-10">·</span>
<span class="text-sm text-n-slate-10">
{{ dynamicTime(response.review_notes_updated_at) }}
</span>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,53 @@
<script setup>
import CsatMetricCard from './CsatMetricCard.vue';
</script>
<!-- eslint-disable vue/no-bare-strings-in-template -->
<!-- eslint-disable vue/no-undef-components -->
<template>
<Story
title="Components/Reports/CsatMetricCard"
:layout="{ type: 'grid', width: '400px' }"
>
<Variant title="Default">
<div class="p-4 bg-n-background">
<CsatMetricCard
label="Total Responses"
tooltip="Total number of responses received"
value="1,234"
/>
</div>
</Variant>
<Variant title="Percentage Value">
<div class="p-4 bg-n-background">
<CsatMetricCard
label="Satisfaction Score"
tooltip="Percentage of positive responses"
value="85%"
/>
</div>
</Variant>
<Variant title="Loading State">
<div class="p-4 bg-n-background">
<CsatMetricCard
label="Response Rate"
tooltip="Percentage of conversations with responses"
value="0"
is-loading
/>
</div>
</Variant>
<Variant title="Zero Value">
<div class="p-4 bg-n-background">
<CsatMetricCard
label="Total Responses"
tooltip="Total number of responses received"
value="0"
/>
</div>
</Variant>
</Story>
</template>
@@ -0,0 +1,41 @@
<script setup>
defineProps({
label: {
type: String,
required: true,
},
tooltip: {
type: String,
required: true,
},
value: {
type: [String, Number],
required: true,
},
isLoading: {
type: Boolean,
default: false,
},
});
</script>
<template>
<div class="flex flex-col gap-2 items-start justify-center min-w-[10rem]">
<span
class="inline-flex items-center gap-1 text-sm font-medium text-n-slate-11"
>
{{ label }}
<span
v-tooltip.right="tooltip"
class="i-lucide-info flex flex-shrink-0 text-n-slate-10 size-3.5"
/>
</span>
<div
v-if="isLoading"
class="w-16 h-8 rounded-md bg-n-slate-3 animate-pulse"
/>
<span v-else class="text-2xl font-medium text-n-slate-12">
{{ value }}
</span>
</div>
</template>
@@ -1,135 +1,63 @@
<script>
import { mapGetters } from 'vuex';
import CsatMetricCard from './ReportMetricCard.vue';
import { CSAT_RATINGS } from 'shared/constants/messages';
import BarChart from 'shared/components/charts/BarChart.vue';
<script setup>
import { computed } from 'vue';
import { useMapGetter } from 'dashboard/composables/store';
import CsatMetricCard from './CsatMetricCard.vue';
import CsatRatingDistribution from './CsatRatingDistribution.vue';
export default {
components: { BarChart, CsatMetricCard },
props: {
filters: {
type: Object,
required: true,
},
},
data() {
return {
csatRatings: CSAT_RATINGS,
};
},
computed: {
...mapGetters({
metrics: 'csat/getMetrics',
ratingPercentage: 'csat/getRatingPercentage',
satisfactionScore: 'csat/getSatisfactionScore',
responseRate: 'csat/getResponseRate',
}),
ratingFilterEnabled() {
return Boolean(this.filters.rating);
},
chartData() {
const sortedRatings = [...CSAT_RATINGS].sort((a, b) => b.value - a.value);
return {
labels: ['Rating'],
datasets: sortedRatings.map(rating => ({
label: rating.emoji,
data: [this.ratingPercentage[rating.value]],
backgroundColor: rating.color,
})),
};
},
responseCount() {
return this.metrics.totalResponseCount
? this.metrics.totalResponseCount.toLocaleString()
: '--';
},
chartOptions() {
return {
indexAxis: 'y',
responsive: true,
plugins: {
legend: {
display: false,
},
title: {
display: false,
},
tooltip: {
enabled: false,
},
},
scales: {
x: {
display: false,
stacked: true,
},
y: {
display: false,
stacked: true,
},
},
};
},
},
methods: {
formatToPercent(value) {
return value ? `${value}%` : '--';
},
ratingToEmoji(value) {
return CSAT_RATINGS.find(rating => rating.value === Number(value)).emoji;
},
},
};
const metrics = useMapGetter('csat/getMetrics');
const ratingPercentage = useMapGetter('csat/getRatingPercentage');
const ratingCount = useMapGetter('csat/getRatingCount');
const satisfactionScore = useMapGetter('csat/getSatisfactionScore');
const responseRate = useMapGetter('csat/getResponseRate');
const uiFlags = useMapGetter('csat/getUIFlags');
const isLoading = computed(() => uiFlags.value.isFetchingMetrics);
const responseCount = computed(() =>
metrics.value.totalResponseCount
? metrics.value.totalResponseCount.toLocaleString()
: '0'
);
const formatPercent = value => (value ? `${value}%` : '0%');
</script>
<!-- eslint-disable vue/no-unused-refs -->
<!-- Added ref for writing specs -->
<template>
<div
class="flex-col lg:flex-row flex flex-wrap mx-0 shadow outline-1 outline outline-n-container rounded-xl bg-n-solid-2 px-6 py-8 gap-4"
>
<CsatMetricCard
:label="$t('CSAT_REPORTS.METRIC.TOTAL_RESPONSES.LABEL')"
:info-text="$t('CSAT_REPORTS.METRIC.TOTAL_RESPONSES.TOOLTIP')"
:value="responseCount"
class="xs:w-full sm:max-w-[50%] lg:w-1/6 lg:max-w-[16%]"
/>
<CsatMetricCard
:disabled="ratingFilterEnabled"
:label="$t('CSAT_REPORTS.METRIC.SATISFACTION_SCORE.LABEL')"
:info-text="$t('CSAT_REPORTS.METRIC.SATISFACTION_SCORE.TOOLTIP')"
:value="ratingFilterEnabled ? '--' : formatToPercent(satisfactionScore)"
class="xs:w-full sm:max-w-[50%] lg:w-1/6 lg:max-w-[16%]"
/>
<CsatMetricCard
:label="$t('CSAT_REPORTS.METRIC.RESPONSE_RATE.LABEL')"
:info-text="$t('CSAT_REPORTS.METRIC.RESPONSE_RATE.TOOLTIP')"
:value="formatToPercent(responseRate)"
class="xs:w-full sm:max-w-[50%] lg:w-1/6 lg:max-w-[16%]"
/>
<div class="flex flex-col gap-4">
<div
v-if="metrics.totalResponseCount && !ratingFilterEnabled"
ref="csatBarChart"
class="w-full md:w-1/2 md:max-w-[50%] flex-1 rtl:[direction:initial]"
class="flex sm:flex-row flex-col w-full gap-4 sm:gap-14 shadow outline-1 outline outline-n-container rounded-xl bg-n-solid-2 px-6 py-5"
>
<h3
class="flex items-center m-0 text-xs font-medium md:text-sm text-n-slate-12"
>
<div class="flex flex-row-reverse justify-end">
<div
v-for="(rating, key, index) in ratingPercentage"
:key="rating + key + index"
class="ltr:pr-4 rtl:pl-4"
>
<span class="my-0 mx-0.5">{{ ratingToEmoji(key) }}</span>
<span>{{ formatToPercent(rating) }}</span>
</div>
</div>
</h3>
<div class="mt-2 h-6">
<BarChart :collection="chartData" :chart-options="chartOptions" />
</div>
<CsatMetricCard
:label="$t('CSAT_REPORTS.METRIC.TOTAL_RESPONSES.LABEL')"
:tooltip="$t('CSAT_REPORTS.METRIC.TOTAL_RESPONSES.TOOLTIP')"
:value="responseCount"
:is-loading="isLoading"
/>
<div class="w-full sm:w-px bg-n-strong" />
<CsatMetricCard
:label="$t('CSAT_REPORTS.METRIC.SATISFACTION_SCORE.LABEL')"
:tooltip="$t('CSAT_REPORTS.METRIC.SATISFACTION_SCORE.TOOLTIP')"
:value="formatPercent(satisfactionScore)"
:is-loading="isLoading"
/>
<div class="w-full sm:w-px bg-n-strong" />
<CsatMetricCard
:label="$t('CSAT_REPORTS.METRIC.RESPONSE_RATE.LABEL')"
:tooltip="$t('CSAT_REPORTS.METRIC.RESPONSE_RATE.TOOLTIP')"
:value="formatPercent(responseRate)"
:is-loading="isLoading"
/>
</div>
<CsatRatingDistribution
:rating-percentage="ratingPercentage"
:rating-count="ratingCount"
:total-response-count="metrics.totalResponseCount"
:is-loading="isLoading"
/>
</div>
</template>
@@ -0,0 +1,75 @@
<script setup>
import CsatRatingDistribution from './CsatRatingDistribution.vue';
const sampleRatingPercentage = {
1: 5,
2: 10,
3: 15,
4: 25,
5: 45,
};
const sampleRatingCount = {
1: 50,
2: 100,
3: 150,
4: 250,
5: 450,
};
const emptyRatingPercentage = {
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
};
const emptyRatingCount = {
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
};
</script>
<!-- eslint-disable vue/no-bare-strings-in-template -->
<!-- eslint-disable vue/no-undef-components -->
<template>
<Story
title="Components/Reports/CsatRatingDistribution"
:layout="{ type: 'grid', width: '800px' }"
>
<Variant title="With Data">
<div class="p-4 bg-n-background">
<CsatRatingDistribution
:rating-percentage="sampleRatingPercentage"
:rating-count="sampleRatingCount"
:total-response-count="1000"
/>
</div>
</Variant>
<Variant title="Empty State">
<div class="p-4 bg-n-background">
<CsatRatingDistribution
:rating-percentage="emptyRatingPercentage"
:rating-count="emptyRatingCount"
:total-response-count="0"
/>
</div>
</Variant>
<Variant title="Loading State">
<div class="p-4 bg-n-background">
<CsatRatingDistribution
:rating-percentage="emptyRatingPercentage"
:rating-count="emptyRatingCount"
:total-response-count="0"
is-loading
/>
</div>
</Variant>
</Story>
</template>
@@ -0,0 +1,101 @@
<script setup>
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { CSAT_RATINGS } from 'shared/constants/messages';
const props = defineProps({
ratingPercentage: {
type: Object,
default: () => ({}),
},
ratingCount: {
type: Object,
default: () => ({}),
},
totalResponseCount: {
type: Number,
default: 0,
},
isLoading: {
type: Boolean,
default: false,
},
});
const { t } = useI18n();
const sortedRatings = computed(() =>
[...CSAT_RATINGS].sort((a, b) => b.value - a.value)
);
const formatPercent = value => (value ? `${value}%` : '0%');
const getRatingLabel = value => {
const rating = CSAT_RATINGS.find(r => r.value === value);
return rating ? t(rating.translationKey) : '';
};
const getRatingCount = value => {
return props.ratingCount[value] || 0;
};
</script>
<template>
<div
class="shadow outline-1 outline outline-n-container rounded-xl bg-n-solid-2 px-6 py-5"
>
<span class="text-sm font-medium text-n-slate-11">
{{ $t('CSAT_REPORTS.METRIC.RATING_DISTRIBUTION') }}
</span>
<div v-if="isLoading" class="mt-4">
<div class="h-6 w-full rounded-full bg-n-slate-3 animate-pulse" />
<div class="flex gap-6 mt-4">
<div
v-for="n in 5"
:key="n"
class="h-4 w-20 rounded bg-n-slate-3 animate-pulse"
/>
</div>
</div>
<div v-else class="mt-4">
<div
v-if="totalResponseCount"
class="flex h-6 w-full rounded-full overflow-hidden bg-n-alpha-2"
>
<div
v-for="rating in sortedRatings"
:key="rating.value"
v-tooltip="
`${getRatingLabel(rating.value)}: ${formatPercent(ratingPercentage[rating.value])} (${getRatingCount(rating.value)})`
"
:style="{
width: `${ratingPercentage[rating.value]}%`,
backgroundColor: rating.color,
}"
class="h-full transition-all duration-300 first:rounded-s-full last:rounded-e-full cursor-default"
/>
</div>
<div v-else class="h-6 w-full rounded-full bg-n-alpha-2" />
<div class="flex flex-wrap gap-x-6 gap-y-2 mt-4">
<div
v-for="rating in sortedRatings"
:key="rating.value"
class="flex items-center gap-2"
>
<span class="text-sm text-n-slate-11">
{{ getRatingLabel(rating.value) }}
</span>
<span class="text-sm font-medium text-n-slate-12">
{{ formatPercent(ratingPercentage[rating.value]) }}
</span>
<span class="text-xs text-n-slate-10">
({{ getRatingCount(rating.value) }})
</span>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,28 @@
<script setup>
import { useRouter } from 'vue-router';
import { useMapGetter } from 'dashboard/composables/store';
import BasePaywallModal from 'dashboard/routes/dashboard/settings/components/BasePaywallModal.vue';
const router = useRouter();
const currentAccountId = useMapGetter('getCurrentAccountId');
const goToBillingSettings = () => {
router.push({
name: 'billing_settings_index',
params: { accountId: currentAccountId.value },
});
};
</script>
<template>
<div class="py-4 px-5 bg-n-background">
<div class="flex justify-center">
<BasePaywallModal
feature-prefix="CSAT_REPORTS.REVIEW_NOTES"
i18n-key="PAYWALL"
is-on-chatwoot-cloud
@upgrade="goToBillingSettings"
/>
</div>
</div>
</template>
@@ -1,19 +1,19 @@
<script setup>
import { defineEmits, computed, h } from 'vue';
import { ref, computed } from 'vue';
import { useMapGetter } from 'dashboard/composables/store';
import { useAccount } from 'dashboard/composables/useAccount';
import { useI18n } from 'vue-i18n';
// [TODO] Instead of converting the values to their reprentation when building the tableData
// We should do the change in the cell
import { messageStamp, dynamicTime } from 'shared/helpers/timeHelper';
// components
import Table from 'dashboard/components/table/Table.vue';
import Pagination from 'dashboard/components/table/Pagination.vue';
import UserAvatarWithName from 'dashboard/components/widgets/UserAvatarWithName.vue';
import ConversationCell from './ConversationCell.vue';
import ShowMore from 'dashboard/components/widgets/ShowMore.vue';
import CsatContactCell from './CsatContactCell.vue';
import CsatExpandedRow from './CsatExpandedRow.vue';
import CsatEmptyState from './CsatEmptyState.vue';
import CsatTableLoader from './CsatTableLoader.vue';
// constants
import { CSAT_RATINGS } from 'shared/constants/messages';
import {
@@ -31,97 +31,82 @@ const { pageIndex } = defineProps({
const emit = defineEmits(['pageChange']);
const { t } = useI18n();
// const isRTL = useMapGetter('accounts/isRTL');
const { isCloudFeatureEnabled, isOnChatwootCloud } = useAccount();
const csatResponses = useMapGetter('csat/getCSATResponses');
const isFeatureEnabled = computed(() =>
isCloudFeatureEnabled('csat_review_notes')
);
const showExpandableRows = computed(
() => isFeatureEnabled.value || isOnChatwootCloud.value
);
const metrics = useMapGetter('csat/getMetrics');
const uiFlags = useMapGetter('csat/getUIFlags');
const isLoading = computed(() => uiFlags.value.isFetching);
const expandedRows = ref({});
const toggleRow = id => {
expandedRows.value = {
...expandedRows.value,
[id]: !expandedRows.value[id],
};
};
const isRowExpanded = id => !!expandedRows.value[id];
const tableData = computed(() => {
return csatResponses.value.map(response => ({
id: response.id,
contact: response.contact,
assignedAgent: response.assigned_agent,
rating: response.rating,
feedbackText: response.feedback_message || '---',
feedbackText: response.feedback_message || '',
conversationId: response.conversation_id,
csatReviewNotes: response.csat_review_notes,
createdAgo: dynamicTime(response.created_at),
createdAt: messageStamp(response.created_at, 'LLL d yyyy, h:mm a'),
_original: response,
}));
});
const defaultSpanRender = cellProps => {
const value = cellProps.getValue() || '---';
return h(
'span',
{
class: 'line-clamp-5 break-words max-w-full text-n-slate-12',
title: value,
},
value
);
const getRatingData = rating => {
return CSAT_RATINGS.find(r => r.value === rating) || {};
};
const columnHelper = createColumnHelper();
const columns = computed(() => [
columnHelper.accessor('contact', {
header: t('CSAT_REPORTS.TABLE.HEADER.CONTACT_NAME'),
width: 200,
cell: cellProps => {
const { contact } = cellProps.row.original;
if (contact) {
return h(UserAvatarWithName, {
user: contact,
class: 'max-w-[200px] overflow-hidden',
});
}
return '--';
},
}),
columnHelper.accessor('assignedAgent', {
header: t('CSAT_REPORTS.TABLE.HEADER.AGENT_NAME'),
width: 200,
cell: cellProps => {
const { assignedAgent } = cellProps.row.original;
if (assignedAgent) {
return h(UserAvatarWithName, {
user: assignedAgent,
class: 'max-w-[200px] overflow-hidden',
});
}
return '--';
},
}),
columnHelper.accessor('rating', {
header: t('CSAT_REPORTS.TABLE.HEADER.RATING'),
align: 'center',
width: 80,
cell: cellProps => {
const { rating: giveRating } = cellProps.row.original;
const [ratingObject = {}] = CSAT_RATINGS.filter(
rating => rating.value === giveRating
);
const columns = computed(() => {
const baseColumns = [
columnHelper.accessor('contact', {
header: t('CSAT_REPORTS.TABLE.HEADER.CONTACT_NAME'),
}),
columnHelper.accessor('rating', {
header: t('CSAT_REPORTS.TABLE.HEADER.RATING'),
size: 120,
}),
columnHelper.accessor('feedbackText', {
header: t('CSAT_REPORTS.TABLE.HEADER.FEEDBACK_TEXT'),
size: 500,
}),
columnHelper.accessor('assignedAgent', {
header: t('CSAT_REPORTS.TABLE.HEADER.HANDLED_BY'),
size: 160,
}),
];
return h(
'span',
{
class: ratingObject.emoji
? 'emoji-response text-lg'
: 'text-n-slate-10',
},
ratingObject.emoji || '---'
);
},
}),
columnHelper.accessor('feedbackText', {
header: t('CSAT_REPORTS.TABLE.HEADER.FEEDBACK_TEXT'),
width: 400,
cell: defaultSpanRender,
}),
columnHelper.accessor('conversationId', {
header: '',
width: 100,
cell: cellProps => h(ConversationCell, cellProps),
}),
]);
if (showExpandableRows.value) {
baseColumns.push(
columnHelper.accessor('actions', {
header: '',
size: 50,
})
);
}
return baseColumns;
});
const paginationParams = computed(() => {
return {
@@ -149,25 +134,124 @@ const table = useVueTable({
},
},
onPaginationChange: updater => {
const newPagintaion = updater(paginationParams.value);
emit('pageChange', newPagintaion.pageIndex);
const newPagination = updater(paginationParams.value);
emit('pageChange', newPagination.pageIndex);
},
});
</script>
<template>
<div
class="shadow outline-1 outline outline-n-container rounded-xl bg-n-solid-2 px-6 py-5"
class="shadow outline-1 outline outline-n-container rounded-xl bg-n-solid-2 overflow-hidden"
>
<Table :table="table" class="max-h-[calc(100vh-21.875rem)]" />
<div
v-show="!tableData.length"
class="h-48 flex items-center justify-center text-n-slate-12 text-sm"
>
{{ $t('CSAT_REPORTS.NO_RECORDS') }}
<CsatTableLoader v-if="isLoading" />
<div v-else-if="tableData.length" class="overflow-x-auto">
<table class="w-full">
<thead class="bg-n-solid-2 border-b border-n-container">
<tr>
<th
v-for="header in table.getFlatHeaders()"
:key="header.id"
:style="{
width: header.getSize() ? `${header.getSize()}px` : 'auto',
}"
class="text-left py-3 px-5 font-medium text-sm text-n-slate-12"
>
{{ header.column.columnDef.header }}
</th>
</tr>
</thead>
<tbody class="divide-y divide-n-container">
<template v-for="row in tableData" :key="row.id">
<tr
class="group hover:bg-n-slate-2 dark:hover:bg-n-solid-3 transition-colors"
:class="{
'bg-n-slate-2 dark:bg-n-solid-3': isRowExpanded(row.id),
'cursor-pointer': showExpandableRows,
}"
@click="showExpandableRows && toggleRow(row.id)"
>
<td class="py-4 px-5">
<CsatContactCell
:contact="row.contact"
:conversation-id="row.conversationId"
:created-ago="row.createdAgo"
:created-at="row.createdAt"
/>
</td>
<td class="py-4 px-5">
<div
class="inline-flex items-center gap-1.5 px-2 py-1 rounded-lg"
:style="{
backgroundColor: `${getRatingData(row.rating).color}20`,
}"
>
<span class="text-sm font-medium text-n-slate-12 truncate">
{{ $t(getRatingData(row.rating).translationKey) }}
</span>
</div>
</td>
<td class="py-4 px-5">
<span
v-if="!row.feedbackText"
class="text-n-slate-10 italic text-sm"
>
{{ $t('CSAT_REPORTS.NO_FEEDBACK') }}
</span>
<div v-else class="text-sm text-n-slate-12">
<ShowMore :text="row.feedbackText" :limit="100" />
</div>
</td>
<td class="py-4 px-5">
<UserAvatarWithName
v-if="row.assignedAgent"
:user="row.assignedAgent"
:size="28"
/>
<span v-else class="text-n-slate-10 text-sm italic">
{{ $t('CSAT_REPORTS.NO_AGENT') }}
</span>
</td>
<td v-if="showExpandableRows" class="py-4 px-5">
<div
class="p-1.5 rounded-md text-n-slate-10 group-hover:text-n-slate-12 transition-colors"
>
<i
class="size-4 block transition-transform duration-200"
:class="
isRowExpanded(row.id)
? 'i-lucide-chevron-up'
: 'i-lucide-chevron-down'
"
/>
</div>
</td>
</tr>
<tr
v-if="showExpandableRows && isRowExpanded(row.id)"
class="!border-t-0"
>
<td colspan="5" class="p-0 !border-t-0">
<CsatExpandedRow :response="row._original" />
</td>
</tr>
</template>
</tbody>
</table>
</div>
<div v-if="metrics.totalResponseCount" class="table-pagination">
<Pagination class="mt-2" :table="table" />
<CsatEmptyState
v-else
:title="$t('CSAT_REPORTS.NO_RECORDS')"
:description="$t('CSAT_REPORTS.NO_RECORDS_DESCRIPTION')"
/>
<div
v-if="metrics.totalResponseCount"
class="px-6 py-4 border-t border-n-weak"
>
<Pagination :table="table" />
</div>
</div>
</template>
@@ -0,0 +1,36 @@
<script setup>
defineProps({
rows: {
type: Number,
default: 5,
},
});
</script>
<template>
<div class="p-6">
<div class="space-y-4">
<div class="flex gap-4 pb-3 border-b border-n-weak">
<div class="h-4 w-32 rounded bg-n-slate-3 animate-pulse" />
<div class="h-4 w-28 rounded bg-n-slate-3 animate-pulse" />
<div class="h-4 w-20 rounded bg-n-slate-3 animate-pulse" />
<div class="h-4 flex-1 rounded bg-n-slate-3 animate-pulse" />
<div class="h-4 w-20 rounded bg-n-slate-3 animate-pulse" />
</div>
<div v-for="n in rows" :key="n" class="flex items-center gap-4 py-3">
<div class="flex items-center gap-2 w-48">
<div class="size-8 rounded-full bg-n-slate-3 animate-pulse" />
<div class="h-4 w-24 rounded bg-n-slate-3 animate-pulse" />
</div>
<div class="flex items-center gap-2 w-44">
<div class="size-8 rounded-full bg-n-slate-3 animate-pulse" />
<div class="h-4 w-20 rounded bg-n-slate-3 animate-pulse" />
</div>
<div class="h-7 w-24 rounded-lg bg-n-slate-3 animate-pulse" />
<div class="h-4 flex-1 rounded bg-n-slate-3 animate-pulse" />
<div class="h-4 w-16 rounded bg-n-slate-3 animate-pulse" />
</div>
</div>
</div>
</template>
@@ -6,7 +6,6 @@ describe('CsatMetrics.vue', () => {
let getters;
let store;
let wrapper;
const filters = { rating: 3 };
beforeEach(() => {
getters = {
@@ -18,8 +17,16 @@ describe('CsatMetrics.vue', () => {
4: 30,
5: 10,
}),
'csat/getRatingCount': () => ({
1: 10,
2: 20,
3: 30,
4: 30,
5: 10,
}),
'csat/getSatisfactionScore': () => 85,
'csat/getResponseRate': () => 90,
'csat/getUIFlags': () => ({ isFetchingMetrics: false }),
};
store = createStore({
@@ -28,40 +35,31 @@ describe('CsatMetrics.vue', () => {
wrapper = shallowMount(CsatMetrics, {
global: {
plugins: [store], // Ensure the store is injected here
plugins: [store],
mocks: {
$t: msg => msg, // mock translation function
$t: msg => msg,
},
stubs: {
CsatMetricCard: '<csat-metric-card/>',
BarChart: '<woot-horizontal-bar/>',
CsatMetricCard: true,
CsatRatingDistribution: true,
},
},
props: { filters },
});
});
it('computes response count correctly', () => {
expect(wrapper.vm.responseCount).toBe('100');
expect(wrapper.html()).toMatchSnapshot();
});
it('formats values to percent correctly', () => {
expect(wrapper.vm.formatToPercent(85)).toBe('85%');
expect(wrapper.vm.formatToPercent(null)).toBe('--');
it('renders metric cards with correct values', () => {
const metricCards = wrapper.findAllComponents({ name: 'CsatMetricCard' });
expect(metricCards).toHaveLength(3);
});
it('maps rating value to emoji correctly', () => {
const rating = wrapper.vm.csatRatings[0]; // assuming this is { value: 1, emoji: '😡' }
expect(wrapper.vm.ratingToEmoji(rating.value)).toBe(rating.emoji);
});
it('hides report card if rating filter is enabled', () => {
expect(wrapper.html()).not.toContain('bar-chart-stub');
});
it('shows report card if rating filter is not enabled', async () => {
await wrapper.setProps({ filters: {} });
expect(wrapper.html()).toContain('bar-chart-stub');
it('renders rating distribution component', () => {
const distribution = wrapper.findComponent({
name: 'CsatRatingDistribution',
});
expect(distribution.exists()).toBe(true);
});
});
@@ -1,10 +0,0 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`CsatMetrics.vue > computes response count correctly 1`] = `
"<div class="flex-col lg:flex-row flex flex-wrap mx-0 shadow outline-1 outline outline-n-container rounded-xl bg-n-solid-2 px-6 py-8 gap-4">
<csat-metric-card-stub label="CSAT_REPORTS.METRIC.TOTAL_RESPONSES.LABEL" infotext="CSAT_REPORTS.METRIC.TOTAL_RESPONSES.TOOLTIP" disabled="false" class="xs:w-full sm:max-w-[50%] lg:w-1/6 lg:max-w-[16%]" value="100"></csat-metric-card-stub>
<csat-metric-card-stub label="CSAT_REPORTS.METRIC.SATISFACTION_SCORE.LABEL" infotext="CSAT_REPORTS.METRIC.SATISFACTION_SCORE.TOOLTIP" disabled="true" class="xs:w-full sm:max-w-[50%] lg:w-1/6 lg:max-w-[16%]" value="--"></csat-metric-card-stub>
<csat-metric-card-stub label="CSAT_REPORTS.METRIC.RESPONSE_RATE.LABEL" infotext="CSAT_REPORTS.METRIC.RESPONSE_RATE.TOOLTIP" disabled="false" class="xs:w-full sm:max-w-[50%] lg:w-1/6 lg:max-w-[16%]" value="90%"></csat-metric-card-stub>
<!--v-if-->
</div>"
`;
@@ -78,7 +78,6 @@ const getValueFromConversation = (conversation, attributeKey) => {
case 'team_id':
return conversation.meta?.team?.id;
case 'browser_language':
case 'country_code':
case 'referer':
return conversation.additional_attributes?.[attributeKey];
default:
@@ -82,6 +82,9 @@ export const getters = {
),
};
},
getRatingCount(_state) {
return _state.metrics.ratingsCount;
},
};
export const actions = {
@@ -115,6 +118,13 @@ export const actions = {
});
});
},
update: async ({ commit }, { id, reviewNotes }) => {
const response = await CSATReports.update(id, {
csat_review_notes: reviewNotes,
});
commit(types.UPDATE_CSAT_RESPONSE, response.data);
return response.data;
},
};
export const mutations = {
@@ -144,6 +154,7 @@ export const mutations = {
};
_state.metrics.totalSentMessagesCount = totalSentMessagesCount || 0;
},
[types.UPDATE_CSAT_RESPONSE]: MutationHelpers.update,
};
export default {
@@ -234,6 +234,19 @@ export const actions = {
console.error(error);
});
},
downloadConversationsSummaryReports(_, reportObj) {
return Report.getConversationsSummaryReports(reportObj)
.then(response => {
downloadCsvFile(reportObj.fileName, response.data);
AnalyticsHelper.track(REPORTS_EVENTS.DOWNLOAD_REPORT, {
reportType: 'conversations_summary',
businessHours: reportObj?.businessHours,
});
})
.catch(error => {
console.error(error);
});
},
downloadLabelReports(_, reportObj) {
return Report.getLabelReports(reportObj)
.then(response => {
@@ -86,4 +86,19 @@ describe('#getters', () => {
})
).toEqual('50.00');
});
it('getRatingCount', () => {
const state = {
metrics: {
ratingsCount: { 1: 10, 2: 20, 3: 15, 4: 3, 5: 2 },
},
};
expect(getters.getRatingCount(state)).toEqual({
1: 10,
2: 20,
3: 15,
4: 3,
5: 2,
});
});
});
@@ -201,4 +201,24 @@ describe('#actions', () => {
);
});
});
describe('#downloadConversationsSummaryReports', () => {
it('open CSV download prompt if API is success', async () => {
const data = `Conversations,Messages received,Messages sent,Avg first response time,Avg resolution time,Resolution count,Avg customer waiting time
217,323,623,23 hours 22 minutes,179 days 18 hours,30,48 days 4 hours`;
axios.get.mockResolvedValue({ data });
const param = {
from: 1631039400,
to: 1635013800,
fileName: 'conversations-summary-report-24-10-2021.csv',
};
actions.downloadConversationsSummaryReports(1, param);
await flushPromises();
expect(DownloadHelper.downloadCsvFile).toBeCalledWith(
param.fileName,
data
);
});
});
});
@@ -241,6 +241,7 @@ export default {
SET_CSAT_RESPONSE_UI_FLAG: 'SET_CSAT_RESPONSE_UI_FLAG',
SET_CSAT_RESPONSE: 'SET_CSAT_RESPONSE',
SET_CSAT_RESPONSE_METRICS: 'SET_CSAT_RESPONSE_METRICS',
UPDATE_CSAT_RESPONSE: 'UPDATE_CSAT_RESPONSE',
// Custom Attributes
SET_CUSTOM_ATTRIBUTE_UI_FLAG: 'SET_CUSTOM_ATTRIBUTE_UI_FLAG',
@@ -1,3 +1,7 @@
import { getAllowedFileTypesByChannel } from '@chatwoot/utils';
import { INBOX_TYPES } from 'dashboard/helper/inbox';
import { ALLOWED_FILE_TYPES } from 'shared/constants/messages';
export const DEFAULT_MAXIMUM_FILE_UPLOAD_SIZE = 40;
export const formatBytes = (bytes, decimals = 2) => {
@@ -31,3 +35,55 @@ export const resolveMaximumFileUploadSize = value => {
return parsedValue;
};
/**
* Validates if a file type is allowed for a specific channel
* @param {File} file - The file to validate
* @param {Object} options - Validation options
* @param {string} options.channelType - The channel type
* @param {string} options.medium - The channel medium
* @param {string} options.conversationType - The conversation type (for Instagram DM detection)
* @param {boolean} options.isInstagramChannel - Whether it's an Instagram channel
* @param {boolean} options.isOnPrivateNote - Whether composing a private note (uses broader file type list)
* @returns {boolean} - True if file type is allowed, false otherwise
*/
export const isFileTypeAllowedForChannel = (file, options = {}) => {
if (!file || file.size === 0) return false;
const {
channelType: originalChannelType,
medium,
conversationType,
isInstagramChannel,
isOnPrivateNote,
} = options;
// Use broader file types for private notes (matches file picker behavior)
const allowedFileTypes = isOnPrivateNote
? ALLOWED_FILE_TYPES
: getAllowedFileTypesByChannel({
channelType:
isInstagramChannel || conversationType === 'instagram_direct_message'
? INBOX_TYPES.INSTAGRAM
: originalChannelType,
medium,
});
// Convert to array and validate
const allowedTypesArray = allowedFileTypes.split(',').map(t => t.trim());
const fileExtension = `.${file.name.split('.').pop()}`;
return allowedTypesArray.some(allowedType => {
// Check for exact file extension match
if (allowedType === fileExtension) return true;
// Check for wildcard MIME type (e.g., image/*)
if (allowedType.endsWith('/*')) {
const prefix = allowedType.slice(0, -2); // Remove '/*'
return file.type.startsWith(prefix + '/');
}
// Check for exact MIME type match
return allowedType === file.type;
});
};
@@ -4,6 +4,7 @@ import {
fileSizeInMegaBytes,
checkFileSizeLimit,
resolveMaximumFileUploadSize,
isFileTypeAllowedForChannel,
} from '../FileHelper';
describe('#File Helpers', () => {
@@ -61,4 +62,187 @@ describe('#File Helpers', () => {
expect(resolveMaximumFileUploadSize(75)).toBe(75);
});
});
describe('isFileTypeAllowedForChannel', () => {
describe('edge cases', () => {
it('should return false for null file', () => {
expect(isFileTypeAllowedForChannel(null)).toBe(false);
});
it('should return false for undefined file', () => {
expect(isFileTypeAllowedForChannel(undefined)).toBe(false);
});
it('should return false for file with zero size', () => {
const file = { name: 'test.png', type: 'image/png', size: 0 };
expect(isFileTypeAllowedForChannel(file)).toBe(false);
});
});
describe('wildcard MIME types', () => {
it('should allow image/png when image/* is allowed', () => {
const file = { name: 'test.png', type: 'image/png', size: 1000 };
expect(
isFileTypeAllowedForChannel(file, {
channelType: 'Channel::WebWidget',
})
).toBe(true);
});
it('should allow image/jpeg when image/* is allowed', () => {
const file = { name: 'test.jpg', type: 'image/jpeg', size: 1000 };
expect(
isFileTypeAllowedForChannel(file, {
channelType: 'Channel::WebWidget',
})
).toBe(true);
});
it('should allow audio/mp3 when audio/* is allowed', () => {
const file = { name: 'test.mp3', type: 'audio/mp3', size: 1000 };
expect(
isFileTypeAllowedForChannel(file, {
channelType: 'Channel::WebWidget',
})
).toBe(true);
});
it('should allow video/mp4 when video/* is allowed', () => {
const file = { name: 'test.mp4', type: 'video/mp4', size: 1000 };
expect(
isFileTypeAllowedForChannel(file, {
channelType: 'Channel::WebWidget',
})
).toBe(true);
});
});
describe('exact MIME types', () => {
it('should allow application/pdf when explicitly allowed', () => {
const file = { name: 'test.pdf', type: 'application/pdf', size: 1000 };
expect(
isFileTypeAllowedForChannel(file, {
channelType: 'Channel::WebWidget',
})
).toBe(true);
});
it('should allow text/plain when explicitly allowed', () => {
const file = { name: 'test.txt', type: 'text/plain', size: 1000 };
expect(
isFileTypeAllowedForChannel(file, {
channelType: 'Channel::WebWidget',
})
).toBe(true);
});
});
describe('file extensions', () => {
it('should allow .3gpp extension when explicitly allowed', () => {
const file = { name: 'test.3gpp', type: '', size: 1000 };
expect(
isFileTypeAllowedForChannel(file, {
channelType: 'Channel::WebWidget',
})
).toBe(true);
});
});
describe('Instagram special handling', () => {
it('should use Instagram rules when isInstagramChannel is true', () => {
const file = { name: 'test.png', type: 'image/png', size: 1000 };
expect(
isFileTypeAllowedForChannel(file, {
channelType: 'Channel::WebWidget',
isInstagramChannel: true,
})
).toBe(true);
});
it('should use Instagram rules when conversationType is instagram_direct_message', () => {
const file = { name: 'test.png', type: 'image/png', size: 1000 };
expect(
isFileTypeAllowedForChannel(file, {
channelType: 'Channel::WebWidget',
conversationType: 'instagram_direct_message',
})
).toBe(true);
});
});
describe('disallowed file types', () => {
it('should reject executable files', () => {
const file = {
name: 'malware.exe',
type: 'application/x-msdownload',
size: 1000,
};
expect(
isFileTypeAllowedForChannel(file, {
channelType: 'Channel::WebWidget',
})
).toBe(false);
});
it('should reject unsupported file types', () => {
const file = {
name: 'test.xyz',
type: 'application/x-unknown',
size: 1000,
};
expect(
isFileTypeAllowedForChannel(file, {
channelType: 'Channel::WebWidget',
})
).toBe(false);
});
});
describe('channel-specific rules', () => {
it('should allow WhatsApp-specific file types', () => {
const file = { name: 'test.pdf', type: 'application/pdf', size: 1000 };
expect(
isFileTypeAllowedForChannel(file, {
channelType: 'Channel::Whatsapp',
})
).toBe(true);
});
it('should allow Twilio WhatsApp-specific file types', () => {
const file = { name: 'test.pdf', type: 'application/pdf', size: 1000 };
expect(
isFileTypeAllowedForChannel(file, {
channelType: 'Channel::TwilioSms',
medium: 'whatsapp',
})
).toBe(true);
});
});
describe('private note file types', () => {
it('should allow broader file types for private notes', () => {
const file = {
name: 'test.pdf',
type: 'application/pdf',
size: 1000,
};
expect(
isFileTypeAllowedForChannel(file, {
channelType: 'Channel::Line',
isOnPrivateNote: true,
})
).toBe(true);
});
it('should allow CSV files in private notes', () => {
const file = { name: 'data.csv', type: 'text/csv', size: 1000 };
expect(
isFileTypeAllowedForChannel(file, {
channelType: 'Channel::Line',
isOnPrivateNote: true,
})
).toBe(true);
});
});
});
});
+9
View File
@@ -82,6 +82,7 @@ export default {
const { websiteToken, locale, widgetColor } = window.chatwootWebChannel;
this.setLocale(locale);
this.setWidgetColor(widgetColor);
this.setWidgetColorVariable(widgetColor);
setHeader(window.authToken);
if (this.isIFrame) {
this.registerListeners();
@@ -114,6 +115,14 @@ export default {
'resetCampaign',
]),
...mapActions('agent', ['fetchAvailableAgents']),
setWidgetColorVariable(widgetColor) {
if (widgetColor) {
document.documentElement.style.setProperty(
'--widget-color',
widgetColor
);
}
},
scrollConversationToBottom() {
const container = this.$el.querySelector('.conversation-wrap');
container.scrollTop = container.scrollHeight;
@@ -130,7 +130,7 @@ export default {
<div
class="items-center flex ltr:pl-3 rtl:pr-3 ltr:pr-2 rtl:pl-2 rounded-[7px] transition-all duration-200 bg-n-background !shadow-[0_0_0_1px,0_0_2px_3px]"
:class="{
'!shadow-n-brand dark:!shadow-n-brand': isFocused,
'!shadow-[var(--widget-color,#2781f6)]': isFocused,
'!shadow-n-strong dark:!shadow-n-strong': !isFocused,
}"
@keydown.esc="hideEmojiPicker"
+7 -5
View File
@@ -16,10 +16,12 @@ class Conversations::ResolutionJob < ApplicationJob
private
def conversation_scope(account)
if account.auto_resolve_ignore_waiting
account.conversations.resolvable_not_waiting(account.auto_resolve_after)
else
account.conversations.resolvable_all(account.auto_resolve_after)
end
base_scope = if account.auto_resolve_ignore_waiting
account.conversations.resolvable_not_waiting(account.auto_resolve_after)
else
account.conversations.resolvable_all(account.auto_resolve_after)
end
# Exclude orphan conversations where contact was deleted but conversation cleanup is pending
base_scope.where.not(contact_id: nil)
end
end
+5 -2
View File
@@ -159,8 +159,11 @@ class ActionCableListener < BaseListener
end
def contact_deleted(event)
contact, account = extract_contact_and_account(event)
broadcast(account, [account_token(account)], CONTACT_DELETED, contact.push_event_data)
contact_data = event.data[:contact_data]
account = Account.find_by(id: contact_data[:account_id])
return if account.blank?
broadcast(account, [account_token(account)], CONTACT_DELETED, contact_data)
end
def conversation_mentioned(event)
@@ -2,17 +2,21 @@ module ConversationMuteHelpers
extend ActiveSupport::Concern
def mute!
return unless contact
resolved!
contact.update(blocked: true)
create_muted_message
end
def unmute!
return unless contact
contact.update(blocked: false)
create_unmuted_message
end
def muted?
contact.blocked?
contact&.blocked? || false
end
end
+10 -6
View File
@@ -179,11 +179,9 @@ class Contact < ApplicationRecord
end
def self.resolved_contacts(use_crm_v2: false)
if use_crm_v2
where(contact_type: 'lead')
else
where("contacts.email <> '' OR contacts.phone_number <> '' OR contacts.identifier <> ''")
end
return where(contact_type: 'lead') if use_crm_v2
where("contacts.email <> '' OR contacts.phone_number <> '' OR contacts.identifier <> ''")
end
def discard_invalid_attrs
@@ -243,7 +241,13 @@ class Contact < ApplicationRecord
end
def dispatch_destroy_event
Rails.configuration.dispatcher.dispatch(CONTACT_DELETED, Time.zone.now, contact: self)
# Pass serialized data instead of ActiveRecord object to avoid DeserializationError
# when the async EventDispatcherJob runs after the contact has been deleted
Rails.configuration.dispatcher.dispatch(
CONTACT_DELETED,
Time.zone.now,
contact_data: push_event_data.merge(account_id: account_id)
)
end
end
Contact.include_mod_with('Concerns::Contact')
+1
View File
@@ -27,6 +27,7 @@ class CsatSurveyResponse < ApplicationRecord
belongs_to :contact
belongs_to :message
belongs_to :assigned_agent, class_name: 'User', optional: true, inverse_of: :csat_survey_responses
belongs_to :review_notes_updated_by, class_name: 'User', optional: true
validates :rating, presence: true, inclusion: { in: [1, 2, 3, 4, 5] }
validates :account_id, presence: true
+4
View File
@@ -158,6 +158,10 @@ class Inbox < ApplicationRecord
channel_type == 'Channel::Whatsapp'
end
def twilio_whatsapp?
channel_type == 'Channel::TwilioSms' && channel.medium == 'whatsapp'
end
def assignable_agents
(account.users.where(id: members.select(:user_id)) + account.administrators).uniq
end
+2
View File
@@ -90,6 +90,8 @@ class User < ApplicationRecord
has_many :assigned_conversations, foreign_key: 'assignee_id', class_name: 'Conversation', dependent: :nullify, inverse_of: :assignee
alias_attribute :conversations, :assigned_conversations
has_many :csat_survey_responses, foreign_key: 'assigned_agent_id', dependent: :nullify, inverse_of: :assigned_agent
has_many :reviewed_csat_survey_responses, foreign_key: 'review_notes_updated_by_id', class_name: 'CsatSurveyResponse',
dependent: :nullify, inverse_of: :review_notes_updated_by
has_many :conversation_participants, dependent: :destroy_async
has_many :participating_conversations, through: :conversation_participants, source: :conversation
+76 -3
View File
@@ -6,6 +6,8 @@ class CsatSurveyService
if whatsapp_channel? && template_available_and_approved?
send_whatsapp_template_survey
elsif inbox.twilio_whatsapp? && twilio_template_available_and_approved?
send_twilio_whatsapp_template_survey
elsif within_messaging_window?
::MessageTemplates::Template::CsatSurvey.new(conversation: conversation).perform
else
@@ -18,7 +20,7 @@ class CsatSurveyService
delegate :inbox, :contact, to: :conversation
def should_send_csat_survey?
conversation_allows_csat? && csat_enabled? && !csat_already_sent?
conversation_allows_csat? && csat_enabled? && !csat_already_sent? && csat_allowed_by_survey_rules?
end
def conversation_allows_csat?
@@ -37,6 +39,37 @@ class CsatSurveyService
conversation.can_reply?
end
def csat_allowed_by_survey_rules?
return true unless survey_rules_configured?
labels = conversation.label_list
return true if rule_values.empty?
case rule_operator
when 'contains'
rule_values.any? { |label| labels.include?(label) }
when 'does_not_contain'
rule_values.none? { |label| labels.include?(label) }
else
true
end
end
def survey_rules_configured?
return false if csat_config.blank?
return false if csat_config['survey_rules'].blank?
rule_values.any?
end
def rule_operator
csat_config.dig('survey_rules', 'operator') || 'contains'
end
def rule_values
csat_config.dig('survey_rules', 'values') || []
end
def whatsapp_channel?
inbox.channel_type == 'Channel::Whatsapp'
end
@@ -45,7 +78,7 @@ class CsatSurveyService
template_config = inbox.csat_config&.dig('template')
return false unless template_config
template_name = template_config['name'] || Whatsapp::CsatTemplateNameService.csat_template_name(inbox.id)
template_name = template_config['name'] || CsatTemplateNameService.csat_template_name(inbox.id)
status_result = inbox.channel.provider_service.get_template_status(template_name)
@@ -55,9 +88,25 @@ class CsatSurveyService
false
end
def twilio_template_available_and_approved?
template_config = inbox.csat_config&.dig('template')
return false unless template_config
content_sid = template_config['content_sid']
return false unless content_sid
template_service = Twilio::CsatTemplateService.new(inbox.channel)
status_result = template_service.get_template_status(content_sid)
status_result[:success] && status_result[:template][:status] == 'approved'
rescue StandardError => e
Rails.logger.error "Error checking Twilio CSAT template status: #{e.message}"
false
end
def send_whatsapp_template_survey
template_config = inbox.csat_config&.dig('template')
template_name = template_config['name'] || Whatsapp::CsatTemplateNameService.csat_template_name(inbox.id)
template_name = template_config['name'] || CsatTemplateNameService.csat_template_name(inbox.id)
phone_number = conversation.contact_inbox.source_id
template_info = build_template_info(template_name, template_config)
@@ -95,6 +144,30 @@ class CsatSurveyService
)
end
def csat_config
inbox.csat_config || {}
end
def send_twilio_whatsapp_template_survey
template_config = inbox.csat_config&.dig('template')
content_sid = template_config['content_sid']
phone_number = conversation.contact_inbox.source_id
content_variables = { '1' => conversation.uuid }
message = build_csat_message
send_service = Twilio::SendOnTwilioService.new(message: message)
result = send_service.send_csat_template_message(
phone_number: phone_number,
content_sid: content_sid,
content_variables: content_variables
)
message.update!(source_id: result[:message_id]) if result[:success] && result[:message_id].present?
rescue StandardError => e
Rails.logger.error "Error sending Twilio WhatsApp CSAT template for conversation #{conversation.id}: #{e.message}"
end
def create_csat_not_sent_activity_message
content = I18n.t('conversations.activity.csat.not_sent_due_to_messaging_window')
activity_message_params = {
@@ -0,0 +1,196 @@
class CsatTemplateManagementService
DEFAULT_BUTTON_TEXT = 'Please rate us'.freeze
DEFAULT_LANGUAGE = 'en'.freeze
def initialize(inbox)
@inbox = inbox
end
def template_status
template = @inbox.csat_config&.dig('template')
return { template_exists: false } unless template
if @inbox.twilio_whatsapp?
get_twilio_template_status(template)
else
get_whatsapp_template_status(template)
end
rescue StandardError => e
Rails.logger.error "Error fetching CSAT template status: #{e.message}"
{ service_error: e.message }
end
def create_template(template_params)
validate_template_params!(template_params)
delete_existing_template_if_needed
result = create_template_via_provider(template_params)
update_inbox_csat_config(result) if result[:success]
result
rescue StandardError => e
Rails.logger.error "Error creating CSAT template: #{e.message}"
{ success: false, service_error: 'Template creation failed' }
end
private
def validate_template_params!(template_params)
raise ActionController::ParameterMissing, 'message' if template_params[:message].blank?
end
def create_template_via_provider(template_params)
if @inbox.twilio_whatsapp?
create_twilio_template(template_params)
else
create_whatsapp_template(template_params)
end
end
def create_twilio_template(template_params)
template_config = build_template_config(template_params)
template_service = Twilio::CsatTemplateService.new(@inbox.channel)
template_service.create_template(template_config)
end
def create_whatsapp_template(template_params)
template_config = build_template_config(template_params)
Whatsapp::CsatTemplateService.new(@inbox.channel).create_template(template_config)
end
def build_template_config(template_params)
{
message: template_params[:message],
button_text: template_params[:button_text] || DEFAULT_BUTTON_TEXT,
base_url: ENV.fetch('FRONTEND_URL', 'http://localhost:3000'),
language: template_params[:language] || DEFAULT_LANGUAGE,
template_name: CsatTemplateNameService.csat_template_name(@inbox.id)
}
end
def update_inbox_csat_config(result)
current_config = @inbox.csat_config || {}
template_data = build_template_data_from_result(result)
updated_config = current_config.merge('template' => template_data)
@inbox.update!(csat_config: updated_config)
end
def build_template_data_from_result(result)
if @inbox.twilio_whatsapp?
build_twilio_template_data(result)
else
build_whatsapp_cloud_template_data(result)
end
end
def build_twilio_template_data(result)
{
'friendly_name' => result[:friendly_name],
'content_sid' => result[:content_sid],
'approval_sid' => result[:approval_sid],
'language' => result[:language],
'status' => result[:whatsapp_status] || result[:status],
'created_at' => Time.current.iso8601
}.compact
end
def build_whatsapp_cloud_template_data(result)
{
'name' => result[:template_name],
'template_id' => result[:template_id],
'language' => result[:language],
'created_at' => Time.current.iso8601
}
end
def get_twilio_template_status(template)
content_sid = template['content_sid']
return { template_exists: false } unless content_sid
template_service = Twilio::CsatTemplateService.new(@inbox.channel)
status_result = template_service.get_template_status(content_sid)
if status_result[:success]
{
template_exists: true,
friendly_name: template['friendly_name'],
content_sid: template['content_sid'],
status: status_result[:template][:status],
language: template['language']
}
else
{
template_exists: false,
error: 'Template not found'
}
end
end
def get_whatsapp_template_status(template)
template_name = template['name'] || CsatTemplateNameService.csat_template_name(@inbox.id)
status_result = Whatsapp::CsatTemplateService.new(@inbox.channel).get_template_status(template_name)
if status_result[:success]
{
template_exists: true,
template_name: template_name,
status: status_result[:template][:status],
template_id: status_result[:template][:id]
}
else
{
template_exists: false,
error: 'Template not found'
}
end
end
def delete_existing_template_if_needed
template = @inbox.csat_config&.dig('template')
return true if template.blank?
if @inbox.twilio_whatsapp?
delete_existing_twilio_template(template)
else
delete_existing_whatsapp_template(template)
end
rescue StandardError => e
Rails.logger.error "Error during template deletion for inbox #{@inbox.id}: #{e.message}"
false
end
def delete_existing_twilio_template(template)
content_sid = template['content_sid']
return true if content_sid.blank?
template_service = Twilio::CsatTemplateService.new(@inbox.channel)
deletion_result = template_service.delete_template(nil, content_sid)
if deletion_result[:success]
Rails.logger.info "Deleted existing Twilio CSAT template '#{content_sid}' for inbox #{@inbox.id}"
true
else
Rails.logger.warn "Failed to delete existing Twilio CSAT template '#{content_sid}' for inbox #{@inbox.id}: #{deletion_result[:response_body]}"
false
end
end
def delete_existing_whatsapp_template(template)
template_name = template['name']
return true if template_name.blank?
csat_template_service = Whatsapp::CsatTemplateService.new(@inbox.channel)
template_status = csat_template_service.get_template_status(template_name)
return true unless template_status[:success]
deletion_result = csat_template_service.delete_template(template_name)
if deletion_result[:success]
Rails.logger.info "Deleted existing CSAT template '#{template_name}' for inbox #{@inbox.id}"
true
else
Rails.logger.warn "Failed to delete existing CSAT template '#{template_name}' for inbox #{@inbox.id}: #{deletion_result[:response_body]}"
false
end
end
end
@@ -1,4 +1,4 @@
class Whatsapp::CsatTemplateNameService
class CsatTemplateNameService
CSAT_BASE_NAME = 'customer_satisfaction_survey'.freeze
# Generates template names like: customer_satisfaction_survey_{inbox_id}_{version_number}
@@ -2,8 +2,6 @@ class MessageTemplates::Template::CsatSurvey
pattr_initialize [:conversation!]
def perform
return unless should_send_csat_survey?
ActiveRecord::Base.transaction do
conversation.messages.create!(csat_survey_message_params)
end
@@ -13,39 +11,6 @@ class MessageTemplates::Template::CsatSurvey
delegate :contact, :account, :inbox, to: :conversation
def should_send_csat_survey?
return true unless survey_rules_configured?
labels = conversation.label_list
return true if rule_values.empty?
case rule_operator
when 'contains'
rule_values.any? { |label| labels.include?(label) }
when 'does_not_contain'
rule_values.none? { |label| labels.include?(label) }
else
true
end
end
def survey_rules_configured?
return false if csat_config.blank?
return false if csat_config['survey_rules'].blank?
return false if rule_values.empty?
true
end
def rule_operator
csat_config.dig('survey_rules', 'operator') || 'contains'
end
def rule_values
csat_config.dig('survey_rules', 'values') || []
end
def message_content
return I18n.t('conversations.templates.csat_input_message_body') if csat_config.blank? || csat_config['message'].blank?
@@ -0,0 +1,68 @@
class Twilio::CsatTemplateApiClient
def initialize(twilio_channel)
@twilio_channel = twilio_channel
end
def create_template(request_body)
HTTParty.post(
"#{api_base_path}/v1/Content",
headers: api_headers,
body: request_body.to_json
)
end
def submit_for_approval(approval_url, template_name, category)
request_body = {
name: template_name,
category: category
}
HTTParty.post(
approval_url,
headers: api_headers,
body: request_body.to_json
)
end
def delete_template(content_sid)
HTTParty.delete(
"#{api_base_path}/v1/Content/#{content_sid}",
headers: api_headers
)
end
def fetch_template(content_sid)
HTTParty.get(
"#{api_base_path}/v1/Content/#{content_sid}",
headers: api_headers
)
end
def fetch_approval_status(content_sid)
HTTParty.get(
"#{api_base_path}/v1/Content/#{content_sid}/ApprovalRequests",
headers: api_headers
)
end
private
def api_headers
{
'Authorization' => "Basic #{encoded_credentials}",
'Content-Type' => 'application/json'
}
end
def encoded_credentials
if @twilio_channel.api_key_sid.present?
Base64.strict_encode64("#{@twilio_channel.api_key_sid}:#{@twilio_channel.auth_token}")
else
Base64.strict_encode64("#{@twilio_channel.account_sid}:#{@twilio_channel.auth_token}")
end
end
def api_base_path
'https://content.twilio.com'
end
end
@@ -0,0 +1,204 @@
class Twilio::CsatTemplateService
DEFAULT_BUTTON_TEXT = 'Please rate us'.freeze
DEFAULT_LANGUAGE = 'en'.freeze
TEMPLATE_CATEGORY = 'UTILITY'.freeze
TEMPLATE_STATUS_PENDING = 'PENDING'.freeze
TEMPLATE_CONTENT_TYPE = 'twilio/call-to-action'.freeze
def initialize(twilio_channel)
@twilio_channel = twilio_channel
@api_client = Twilio::CsatTemplateApiClient.new(twilio_channel)
end
def create_template(template_config)
base_name = template_config[:template_name]
template_name = generate_template_name(base_name)
template_config_with_name = template_config.merge(template_name: template_name)
request_body = build_template_request_body(template_config_with_name)
# Step 1: Create template
response = @api_client.create_template(request_body)
return process_template_creation_response(response, template_config_with_name) unless response.success? && response['sid']
# Step 2: Submit for WhatsApp approval using the approval_create URL
approval_url = response.dig('links', 'approval_create')
if approval_url.present?
approval_response = submit_for_whatsapp_approval(approval_url, template_config_with_name[:template_name])
process_approval_response(approval_response, response, template_config_with_name)
else
Rails.logger.warn 'No approval_create URL provided in template creation response'
# Fallback if no approval URL provided
process_template_creation_response(response, template_config_with_name)
end
end
def delete_template(_template_name = nil, content_sid = nil)
content_sid ||= current_template_sid_from_config
return { success: false, error: 'No template to delete' } unless content_sid
response = @api_client.delete_template(content_sid)
{ success: response.success?, response_body: response.body }
end
def get_template_status(content_sid)
return { success: false, error: 'No content SID provided' } unless content_sid
template_response = fetch_template_details(content_sid)
return template_response unless template_response[:success]
approval_response = fetch_approval_status(content_sid)
build_template_status_response(content_sid, template_response[:data], approval_response)
rescue StandardError => e
Rails.logger.error "Error fetching Twilio template status: #{e.message}"
{ success: false, error: e.message }
end
private
def fetch_template_details(content_sid)
response = @api_client.fetch_template(content_sid)
if response.success?
{ success: true, data: response }
else
Rails.logger.error "Failed to get template details: #{response.code} - #{response.body}"
{ success: false, error: 'Template not found' }
end
end
def fetch_approval_status(content_sid)
@api_client.fetch_approval_status(content_sid)
end
def build_template_status_response(content_sid, template_response, approval_response)
if approval_response.success? && approval_response['whatsapp']
build_approved_template_response(content_sid, template_response, approval_response['whatsapp'])
else
build_pending_template_response(content_sid, template_response)
end
end
def build_approved_template_response(content_sid, template_response, whatsapp_data)
{
success: true,
template: {
content_sid: content_sid,
friendly_name: whatsapp_data['name'] || template_response['friendly_name'],
status: whatsapp_data['status'] || 'pending',
language: template_response['language'] || 'en'
}
}
end
def build_pending_template_response(content_sid, template_response)
{
success: true,
template: {
content_sid: content_sid,
friendly_name: template_response['friendly_name'],
status: 'pending',
language: template_response['language'] || 'en'
}
}
end
def generate_template_name(base_name)
current_template_name = current_template_name_from_config
CsatTemplateNameService.generate_next_template_name(base_name, @twilio_channel.inbox.id, current_template_name)
end
def current_template_name_from_config
@twilio_channel.inbox.csat_config&.dig('template', 'friendly_name')
end
def current_template_sid_from_config
@twilio_channel.inbox.csat_config&.dig('template', 'content_sid')
end
def template_exists_in_config?
content_sid = current_template_sid_from_config
friendly_name = current_template_name_from_config
content_sid.present? && friendly_name.present?
end
def build_template_request_body(template_config)
{
friendly_name: template_config[:template_name],
language: template_config[:language] || DEFAULT_LANGUAGE,
variables: {
'1' => '12345' # Example conversation UUID
},
types: {
TEMPLATE_CONTENT_TYPE => {
body: template_config[:message],
actions: [
{
type: 'URL',
title: template_config[:button_text] || DEFAULT_BUTTON_TEXT,
url: "#{template_config[:base_url]}/survey/responses/{{1}}"
}
]
}
}
}
end
def submit_for_whatsapp_approval(approval_url, template_name)
@api_client.submit_for_approval(approval_url, template_name, TEMPLATE_CATEGORY)
end
def process_template_creation_response(response, template_config = {})
if response.success? && response['sid']
{
success: true,
content_sid: response['sid'],
friendly_name: template_config[:template_name],
language: template_config[:language] || DEFAULT_LANGUAGE,
status: TEMPLATE_STATUS_PENDING
}
else
Rails.logger.error "Twilio template creation failed: #{response.code} - #{response.body}"
{
success: false,
error: 'Template creation failed',
response_body: response.body
}
end
end
def process_approval_response(approval_response, creation_response, template_config)
if approval_response.success?
build_successful_approval_response(approval_response, creation_response, template_config)
else
build_failed_approval_response(approval_response, creation_response, template_config)
end
end
def build_successful_approval_response(approval_response, creation_response, template_config)
approval_data = approval_response.parsed_response
{
success: true,
content_sid: creation_response['sid'],
friendly_name: template_config[:template_name],
language: template_config[:language] || DEFAULT_LANGUAGE,
status: TEMPLATE_STATUS_PENDING,
approval_sid: approval_data['sid'],
whatsapp_status: approval_data.dig('whatsapp', 'status') || TEMPLATE_STATUS_PENDING
}
end
def build_failed_approval_response(approval_response, creation_response, template_config)
Rails.logger.error "Twilio template approval submission failed: #{approval_response.code} - #{approval_response.body}"
{
success: true,
content_sid: creation_response['sid'],
friendly_name: template_config[:template_name],
language: template_config[:language] || DEFAULT_LANGUAGE,
status: 'created'
}
end
end
@@ -1,4 +1,24 @@
class Twilio::SendOnTwilioService < Base::SendOnChannelService
def send_csat_template_message(phone_number:, content_sid:, content_variables: {})
send_params = {
to: phone_number,
content_sid: content_sid
}
send_params[:content_variables] = content_variables.to_json if content_variables.present?
send_params[:status_callback] = channel.send(:twilio_delivery_status_index_url) if channel.respond_to?(:twilio_delivery_status_index_url, true)
# Add messaging service or from number
send_params = send_params.merge(channel.send(:send_message_from))
twilio_message = channel.send(:client).messages.create(**send_params)
{ success: true, message_id: twilio_message.sid }
rescue Twilio::REST::TwilioError, Twilio::REST::RestError => e
Rails.logger.error "Failed to send Twilio template message: #{e.message}"
{ success: false, error: e.message }
end
private
def channel_class
@@ -19,7 +19,7 @@ class Whatsapp::CsatTemplateService
end
def delete_template(template_name = nil)
template_name ||= Whatsapp::CsatTemplateNameService.csat_template_name(@whatsapp_channel.inbox.id)
template_name ||= CsatTemplateNameService.csat_template_name(@whatsapp_channel.inbox.id)
response = HTTParty.delete(
"#{business_account_path}/message_templates?name=#{template_name}",
headers: api_headers
@@ -51,7 +51,7 @@ class Whatsapp::CsatTemplateService
def generate_template_name(base_name)
current_template_name = current_template_name_from_config
Whatsapp::CsatTemplateNameService.generate_next_template_name(base_name, @whatsapp_channel.inbox.id, current_template_name)
CsatTemplateNameService.generate_next_template_name(base_name, @whatsapp_channel.inbox.id, current_template_name)
end
def current_template_name_from_config
@@ -67,7 +67,7 @@ class Whatsapp::Providers::WhatsappCloudService < Whatsapp::Providers::BaseServi
end
def delete_csat_template(template_name = nil)
template_name ||= Whatsapp::CsatTemplateNameService.csat_template_name(whatsapp_channel.inbox.id)
template_name ||= CsatTemplateNameService.csat_template_name(whatsapp_channel.inbox.id)
csat_template_service.delete_template(template_name)
end
@@ -20,7 +20,9 @@ class Whatsapp::TemplateProcessorService
def find_template
channel.message_templates.find do |t|
t['name'] == template_params['name'] && t['language'] == template_params['language'] && t['status']&.downcase == 'approved'
t['name'] == template_params['name'] &&
t['language']&.downcase == template_params['language']&.downcase &&
t['status']&.downcase == 'approved'
end
end
@@ -1,5 +1,5 @@
<%=
CSV.generate_line([
<%
headers = [
I18n.t('reports.csat.headers.agent_name'),
I18n.t('reports.csat.headers.rating'),
I18n.t('reports.csat.headers.feedback'),
@@ -8,24 +8,28 @@
I18n.t('reports.csat.headers.contact_phone_number'),
I18n.t('reports.csat.headers.link_to_the_conversation'),
I18n.t('reports.csat.headers.recorded_at')
])
]
headers << I18n.t('reports.csat.headers.review_notes') if ChatwootApp.enterprise?
-%>
<%= CSV.generate_line(headers) -%>
<% @csat_survey_responses.each do |csat_response| %>
<% assigned_agent = csat_response.assigned_agent %>
<% contact = csat_response.contact %>
<% conversation = csat_response.conversation %>
<%=
CSV.generate_line([
<%
row = [
assigned_agent ? "#{assigned_agent.name} (#{assigned_agent.email})" : nil,
csat_response.rating,
csat_response.feedback_message.present? ? csat_response.feedback_message : nil,
contact&.name.present? ? contact&.name: nil,
contact&.email.present? ? contact&.email: nil,
contact&.phone_number.present? ? contact&.phone_number: nil,
conversation ? app_account_conversation_url(account_id: Current.account.id, id: conversation.display_id): nil,
csat_response.created_at,
]).html_safe
csat_response.feedback_message.presence,
contact&.name.presence,
contact&.email.presence,
contact&.phone_number.presence,
conversation ? app_account_conversation_url(account_id: Current.account.id, id: conversation.display_id) : nil,
csat_response.created_at
]
row << csat_response.csat_review_notes if ChatwootApp.enterprise?
-%>
<%= CSV.generate_line(row).html_safe -%>
<% end %>
<%=
CSV.generate_line([
@@ -0,0 +1 @@
json.partial! 'api/v1/models/csat_survey_response', formats: [:json], resource: @csat_survey_response
@@ -1,6 +1,14 @@
json.id resource.id
json.rating resource.rating
json.feedback_message resource.feedback_message
json.csat_review_notes resource.csat_review_notes
json.review_notes_updated_at resource.review_notes_updated_at&.to_i
if resource.review_notes_updated_by
json.review_notes_updated_by do
json.id resource.review_notes_updated_by.id
json.name resource.review_notes_updated_by.name
end
end
json.account_id resource.account_id
json.message_id resource.message_id
if resource.contact
@@ -0,0 +1,16 @@
<%= CSVSafe.generate_line [I18n.t('reports.period', since: Date.strptime(params[:since], '%s'), until: Date.strptime(params[:until], '%s'))] %>
<% headers = [
I18n.t('reports.conversation_csv.conversations_count'),
I18n.t('reports.conversation_csv.incoming_messages_count'),
I18n.t('reports.conversation_csv.outgoing_messages_count'),
I18n.t('reports.conversation_csv.avg_first_response_time'),
I18n.t('reports.conversation_csv.avg_resolution_time'),
I18n.t('reports.conversation_csv.resolution_count'),
I18n.t('reports.conversation_csv.avg_customer_waiting_time')
]
%>
<%= CSVSafe.generate_line headers -%>
<% @report_data.each do |row| %>
<%= CSVSafe.generate_line row -%>
<% end %>
+1 -1
View File
@@ -1,5 +1,5 @@
shared: &shared
version: '4.9.1'
version: '4.10.0'
development:
<<: *shared
+4
View File
@@ -230,3 +230,7 @@
- name: channel_tiktok
display_name: TikTok Channel
enabled: true
- name: csat_review_notes
display_name: CSAT Review Notes
enabled: false
premium: true
+11
View File
@@ -134,6 +134,8 @@ en:
plan_not_eligible: Top-ups are only available for paid plans. Please upgrade your plan first.
stripe_customer_not_configured: Stripe customer not configured
no_payment_method: No payment methods found. Please add a payment method before making a purchase.
reports:
date_range_too_long: Date range cannot exceed 6 months
profile:
mfa:
enabled: MFA enabled successfully
@@ -170,6 +172,14 @@ en:
avg_resolution_time: Avg resolution time
resolution_count: Resolution Count
avg_customer_waiting_time: Avg customer waiting time
conversation_csv:
conversations_count: Conversations
incoming_messages_count: Messages received
outgoing_messages_count: Messages sent
avg_first_response_time: Avg first response time
avg_resolution_time: Avg resolution time
resolution_count: Resolution count
avg_customer_waiting_time: Avg customer waiting time
conversation_traffic_csv:
timezone: Timezone
sla_csv:
@@ -192,6 +202,7 @@ en:
rating: Rating
feedback: Feedback Comment
recorded_at: Recorded date
review_notes: Review Notes
notifications:
notification_title:
conversation_creation: 'A conversation (#%{display_id}) has been created in %{inbox_name}'
+5
View File
@@ -189,6 +189,9 @@ Rails.application.routes.draw do
get :metrics
get :download
end
member do
patch :update if ChatwootApp.enterprise?
end
end
resources :applied_slas, only: [:index] do
collection do
@@ -418,6 +421,7 @@ Rails.application.routes.draw do
get :team
get :inbox
get :label
get :channel
end
end
resources :reports, only: [:index] do
@@ -429,6 +433,7 @@ Rails.application.routes.draw do
get :labels
get :teams
get :conversations
get :conversations_summary
get :conversation_traffic
get :bot_metrics
end
@@ -0,0 +1,32 @@
class RemoveCountryCodeFromConversationFilters < ActiveRecord::Migration[7.1]
def up
CustomFilter.conversation
.where('query::text LIKE ?', '%country_code%')
.find_each do |custom_filter|
query = custom_filter.query || {}
payload = query['payload']
next unless payload.is_a?(Array)
updated_payload = payload.reject do |filter|
filter.is_a?(Hash) && filter['attribute_key'] == 'country_code'
end
next if updated_payload == payload
if updated_payload.empty?
custom_filter.delete
next
end
# rubocop:disable Rails/SkipsModelValidations
# we will skip model validation, since we don't want any callbacks running
custom_filter.update_columns(query: query.merge('payload' => updated_payload))
# rubocop:enable Rails/SkipsModelValidations
end
end
def down
# no-op: removed filters cannot be restored reliably
end
end
@@ -0,0 +1,5 @@
class AddInternalObservationsToCsatSurveyResponses < ActiveRecord::Migration[7.1]
def change
add_column :csat_survey_responses, :csat_review_notes, :text
end
end
@@ -0,0 +1,6 @@
class AddObservationsAuditToCsatSurveyResponses < ActiveRecord::Migration[7.1]
def change
add_column :csat_survey_responses, :review_notes_updated_at, :datetime
add_reference :csat_survey_responses, :review_notes_updated_by, index: true
end
end
+5 -1
View File
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[7.1].define(version: 2025_12_29_081141) do
ActiveRecord::Schema[7.1].define(version: 2026_01_14_201315) do
# These extensions should be enabled to support this database
enable_extension "pg_stat_statements"
enable_extension "pg_trgm"
@@ -733,11 +733,15 @@ ActiveRecord::Schema[7.1].define(version: 2025_12_29_081141) do
t.bigint "assigned_agent_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "csat_review_notes"
t.datetime "review_notes_updated_at"
t.bigint "review_notes_updated_by_id"
t.index ["account_id"], name: "index_csat_survey_responses_on_account_id"
t.index ["assigned_agent_id"], name: "index_csat_survey_responses_on_assigned_agent_id"
t.index ["contact_id"], name: "index_csat_survey_responses_on_contact_id"
t.index ["conversation_id"], name: "index_csat_survey_responses_on_conversation_id"
t.index ["message_id"], name: "index_csat_survey_responses_on_message_id", unique: true
t.index ["review_notes_updated_by_id"], name: "index_csat_survey_responses_on_review_notes_updated_by_id"
end
create_table "custom_attribute_definitions", force: :cascade do |t|
+6 -6
View File
@@ -2,7 +2,7 @@
FROM node:24-alpine as node
FROM ruby:3.4.4-alpine3.21 AS pre-builder
ARG NODE_VERSION="24.12.0"
ARG NODE_VERSION="24.13.0"
ARG PNPM_VERSION="10.2.0"
ENV NODE_VERSION=${NODE_VERSION}
ENV PNPM_VERSION=${PNPM_VERSION}
@@ -11,7 +11,7 @@ ENV PNPM_VERSION=${PNPM_VERSION}
# For development docker-compose file overrides ARGS
ARG BUNDLE_WITHOUT="development:test"
ENV BUNDLE_WITHOUT ${BUNDLE_WITHOUT}
ENV BUNDLER_VERSION=2.5.11
ENV BUNDLER_VERSION=2.5.16
ARG RAILS_SERVE_STATIC_FILES=true
ENV RAILS_SERVE_STATIC_FILES ${RAILS_SERVE_STATIC_FILES}
@@ -35,7 +35,7 @@ RUN apk update && apk add --no-cache \
curl \
xz \
&& mkdir -p /var/app \
&& gem install bundler
&& gem install bundler -v "$BUNDLER_VERSION"
COPY --from=node /usr/local/bin/node /usr/local/bin/
COPY --from=node /usr/local/lib/node_modules /usr/local/lib/node_modules
@@ -98,14 +98,14 @@ RUN rm -rf /gems/ruby/3.4.0/cache/*.gem \
# final build stage
FROM ruby:3.4.4-alpine3.21
ARG NODE_VERSION="24.12.0"
ARG NODE_VERSION="24.13.0"
ARG PNPM_VERSION="10.2.0"
ENV NODE_VERSION=${NODE_VERSION}
ENV PNPM_VERSION=${PNPM_VERSION}
ARG BUNDLE_WITHOUT="development:test"
ENV BUNDLE_WITHOUT ${BUNDLE_WITHOUT}
ENV BUNDLER_VERSION=2.5.11
ENV BUNDLER_VERSION=2.5.16
ARG EXECJS_RUNTIME="Disabled"
ENV EXECJS_RUNTIME ${EXECJS_RUNTIME}
@@ -128,7 +128,7 @@ RUN apk update && apk add --no-cache \
imagemagick \
git \
vips \
&& gem install bundler
&& gem install bundler -v "$BUNDLER_VERSION"
COPY --from=node /usr/local/bin/node /usr/local/bin/
COPY --from=node /usr/local/lib/node_modules /usr/local/lib/node_modules
@@ -0,0 +1,12 @@
module Enterprise::Api::V1::Accounts::CsatSurveyResponsesController
def update
@csat_survey_response = Current.account.csat_survey_responses.find(params[:id])
authorize @csat_survey_response
@csat_survey_response.update!(
csat_review_notes: params[:csat_review_notes],
review_notes_updated_by: Current.user,
review_notes_updated_at: Time.current
)
end
end
@@ -0,0 +1,47 @@
module Captain::ChatGenerationRecorder
extend ActiveSupport::Concern
include Integrations::LlmInstrumentationConstants
private
def record_llm_generation(chat, message)
return unless valid_llm_message?(message)
# Create a generation span with model and token info for Langfuse cost calculation.
# Note: span duration will be near-zero since we create and end it immediately, but token counts are what Langfuse uses for cost calculation.
tracer.in_span("llm.captain.#{feature_name}.generation") do |span|
set_generation_span_attributes(span, chat, message)
end
rescue StandardError => e
Rails.logger.warn "Failed to record LLM generation: #{e.message}"
end
# Skip non-LLM messages (e.g., tool results that RubyLLM processes internally).
# Check for assistant role rather than token presence - some providers/streaming modes
# may not return token counts, but we still want to capture the generation for evals.
def valid_llm_message?(message)
message.respond_to?(:role) && message.role.to_s == 'assistant'
end
def set_generation_span_attributes(span, chat, message)
generation_attributes(chat, message).each do |key, value|
span.set_attribute(key, value) if value
end
end
def generation_attributes(chat, message)
{
ATTR_GEN_AI_PROVIDER => determine_provider(model),
ATTR_GEN_AI_REQUEST_MODEL => model,
ATTR_GEN_AI_REQUEST_TEMPERATURE => temperature,
ATTR_GEN_AI_USAGE_INPUT_TOKENS => message.input_tokens,
ATTR_GEN_AI_USAGE_OUTPUT_TOKENS => message.respond_to?(:output_tokens) ? message.output_tokens : nil,
ATTR_LANGFUSE_OBSERVATION_INPUT => format_input_messages(chat),
ATTR_LANGFUSE_OBSERVATION_OUTPUT => message.respond_to?(:content) ? message.content.to_s : nil
}
end
def format_input_messages(chat)
chat.messages[0...-1].map { |m| { role: m.role.to_s, content: m.content.to_s } }.to_json
end
end
@@ -1,6 +1,7 @@
module Captain::ChatHelper
include Integrations::LlmInstrumentation
include Captain::ChatResponseHelper
include Captain::ChatGenerationRecorder
def request_chat_completion
log_chat_completion_request
@@ -42,8 +43,11 @@ module Captain::ChatHelper
end
def setup_event_handlers(chat)
chat.on_new_message { start_llm_turn_span(instrumentation_params(chat)) }
chat.on_end_message { |message| end_llm_turn_span(message) }
# NOTE: We only use on_end_message to record the generation with token counts.
# RubyLLM callbacks fire after chunks arrive, not around the API call, so
# span timing won't reflect actual API latency. But Langfuse calculates costs
# from model + token counts, so this is sufficient for cost tracking.
chat.on_end_message { |message| record_llm_generation(chat, message) }
chat.on_tool_call { |tool_call| handle_tool_call(tool_call) }
chat.on_tool_result { |result| handle_tool_result(result) }
@@ -10,4 +10,8 @@ module Enterprise::CsatSurveyResponsePolicy
def download?
@account_user.custom_role&.permissions&.include?('report_manage') || super
end
def update?
@account_user.administrator? || @account_user.custom_role&.permissions&.include?('report_manage')
end
end
@@ -22,7 +22,7 @@ class Enterprise::Billing::HandleStripeEventService
].freeze
# Additional features available starting with the Business plan
BUSINESS_PLAN_FEATURES = %w[sla custom_roles].freeze
BUSINESS_PLAN_FEATURES = %w[sla custom_roles csat_review_notes].freeze
# Additional features available only in the Enterprise plan
ENTERPRISE_PLAN_FEATURES = %w[audit_logs disable_branding saml].freeze

Some files were not shown because too many files have changed in this diff Show More