Compare commits

...
Author SHA1 Message Date
Shivam Mishra 37700eed5e feat: update pnpm 2025-02-04 09:20:34 +05:30
Sivin VargheseandGitHub c18452f6b6 chore: Use getFileInfo helper from utils (#10819)
# Pull Request Template

## Description
The PR includes the usage of `getFileInfo` helper from utils
https://github.com/chatwoot/utils/pull/40.

Fixes
https://github.com/chatwoot/chatwoot/pull/10806#discussion_r1937797905

## How Has This Been Tested?

**Screenshot**
<img width="490" alt="image"
src="https://github.com/user-attachments/assets/f0788e89-b670-47da-b0ca-3765eb424be0"
/>



## 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
- [ ] 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
2025-02-03 14:13:01 +05:30
EvansandGitHub c403f6872c docs: Update copyright year to 2025 (#10817)
Update copyright year to 2025

# Pull Request Template

## Description

This PR updates the copyright year in the README

## Type of change

Please delete options that are not relevant.

## How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Provide
instructions so we can reproduce. Please also list any relevant details
for your test configuration.


## 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
- [x] I have made corresponding changes to the documentation
- [x] 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
2025-02-01 19:44:57 +05:30
Sivin VargheseandGitHub 70919d184d fix: Update min-length validation for the contact to support names with single characters (#10813)
This PR updates the contact form validation to allow a minimum length of one character for the first name.

Fixes
https://linear.app/chatwoot/issue/CW-3993/update-the-validation-on-contact-form-to-support-just-one-character

## Type of change

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

## How Has This Been Tested?



https://github.com/user-attachments/assets/2b95af80-ee70-4f4b-8d0d-b01779db9d94




## 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
- [ ] 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
2025-01-31 14:39:32 -08:00
Sivin VargheseandGitHub 24257f9771 chore: Always display the extension of an attached file (#10806) 2025-01-31 18:28:28 +05:30
Sivin VargheseandGitHub c3aab44b5f feat: Add unread badge to sidebar for inbox view (#10803)
# Pull Request Template

## Description

This PR adds a badge to the icon in the sidebar group header and an
unread highlight for the inbox view.

## Type of change

- [x] New feature (non-breaking change which adds functionality)

## How Has This Been Tested?

**Loom video**

https://www.loom.com/share/1a880aa16de249a1836b8d014325c067?sid=87cc7b64-667b-4066-8993-d33abccf7b67


## 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
- [ ] 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
2025-01-31 15:14:10 +05:30
Shivam MishraandGitHub b811c27ab5 feat: Hide empty folders from sidebar (#10786)
This PR updates the sidebar to hide empty folders. So, in case the user
has not created any folders, or teams, the section in the sidebar will
be hidden
2025-01-30 17:03:12 -08:00
Vishnu NarayananandGitHub 55f1690d9e fix: docker github action for ce images (#10800)
- Fix the docker tag issue during push stage for ce image build
2025-01-30 15:52:01 +05:30
Sivin VargheseandGitHub 2c75ccb004 feat: Ability to rearrange attributes in sidebar (#10784) 2025-01-30 15:24:02 +05:30
Shivam MishraandGitHub d997734837 revert: Next bubble improvements (#10795) 2025-01-29 20:04:45 -08:00
Sivin VargheseandGitHub 2c1a8e59f5 chore: Next bubble improvements (#10759) 2025-01-29 22:56:08 +05:30
Vishnu NarayananandGitHub f6d87d0e6e feat: switch to native arm64 runners for docker ce images (#10789)
Emulated docker arm64 builds are failing for community images. This PR

- Switches gh action to use native arm64 runners
- Merges amd64 and arm64 images to create a multi-arch docker image

Fixes https://github.com/chatwoot/chatwoot/issues/10790
2025-01-29 22:53:29 +05:30
Vishnu NarayananandGitHub 56874c442c feat: add OOMPolicy for sidekiq systemd service (#10772)
- Add OOM policy for `sidekiq` `systemd` service
- This ensures `sidekiq` does not consume all the memory available in
the system
2025-01-29 17:27:58 +05:30
eb908d9c03 fix: Download file CORS issue (#10787)
# Pull Request Template

## Description
Ref: https://github.com/chatwoot/utils/pull/39

---------

Co-authored-by: Shivam Mishra <scm.mymail@gmail.com>
2025-01-29 15:32:13 +05:30
Shivam MishraandGitHub 5ccae73f8a fix: Update captain billing colors (#10782) 2025-01-28 13:50:50 -08:00
Sivin VargheseandGitHub 80e6a2a479 chore: Disable audio alert for pending status conversation (#10777)
# Pull Request Template

## Description

This PR disables audio alerts for conversations with a status of
"pending." It applies to all notification event types, ensuring that
audio will not play for conversations marked as "pending."

Fixes
https://linear.app/chatwoot/issue/CW-3951/audio-alerts-shouldnt-be-triggered-in-conversation-is-in-pending-state

## Type of change

- [x] Breaking change (fix or feature that would cause existing
functionality not to work as expected)

## How Has This Been Tested?

Steps:
1. Create a conversation.
2. Then mark the conversation as pending.
3. Send message.
4. Make sure audio notification are enabled.


## 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
2025-01-28 18:49:12 +05:30
PranavandGitHub cf0975ad94 fix: Use current_available instead available to compute the document limit (#10776)
The available limit for documents is now stored in
captain.documents.current_available. This PR fixes the limit sent on
crawler job.
2025-01-28 10:55:46 +05:30
cb42be8e65 feat(v4): Update the report pages to show aggregate values (#10766)
This PR updates the report pages for agents, inboxes, and teams by
replacing charts with aggregate values (under a feature flag). Users can
click on any item to view more details if needed. Most users seem to
prefer aggregate values, so this change will likely stay.

The PR also includes a few fixes:

- The summary reports now use the same logic for both the front-end and
CSV exports.
- Fixed an issue where a single quote was being added to values with
hyphens in CSV files. Now, ‘n/a’ is used when no value is available.
- Fixed a bug where the average value was calculated incorrectly when
multiple accounts were present.

These changes should make reports easier to use and more consistent.

### Agents:

<img width="1438" alt="Screenshot 2025-01-26 at 10 47 18 AM"
src="https://github.com/user-attachments/assets/bf2fcebc-6207-4701-9703-5c2110b7b8a0"
/>

### Inboxes
<img width="1438" alt="Screenshot 2025-01-26 at 10 47 10 AM"
src="https://github.com/user-attachments/assets/b83e1cf2-fd14-4e8e-8dcd-9033404a9f22"
/>


### Teams: 
<img width="1436" alt="Screenshot 2025-01-26 at 10 47 01 AM"
src="https://github.com/user-attachments/assets/96b1ce07-f557-42ca-8143-546a111d6458"
/>

---------

Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com>
Co-authored-by: Shivam Mishra <scm.mymail@gmail.com>
2025-01-28 09:19:18 +05:30
Sivin VargheseandGitHub 9cee8a1713 fix: CORS issue with file download (#10755)
# Pull Request Template

## Description
https://github.com/chatwoot/utils/pull/38

## Type of change

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

## How Has This Been Tested?

## 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
- [ ] 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
2025-01-27 14:33:12 +05:30
Sivin VargheseandGitHub d925729444 chore: Disable account switcher for single-account users (#10768) 2025-01-27 13:19:48 +05:30
ef7bf66476 feat: Add frontend changes for Captain limits (#10749)
This PR introduces several improvements to the Captain AI dashboard
section:

- New billing page, with new colors, layout and meters for Captain usage
- Updated the base paywall component to use new colors
- Updated PageLayout.vue, it's more generic and can be used for other
pages as well
   - Use flags to toggle empty state and loading state
- Add prop for `featureFlag` to show the paywall slot based on feature
enabled on account
- Update `useAccount` to add a `isCloudFeatureEnabled`
- **Removed feature flag checks from captain route definitions**, so the
captain entry will always be visible on the sidebar
- Add banner to Captain pages for the following cases
   - Responses usage is over 80%
   - Documents limit is fully exhausted


### Screenshots

<details><summary>Free plan</summary>
<p>

![CleanShot 2025-01-22 at 18 37
11@2x](https://github.com/user-attachments/assets/17d3ddba-9095-4e81-9b6f-45b5f69e6a3f)
![CleanShot 2025-01-22 at 18 37
04@2x](https://github.com/user-attachments/assets/df9bb0a6-085f-45da-97d4-74cbcc33fc7e)


</p>
</details> 

<details><summary>Paid plan</summary>
<p>

![CleanShot 2025-01-22 at 18 36
45@2x](https://github.com/user-attachments/assets/a7ccf9d4-143b-49e4-8149-83c7a7985023)

![CleanShot 2025-01-22 at 20 23
57@2x](https://github.com/user-attachments/assets/c6ce35ba-e537-486d-85c8-4cc2d4e76438)


</p>
</details>

---------

Co-authored-by: Sojan Jose <sojan@pepalo.com>
Co-authored-by: Pranav <pranav@chatwoot.com>
Co-authored-by: Muhsin Keloth <muhsinkeramam@gmail.com>
2025-01-24 09:21:09 -08:00
Sivin VargheseandGitHub b429ce0ad5 fix: Prevent template variables from becoming links (#10725)
# Pull Request Template

## Description

**Issue**
This PR fixes template variables in messages (e.g., {{customer.name}})
that were being incorrectly converted to clickable links by the
`MessageFormatter's linkify` functionality. This caused formatting
issues and broken links.

**Solution**
Added a `linkify` parameter to `MessageFormatter` to optionally disable
link conversion

## Type of change

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

## How Has This Been Tested?

**Screenshots**

**Before**
<img width="1012" alt="image"
src="https://github.com/user-attachments/assets/70abb238-b4d9-439d-9e51-c7513cf482fb"
/>


**After**
<img width="1012" alt="image"
src="https://github.com/user-attachments/assets/387acb74-674e-4b26-85cc-2d7190d256b1"
/>




## 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
2025-01-23 18:18:14 +05:30
Sivin VargheseandGitHub d3d39a81d6 fix: Prevent duplicate chat creation in the web widget during latency (#10745) 2025-01-23 12:53:28 +05:30
be8205657e fix: Added authentication to FireCrawl API, remove unused RobinAI references (#10737)
- Fixed Firecrawl webhook payloads to ensure proper data handling and
delivery.
- Removed unused Robin AI code to improve codebase cleanliness and
maintainability.
- Implement authentication for the Firecrawl endpoint to improve
security. A key is generated to secure the webhook URLs from FireCrawl.

---------

Co-authored-by: Pranav <pranavrajs@gmail.com>
2025-01-22 18:14:25 -08:00
Shivam MishraandGitHub 3b366f43e6 feat: setup captain limits (#10713)
This pull request introduces several changes to implement and manage
usage limits for the Captain AI service. The key changes include adding
configuration for plan limits, updating error messages, modifying
controllers and models to handle usage limits, and updating tests to
ensure the new functionality works correctly.

## Implementation Checklist

- [x] Ability to configure captain limits per check
- [x] Update response for `usage_limits` to include captain limits
- [x] Methods to increment or reset captain responses limits in the
`limits` column for the `Account` model
- [x] Check documents limit using a count query
- [x] Ensure Captain hand-off if a limit is reached
- [x] Ensure limits are enforced for Copilot Chat
- [x] Ensure limits are reset when stripe webhook comes in 
- [x] Increment usage for FAQ generation and Contact notes
- [x] Ensure documents limit is enforced

These changes ensure that the Captain AI service operates within the defined usage limits for different subscription plans, providing appropriate error messages and handling when limits are exceeded.
2025-01-23 01:23:18 +05:30
David KubešandGitHub 52362ec1ea fix: country selection (#10670) 2025-01-22 21:30:51 +05:30
Sivin VargheseandGitHub 38e46bbb6c chore: Adds loader for attachment download buttons (#10748) 2025-01-22 18:29:57 +05:30
Sivin VargheseandGitHub 137c6f8a75 fix: Context menu and its submenu boundary overflow (#10729)
# Pull Request Template

## Description

This PR adds smart positioning to prevent context menu and submenu from
overflowing screen boundaries. The context menu and its submenu now
dynamically adjust their position when there isn't enough space.


Fixes
https://linear.app/chatwoot/issue/CW-3936/assign-to-agent-ui-element-is-drawn-off-canvas
https://github.com/chatwoot/chatwoot/issues/10727

## 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/6c267dde103c4f2281ed5b4d006a43b1?sid=047966f5-d6d3-4de6-ade8-270141e6e215

**After**

https://www.loom.com/share/5599c6061bb74c3ea527dd06960d3189?sid=ffb01149-bb7a-449e-b0ec-02cc191f472b


## 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
- [ ] 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
2025-01-22 17:56:43 +05:30
PranavandGitHub 3a950dbdbb fix: Use documentable instead of document (#10743)
Fixes
https://linear.app/chatwoot/issue/CW-3950/nomethoderror-undefined-method-document-for-an-instance-of
2025-01-21 19:43:20 -08:00
451c28a7a1 feat: add prompt suggestions and June events (#10726)
This PR adds the following two features

1. Prompt suggestions to get started with Copilot Chat
2. June events for each action

![CleanShot 2025-01-20 at 21 00
52@2x](https://github.com/user-attachments/assets/d73e7982-0f78-4d85-873e-da2c16762688)

---------

Co-authored-by: Pranav <pranavrajs@gmail.com>
2025-01-21 22:52:42 +05:30
Sivin VargheseandGitHub 0021a7d8e5 chore: Design improvements (#10732) 2025-01-21 17:03:15 +05:30
615a0c69fe chore: Help center improvements (#10712)
# Pull Request Template

## Description

Fixes https://linear.app/chatwoot/issue/CW-3913/issues-with-help-center

**Fixes included**
1. > The default locale that is selected should the portal default
locale.

Now, we update the last active locale in UI settings after changing the
selected locale from the article page header. This ensures that we see
the last active locale-based categories on the category page and
remember it when we return. Initially, it’s the default locale.
     
2. > I cannot switch to a different locale if there are no articles in
the portal

Now, the `v-if` condition that checked for the presence of articles in
portal has been removed. Additionally, the locale length checks for the
showing dropdown have been removed, allows locale switching even if
article is not preset.
     
3. > Create or updating the article is quite painful, see the video 

Removed the `quickSave` and `saveAndSyncDebounced` usage for a newly
creating article.

4. > I cannot see the articles if I delete the English locale
(irrespective of what I choose as default locale)

Now, the last active locale in UI settings will automatically update to
the default locale when the last active locale is deleted.

5. > Set a new default locale other than `en` and delete the `en` locale
preset in the portal. Then, adding a new locale will automatically set
`en` as the default locale, even if the `en` locale not preset in the
portal.

    Now, we pass default locale when we add a new locale.

6. Adds search for all dropdown menus
7. Update article count in realtime.


## Type of change

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

## How Has This Been Tested?

**Check this linear issues**
https://linear.app/chatwoot/issue/CW-3913/issues-with-help-center


## 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
- [ ] 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: Pranav <pranav@chatwoot.com>
2025-01-21 13:50:01 +05:30
PranavandGitHub 1528473dd0 fix(ce): Check the edition before running the data migration (#10728)
Fixes #10721

This PR addresses an issue where the data migration in the CE edition
was failing due to missing models. The change ensures that the migration
process runs only when the deployment is using the EE image.
2025-01-21 10:00:37 +05:30
Sivin VargheseandGitHub 05c16b49dd fix: Vite dev build fails due to sass (#10716)
# Pull Request Template

## Description

Fixes
https://linear.app/chatwoot/issue/CW-3853/vite-dev-build-fails-due-to-dart-sass

**Other issue**

| First Header  | Second Header |
| ------------- | ------------- |
|
![image](https://github.com/user-attachments/assets/e99ac2bc-0b8a-44d1-aa58-9e10e00b5ad5)
|
![image](https://github.com/user-attachments/assets/c987f70c-f5f5-4606-a498-00a6fe6b6525)
|



## Type of change

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


## 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
- [ ] 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
2025-01-20 14:34:33 +05:30
Sivin VargheseandGitHub a8ecbd3919 chore: Auto-fetch previous page on last item deletion (#10714)
# Pull Request Template

## Description

This PR fixes an issue where deleting the last item on the last page of
responses/documents, would show an empty state instead of loading the
previous page.

Fixes
> If you have pending responses spanning 2 or more pages .. and you
delete the last response in the last page.. instead of showing the
previous page the system show empty state.

## Type of change

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

## How Has This Been Tested?

**Loom video**

https://www.loom.com/share/b0e89f774ccd45dab0e8dba2c34bd1ac?sid=d9923bcd-5030-42d9-9b7f-170df5297cfd


## 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
- [ ] 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
2025-01-20 14:34:23 +05:30
Shivam MishraandGitHub c25a75f497 feat: check if item is present (#10715) 2025-01-18 18:31:07 +05:30
5046dc5727 feat: add CSAT & Form bubble (#10711)
![CleanShot 2025-01-17 at 14 02
40@2x](https://github.com/user-attachments/assets/7a19c4d7-7548-4b6a-92bb-0ddba181c428)

![CleanShot 2025-01-17 at 14 39
50@2x](https://github.com/user-attachments/assets/4251c944-2d1f-4cb5-817a-6352a644b743)

---------

Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com>
2025-01-17 15:30:52 +05:30
Sivin VargheseandGitHub 3da97d97be fix: Download button opens URL instead of downloading (#10710) 2025-01-17 14:34:44 +05:30
Sojan f2ff3b42e3 Merge branch 'release/4.0.1' into develop 2025-01-17 01:13:32 +05:30
Sojan 9dc493c7d4 Bump version to 4.0.1 2025-01-17 01:11:35 +05:30
Shivam MishraandGitHub 2f60301064 fix: bubble colors for email and text (#10701) 2025-01-17 00:57:22 +05:30
PranavandGitHub c20cb9535b fix: Remove backdrop-blur from Modal (#10709)
Remove backdrop-blur-[100px] from Modal as it was causing issues with
old design pages.
2025-01-17 00:50:34 +05:30
Sojan JoseandGitHub 257f59e219 chore: Update SECURITY.md (#10705)
Move vulnerability reporting to Github.
2025-01-16 10:59:33 -08:00
PranavandGitHub c0ad0b4cc1 fix: Re-enable scheduled jobs (#10708)
During Captain, scheduled jobs were disabled. This PR would re-enable them
2025-01-16 10:59:09 -08:00
Shivam MishraandGitHub 937d4f78a8 fix: rendering for woot modal (#10707) 2025-01-16 20:05:53 +05:30
Sojan a33f170171 Merge branch 'release/4.0.0' into develop 2025-01-16 17:11:51 +05:30
Sojan 789f281273 Bump version to 4.0.0 2025-01-16 17:10:55 +05:30
1ccfb4e3db fix: sentry issues (#10695)
1. Ensure audio player ref is accessible before triggering calls
([Sentry](https://chatwoot-p3.sentry.io/issues/6221981610))
2. Use correct default for attachments, this was incorrectly set to
`null` in a previous PR
([Sentry](https://chatwoot-p3.sentry.io/issues/5966738120))
3. Fix `lastNonActivityMessage` is not present
([Sentry](https://chatwoot-p3.sentry.io/issues/6116038455))
4. Fix `Alt+J` & `Alt+K` shortcuts not working
([Sentry](https://chatwoot-p3.sentry.io/issues/6075125384))

---------

Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com>
2025-01-16 15:49:48 +05:30
79997fd86f feat: use break anywhere (#10698)
Ref:
https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-wrap#anywhere

Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com>
2025-01-16 15:49:39 +05:30
0b4028b95d feat: Add support for the references in FAQs (#10699)
Currently, it’s unclear whether an FAQ item is generated from a
document, derived from a conversation, or added manually.

This PR resolves the issue by providing visibility into the source of
each FAQ. Users can now see whether an FAQ was generated or manually
added and, if applicable, by whom.

- Move the document_id to a polymorphic relation (documentable).
- Updated the APIs to accommodate the change.
- Update the service to add corresponding references. 
- Updated the specs.

<img width="1007" alt="Screenshot 2025-01-15 at 11 27 56 PM"
src="https://github.com/user-attachments/assets/7d58f798-19c0-4407-b3e2-748a919d14af"
/>

---------

Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com>
2025-01-16 15:27:30 +05:30
Sivin VargheseandGitHub 88f3b4de48 chore(v4): Update colors (#10700) 2025-01-16 15:27:23 +05:30
Sivin VargheseandGitHub 542bab617b feat: Implement Empty State UI for Captain Pages (#10696) 2025-01-16 00:05:19 -08:00
PranavandGitHub 793b1f85f6 feat: Add assistant filter support to documents page (#10697)
This PR introduces support for an assistant filter on the documents page.

- Moved the existing assistant filter functionality to a standalone, reusable component.
- Updated the documents page and responses page to use the component
2025-01-15 21:41:07 -08:00
Shivam MishraandGitHub 54d629d171 fix: Update words not breaking in reply-to preview (#10694) 2025-01-15 21:16:39 -08:00
PranavandGitHub 6096932f76 feat: Add a review step for FAQs generated from conversations before using it (#10693)
This PR introduces a review step for generated FAQs, allowing a human to
validate and approve them before use in customer interactions. While
hallucinations are minimal, this step ensures accurate and reliable FAQs
for Captain to use during LLM calls when responding to customers.

- Added a status field for the FAQ
- Allow the filter on the UI.
<img width="1072" alt="Screenshot 2025-01-15 at 6 39 26 PM"
src="https://github.com/user-attachments/assets/81dfc038-31e9-40e6-8a09-586ebc4e8384"
/>
2025-01-16 09:54:34 +05:30
e3b5b30666 fix: Remove overflow-hidden on accordionItem (#10692)
This PR fixes the following problem. 

<img width="318" alt="Screenshot 2025-01-15 at 11 53 38 AM"
src="https://github.com/user-attachments/assets/44656cbe-2c29-4400-88b4-15bd270bb627"
/>

Co-authored-by: Sojan Jose <sojan@pepalo.com>
2025-01-16 01:29:20 +05:30
PranavandGitHub 7469cde0b9 fix: Remove Report API calls from being called on every event (#10691)
Previously, the Reports API fetched data based on event triggers. For
example, when an event occurred on an account, the system would
automatically retrieve and display updated information. However, this
approach was designed under the assumption that reports would be
accessed by a small number of users and on an infrequent basis (e.g.,
once daily or weekly).

In scenarios where large customers have multiple team members actively
monitoring reports, this event-driven approach led to an excessive
number of requests, significantly straining the system.

This PR introduces a interval-based fetching of reports instead of the
event-driven model.
2025-01-15 11:23:00 -08:00
Shivam MishraandGitHub da488b0c32 fix: ignore subgroups without link when checking for permission (#10690) 2025-01-15 18:16:10 +05:30
7fd8b4d03a feat: update colors for v4 (#10660)
Porting changes from https://github.com/chatwoot/chatwoot/pull/10552

---------

Co-authored-by: Pranav <pranav@chatwoot.com>
Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com>
Co-authored-by: Vishnu Narayanan <vishnu@chatwoot.com>
Co-authored-by: Sojan <sojan@pepalo.com>
Co-authored-by: iamsivin <iamsivin@gmail.com>
Co-authored-by: Pranav <pranavrajs@gmail.com>
2025-01-15 17:13:03 +05:30
Vishnu NarayananandGitHub a4c0c76fa5 fix: set cwctl pg version to 16 (#10689)
# Pull Request Template

## Description

Multiple versions of postgres were getting installed, conflicting with
the `pgvector` extension being installed. This PR sets the version to
`16` for all postgres dependencies ensuring a single version is
installed.

## Type of change

Please delete options that are not relevant.

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

## How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Provide
instructions so we can reproduce. Please also list any relevant details
for your test configuration.


## 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
2025-01-15 16:31:49 +05:30
Sivin VargheseandGitHub a899c2b5a4 chore: Improve new conversation form (#10687) 2025-01-15 13:10:09 +05:30
d070743383 feat(ee): Add Captain features (#10665)
Migration Guide: https://chwt.app/v4/migration

This PR imports all the work related to Captain into the EE codebase. Captain represents the AI-based features in Chatwoot and includes the following key components:

- Assistant: An assistant has a persona, the product it would be trained on. At the moment, the data at which it is trained is from websites. Future integrations on Notion documents, PDF etc. This PR enables connecting an assistant to an inbox. The assistant would run the conversation every time before transferring it to an agent.
- Copilot for Agents: When an agent is supporting a customer, we will be able to offer additional help to lookup some data or fetch information from integrations etc via copilot.
- Conversation FAQ generator: When a conversation is resolved, the Captain integration would identify questions which were not in the knowledge base.
- CRM memory: Learns from the conversations and identifies important information about the contact.

---------

Co-authored-by: Vishnu Narayanan <vishnu@chatwoot.com>
Co-authored-by: Sojan <sojan@pepalo.com>
Co-authored-by: iamsivin <iamsivin@gmail.com>
Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com>
2025-01-14 16:15:47 -08:00
7b31b5ad6e fix: Fix bubble design in RTL (#10683)
Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com>
2025-01-14 11:14:13 -08:00
Sivin VargheseandGitHub b3d0d466ee fix: Inbox view list lacks a border in RTL view. (#10684) 2025-01-14 11:13:16 -08:00
0c01303db0 chore: Update translations (#10549)
Co-authored-by: Shivam Mishra <scm.mymail@gmail.com>
Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com>
2025-01-14 22:00:56 +05:30
Vishnu NarayananandGitHub 91dd92e318 feat: switch to postgres docker images with pgvector support (v4.0) (#10658)
Starting v4.0, pgvector support is mandatory. This PR adds pgvector
support for new docker installations.

- Switch to postgres images with pgvector support
- Change the default postgres version from `12` to `16`
2025-01-14 19:45:42 +05:30
Vishnu NarayananandGitHub 03a938eb60 feat: cwctl install pgvector for new deployments (v4.0) (#10657)
Starting v4.0, pgvector support is mandatory. This PR adds pgvector
support for new/existing Linux installations via cwctl.

- Install `pgvector` for new deployments via cwctl
- Show a warning before upgrading to 4.0 or above for existing
installations. The user is expected to install `pgvector` based on their
version of self-hosted Postgres or managed Postgres.
2025-01-14 19:43:56 +05:30
Shivam MishraandGitHub 26187c3ebf fix: toggle for reply editor (#10680)
The reply editor toggle was a bit confusing for a few users, where it's
not clear that it's clickable. This PR updates it to make it more clear

### Pending Work

- [x] RTL view

### Preview

##### Dark Mode


https://github.com/user-attachments/assets/9e377eda-34d5-4f64-a06a-23ae822da50e

##### Light Mode


https://github.com/user-attachments/assets/84c6b23c-cd17-4805-8e63-9d7d1cc0d799
2025-01-14 16:28:29 +05:30
Sivin VargheseandGitHub bffc24d119 fix(v4): Overflow issue in conversation card (#10679) 2025-01-14 12:48:30 +05:30
Shivam MishraandGitHub dbcc55665a fix: Bubble style when grouping with next (#10677) 2025-01-14 09:05:29 +05:30
Shivam MishraandGitHub 35ca67c9ba fix: Update the design for the reply box banner UI (#10678) 2025-01-13 13:12:43 -08:00
Sojan JoseandGitHub c75ed1ef69 fix: Prevent duplicate notifications for mentions (#10675)
This PR addresses an issue where mention_notification was being
overwritten by assigned_conversation_new_message notifications.
Similarly, participating_conversation_new_message was taking priority
over assigned_conversation_new_message.

The fix ensures that additional notifications are not created in these
scenarios by establishing a priority order for notifications as follows:

1. mention_notification
2. assigned_conversation_new_message
3. participating_conversation_new_message

This change maintains consistency and prevents redundant notifications.

----

Note: In the older implementation of notifications in Chatwoot,
notification objects were created only if the user had subscribed to a
specific notification type. With the new inbox_view model, we are
changing this approach to create notification objects in all cases. This
PR updates the services to remove reliance on notification preferences,
simplifying the logic.


----

Caveat: Since we don’t create extra notifications for new messages if a
mention_notification already exists, a user subscribed to
new_message_notification push/email notifications but not to
mention_notification will not receive notifications in these cases.
2025-01-13 11:20:31 +05:30
Sojan JoseandGitHub 97235a4365 fix: Exclude notifications for blocked contacts, except mentions (#10659)
- Prevents notifications from being created for conversations or actions
involving blocked contacts.
- The exception is the conversation_mention notification type, which
will still be created when applicable.
2025-01-12 15:30:27 +05:30
Shivam MishraandGitHub 74870bec41 fix: Fix bubble overflow issue and color (#10674) 2025-01-11 10:02:24 -08:00
Shivam MishraandGitHub 0d90e7c158 fix: Teams feature flag (#10673) 2025-01-11 10:01:57 -08:00
Shivam MishraandGitHub e70f7a2550 fix: Bubble typography (#10653)
![CleanShot 2025-01-08 at 18 22
36@2x](https://github.com/user-attachments/assets/77cc99d2-1bdf-49ff-9016-57bb9c50b149)
2025-01-10 15:40:12 +05:30
Shivam MishraandGitHub 4912140893 fix: ensure the message types are same when grouping (#10661) 2025-01-10 09:32:06 +05:30
Shivam MishraandGitHub 2d44468c38 fix: attachment url in file chip (#10662)
https://github.com/user-attachments/assets/e84d94d5-876d-4c00-88be-a460f917bf3b
2025-01-10 09:31:56 +05:30
Shivam MishraandGitHub 1ac2a0949f fix: conversation footer colors (#10654) 2025-01-09 15:04:40 +05:30
Shivam MishraandGitHub ef01779d61 fix: Message grouping logic (#10656) 2025-01-09 13:24:16 +05:30
Muhsin KelothandGitHub b5f4e8155b chore: Configure iOS universal linking (#10651)
- Moved `apple-app-site-association` to
`.well-known/apple-app-site-association`
https://docs.expo.dev/linking/ios-universal-links/#create-aasa-file
- Updated the paths pattern to accept conversation links only.
2025-01-08 21:25:11 +05:30
Shivam MishraandGitHub 25258417de fix: v4 ui issues (#10652)
This PR has the following fixes

1. Remove leading `:` in inbox view push message content
2. Styles for block quotes in text
3. Better condition for checking bot message
4. Use dompurify
2025-01-08 18:17:50 +05:30
dd595675bc chore: Update reply editor design (#10575)
# Pull Request Template

## Description

This PR will update the reply message editor’s design.

**Screen recording**


https://github.com/user-attachments/assets/40f61903-6bf7-4031-9a36-9027dffc46aa

---------

Co-authored-by: Pranav <pranavrajs@gmail.com>
Co-authored-by: Shivam Mishra <scm.mymail@gmail.com>
2025-01-08 17:49:53 +05:30
fa8f1d9b6f fix: throttle reports api endpoint (#10620)
- Throttle reports API requests at the account level
- Throttle reports API requests at the user level for dashboard users as
well as API users

Co-authored-by: Sojan Jose <sojan@pepalo.com>
2025-01-08 15:43:33 +05:30
Shivam MishraandGitHub 91b1015457 feat: fixes for bubble UI (#10643)
This PR applies the following fixes

1. Images in emails have margins, causing unnecessary gaps when 1x1px
images are loaded (ref:
[42111](https://app.chatwoot.com/app/accounts/1/conversations/42111?messageId=96215315))
2. Two adjacent `<br>` tags would add a huge gap, fixed this (ref:
[42111](https://app.chatwoot.com/app/accounts/1/conversations/42111?messageId=96215315))
3. Color for outgoing emails is wrong (ref:
[41621](https://app.chatwoot.com/app/accounts/1/conversations/41621?messageId=93560032))
4. Wrong list styles (see:
[42372](https://app.chatwoot.com/app/accounts/1/conversations/42372?messageId=96208130))
5. Wrong bubble color when outgoing message is sent by a bot or captain
6. Wrong avatar when outgoing message is sent by a bot or captain
2025-01-08 09:26:40 +05:30
Shivam MishraandGitHub c924d386f4 fix: reply-to preview not working on next bubbles (#10649) 2025-01-08 08:58:21 +05:30
Sivin VargheseandGitHub 3c93cdb8b2 feat(v4): Update Inbox view card design (#10599) 2025-01-07 21:11:54 +05:30
918f8e6f8e fix: AgentTable report showing test value for zero conversations (#10641)
# Pull Request Template

## Description

Changed to make use of nullish coalescing operator to only short circuit
in cases when the `metric` variable is not zero. This change also begs
the question as to whether the `stringToFloat` test function should
exist - to me it seems interesting to have test code embedded into
production code for the frontend?
Fixes #10640

## Type of change

Please delete options that are not relevant.

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality not to work as expected)
- [ ] This change requires a documentation update

## How Has This Been Tested?

Tested by opening the report overview page and reviewing that this shows
`---` for agents with no conversations assigned to them.


## 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
- [x] I have made corresponding changes to the documentation
- [x] 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
- [x] Any dependent changes have been merged and published in downstream
modules

---------

Co-authored-by: Shivam Mishra <scm.mymail@gmail.com>
2025-01-06 13:51:27 +05:30
Sojan JoseandGitHub 5e4e955e64 chore: Avoid contact inboxes getting deleted (#10612)
We observed some rare instances on prod where a contact inbox was
getting deleted during the contact merge action. the potential suspect
is contact inbox objects already loaded into the memory getting cleared
through the destroy association job. Reloading the object to avoid this
case !!!
2024-12-26 16:17:38 +05:30
Shivam MishraandGitHub c19d70a6a0 fix: bubble UI issues (#10608)
This PR has fixes for the following issues

- Inconsistent spacing between meta and text in text bubble
- Activity bubble overflows for longer text (for now I have truncated
it, I'll work with @absurdiya on a better solution)
- Ugly lookinh gradient for expand button on email bubble
- Email bubble overflow issues and text rendering issues
- Alignment for error message
- Minute-wise grouping not working
- Link color should not be blue
- Use `gray-3` for bubble background instead of `gray-4`
2024-12-21 13:36:46 +05:30
PranavandGitHub c52282307a feat(v4): Update team, agent summary builder to include resolution metrics (#10607)
Following https://github.com/chatwoot/chatwoot/pull/10604, this PR
introduces similar reporting features for Agents and Teams.

Updates in this PR:
- Added additional methods to the base class to avoid repetition.
- Improve reporting for Teams and Agents to include resolution count.
2024-12-20 19:16:56 +05:30
4fd9bddb9d feat(v4): Add API to fetch aggregate reports for inboxes (#10604)
The Inbox Overview section is being updated to offer a more detailed
report, showing an overall view of the account grouped by inboxes. To
view detailed reports and access specific graphs for individual inboxes,
click on the inbox name to navigate to its dedicated report page.

---------

Co-authored-by: Sojan Jose <sojan@pepalo.com>
2024-12-19 14:47:19 -08:00
eef70b9bd7 feat: integrate new bubbles (#10550)
To test this, set the `useNextBubble` value to `true` in the
localstorage. Here's a quick command to run in the console

```js
localStorage.setItem('useNextBubble', true)
```

```js
localStorage.setItem('useNextBubble', false)
```

---------

Co-authored-by: Pranav <pranavrajs@gmail.com>
2024-12-19 18:41:55 +05:30
Sojan 9279175199 Merge branch 'release/3.16.0' into develop 2024-12-17 23:03:32 +05:30
Sojan 361878d346 Bump version to 3.16.0 2024-12-17 23:02:59 +05:30
Sivin VargheseandGitHub 2a4c0dfa2a chore: Adds the ability to remove labels from label card (#10591) 2024-12-17 18:43:36 +05:30
Sivin VargheseandGitHub 6b348da807 feat(v4): Compose a new conversation from a phone number. (#10568) 2024-12-17 18:07:58 +05:30
96ae298464 fix: Dotenv::Railtie is deprecated (#10515)
https://github.com/bkeepers/dotenv/pull/468

Renames Dotenv::Railtie => Dotenv::Rails

Co-authored-by: Sojan Jose <sojan@pepalo.com>
2024-12-17 17:20:44 +05:30
932244a1ec feat: Add support for Arcade videos on articles (#10585)
Fixes
https://linear.app/chatwoot/issue/CW-3779/add-support-for-arcade-videos-on-articles-loom-alternative

**Loom video**

https://www.loom.com/share/917bdecb4eaf4d3f9782b4fa84ee4bd4?sid=d11f0d71-0cf5-424a-9268-9d9fb3797ee2


Co-authored-by: Sojan Jose <sojan@pepalo.com>
2024-12-17 17:17:42 +05:30
PranavandGitHub d69571f6f8 fix: Update old data to fix login issues (#10594)
The following lines caused issues for some users, specifically those who
signed up in 2021 when audio alerts were implemented as a flag. The data
type update for the flag was not handled correctly. This PR fixes the
issue by updating it to a compatible value.


https://github.com/chatwoot/chatwoot/blob/9410b3bcbbb7aba4b790f33bea52a430bf69466c/app/javascript/dashboard/helper/AudioAlerts/DashboardAudioNotificationHelper.js#L76-L81
2024-12-17 17:17:11 +05:30
Sojan JoseandGitHub 1d88e0dd28 fix: Contact form breaks if name is empty (#10597)
- Handles the case where the form and contact display page breaks if
name is `null`
2024-12-17 17:16:50 +05:30
Shivam MishraandGitHub b34dac7bbe feat: validate query conditions (#10595)
Query conditions can take in arbitrary values, this can cause SQL
errors. This PR fixes it
2024-12-17 17:16:37 +05:30
Vishnu NarayananandGitHub e3109dbb22 chore: pin bundler version to 2.5.x in circleci (#10596) 2024-12-17 16:31:55 +05:30
1637 changed files with 75113 additions and 28049 deletions
+10 -2
View File
@@ -26,6 +26,12 @@ jobs:
override-ci-command: pnpm i
- run: node --version
- run: pnpm --version
- run:
name: Add PostgreSQL repository and update
command: |
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
sudo apt-get update -y
- run:
name: Install System Dependencies
@@ -34,7 +40,9 @@ jobs:
DEBIAN_FRONTEND=noninteractive sudo apt-get install -y \
libpq-dev \
redis-server \
postgresql \
postgresql-common \
postgresql-16 \
postgresql-16-pgvector \
build-essential \
git \
curl \
@@ -74,7 +82,7 @@ jobs:
source ~/.rvm/scripts/rvm
rvm install "3.3.3"
rvm use 3.3.3 --default
gem install bundler
gem install bundler -v 2.5.16
- run:
name: Install Application Dependencies
+1
View File
@@ -51,6 +51,7 @@ exclude_patterns:
- 'app/javascript/dashboard/routes/dashboard/settings/automation/constants.js'
- 'app/javascript/dashboard/components/widgets/FilterInput/FilterOperatorTypes.js'
- 'app/javascript/dashboard/routes/dashboard/settings/reports/constants.js'
- 'app/javascript/dashboard/store/captain/storeFactory.js'
- 'app/javascript/dashboard/i18n/index.js'
- 'app/javascript/widget/i18n/index.js'
- 'app/javascript/survey/i18n/index.js'
+1 -1
View File
@@ -40,7 +40,7 @@ services:
network_mode: service:db
db:
image: postgres:latest
image: pgvector/pgvector:pg16
restart: unless-stopped
volumes:
- postgres-data:/var/lib/postgresql/data
+98 -20
View File
@@ -5,6 +5,7 @@
# #
name: Publish Chatwoot CE docker images
on:
push:
branches:
@@ -12,23 +13,32 @@ on:
- master
tags:
- v*
# pull_request:
workflow_dispatch:
env:
DOCKER_REPO: chatwoot/chatwoot
jobs:
build:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- platform: linux/amd64
runner: ubuntu-latest
- platform: linux/arm64
runner: ubuntu-22.04-arm
runs-on: ${{ matrix.runner }}
env:
GIT_REF: ${{ github.head_ref || github.ref_name }} # ref_name to get tags/branches
GIT_REF: ${{ github.head_ref || github.ref_name }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
- name: Strip enterprise code
run: |
@@ -39,29 +49,97 @@ jobs:
run: |
echo -en '\nENV CW_EDITION="ce"' >> docker/Dockerfile
- name: set docker tag
- name: Set Docker Tags
run: |
# Replace forward slashes with hyphens in the ref name
SANITIZED_REF=$(echo "$GIT_REF" | sed 's/\//-/g')
echo "DOCKER_TAG=chatwoot/chatwoot:$SANITIZED_REF-ce" >> $GITHUB_ENV
if [ "${{ github.ref_name }}" = "master" ]; then
echo "DOCKER_TAG=${DOCKER_REPO}:latest-ce" >> $GITHUB_ENV
else
echo "DOCKER_TAG=${DOCKER_REPO}:${SANITIZED_REF}-ce" >> $GITHUB_ENV
fi
- name: replace docker tag if master
if: github.ref_name == 'master'
run: |
echo "DOCKER_TAG=chatwoot/chatwoot:latest-ce" >> $GITHUB_ENV
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
uses: docker/login-action@v1
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v2
- name: Build and push by digest
id: build
uses: docker/build-push-action@v6
with:
context: .
file: docker/Dockerfile
platforms: linux/amd64, linux/arm64
platforms: ${{ matrix.platform }}
push: ${{ github.event_name == 'push' || github.event_name == 'workflow_dispatch' }}
tags: ${{ env.DOCKER_TAG }}
outputs: type=image,name=${{ env.DOCKER_REPO }},push-by-digest=true,name-canonical=true,push=true
- name: Export digest
run: |
mkdir -p ${{ runner.temp }}/digests
digest="${{ steps.build.outputs.digest }}"
touch "${{ runner.temp }}/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v4
with:
name: digests-${{ env.PLATFORM_PAIR }}
path: ${{ runner.temp }}/digests/*
if-no-files-found: error
retention-days: 1
merge:
runs-on: ubuntu-latest
needs:
- build
steps:
- name: Download digests
uses: actions/download-artifact@v4
with:
path: ${{ runner.temp }}/digests
pattern: digests-*
merge-multiple: true
- name: Login to DockerHub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Create manifest list and push
working-directory: ${{ runner.temp }}/digests
env:
GIT_REF: ${{ github.head_ref || github.ref_name }}
run: |
SANITIZED_REF=$(echo "$GIT_REF" | sed 's/\//-/g')
if [ "${{ github.ref_name }}" = "master" ]; then
TAG="${DOCKER_REPO}:latest-ce"
else
TAG="${DOCKER_REPO}:${SANITIZED_REF}-ce"
fi
docker buildx imagetools create -t $TAG \
$(printf '${{ env.DOCKER_REPO }}@sha256:%s ' *)
- name: Inspect image
env:
GIT_REF: ${{ github.head_ref || github.ref_name }}
run: |
SANITIZED_REF=$(echo "$GIT_REF" | sed 's/\//-/g')
if [ "${{ github.ref_name }}" = "master" ]; then
TAG="${DOCKER_REPO}:latest-ce"
else
TAG="${DOCKER_REPO}:${SANITIZED_REF}-ce"
fi
docker buildx imagetools inspect $TAG
+1 -7
View File
@@ -1,9 +1,3 @@
# #
# # This action will strip the enterprise folder
# # and run the spec.
# # This is set to run against every PR.
# #
name: Run Chatwoot CE spec
on:
push:
@@ -18,7 +12,7 @@ jobs:
runs-on: ubuntu-20.04
services:
postgres:
image: postgres:15.3
image: pgvector/pgvector:pg15
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: ''
@@ -1,89 +0,0 @@
# #
# # This workflow will run specs related to response bot
# # This can only be activated in installations Where vector extension is available.
# #
name: Run Response Bot spec
on:
push:
branches:
- develop
- master
pull_request:
workflow_dispatch:
jobs:
test:
runs-on: ubuntu-20.04
services:
postgres:
image: ankane/pgvector
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: ""
POSTGRES_DB: postgres
POSTGRES_HOST_AUTH_METHOD: trust
ports:
- 5432:5432
# needed because the postgres container does not provide a healthcheck
# tmpfs makes DB faster by using RAM
options: >-
--mount type=tmpfs,destination=/var/lib/postgresql/data
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
redis:
image: redis
ports:
- 6379:6379
options: --entrypoint redis-server
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.ref }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- uses: ruby/setup-ruby@v1
with:
bundler-cache: true # runs 'bundle install' and caches installed gems automatically
- uses: pnpm/action-setup@v2
with:
version: 9.3.0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: pnpm
- name: pnpm
run: pnpm install
- name: Create database
run: bundle exec rake db:create
- name: Seed database
run: bundle exec rake db:schema:load
- name: Enable ResponseBotService in installation
run: RAILS_ENV=test bundle exec rails runner "Features::ResponseBotService.new.enable_in_installation"
# Run Response Bot specs
- name: Run backend tests
run: |
bundle exec rspec \
spec/enterprise/controllers/api/v1/accounts/response_sources_controller_spec.rb \
spec/enterprise/services/enterprise/message_templates/response_bot_service_spec.rb \
spec/enterprise/controllers/enterprise/api/v1/accounts/inboxes_controller_spec.rb:47 \
spec/enterprise/jobs/enterprise/account/conversations_resolution_scheduler_job_spec.rb \
--profile=10 \
--format documentation
- name: Upload rails log folder
uses: actions/upload-artifact@v4
if: always()
with:
name: rails-log-folder
path: log
+2
View File
@@ -175,6 +175,8 @@ gem 'pgvector'
# Convert Website HTML to Markdown
gem 'reverse_markdown'
gem 'ruby-openai'
### Gems required only in specific deployment environments ###
##############################################################
+6
View File
@@ -231,6 +231,7 @@ GEM
erubi (1.13.0)
et-orbi (1.2.11)
tzinfo
event_stream_parser (1.0.0)
execjs (2.8.1)
facebook-messenger (2.0.1)
httparty (~> 0.13, >= 0.13.7)
@@ -684,6 +685,10 @@ GEM
rubocop-rspec (2.21.0)
rubocop (~> 1.33)
rubocop-capybara (~> 2.17)
ruby-openai (7.3.1)
event_stream_parser (>= 0.3.0, < 2.0.0)
faraday (>= 1)
faraday-multipart (>= 1)
ruby-progressbar (1.13.0)
ruby-vips (2.1.4)
ffi (~> 1.12)
@@ -941,6 +946,7 @@ DEPENDENCIES
rubocop-performance
rubocop-rails
rubocop-rspec
ruby-openai
scout_apm
scss_lint
seed_dump
+1 -1
View File
@@ -120,4 +120,4 @@ Thanks goes to all these [wonderful people](https://www.chatwoot.com/docs/contri
<a href="https://github.com/chatwoot/chatwoot/graphs/contributors"><img src="https://opencollective.com/chatwoot/contributors.svg?width=890&button=false" /></a>
*Chatwoot* &copy; 2017-2024, Chatwoot Inc - Released under the MIT License.
*Chatwoot* &copy; 2017-2025, Chatwoot Inc - Released under the MIT License.
+4 -4
View File
@@ -2,13 +2,13 @@ Chatwoot is looking forward to working with security researchers worldwide to ke
## Reporting a Vulnerability
We use [huntr.dev](https://huntr.dev/) for security issues that affect our project. If you believe you have found a vulnerability, please disclose it via this [form](https://huntr.dev/bounties/disclose). This will enable us to review the vulnerability, fix it promptly, and reward you for your efforts.
We use Github to track the security issues that affect our project. If you believe you have found a vulnerability, please disclose it via this [form](https://github.com/chatwoot/chatwoot/security/advisories/new). This will enable us to review the vulnerability, fix it promptly, and reward you for your efforts.
If you have any questions about the process, contact security@chatwoot.com.
Please try your best to describe a clear and realistic impact for your report, and please don't open any public issues on GitHub or social media; we're doing our best to respond through Huntr as quickly as possible.
Please try your best to describe a clear and realistic impact for your report, and please don't open any public issues on GitHub or social media; we're doing our best to respond through Github as quickly as possible.
> Note: Please use the email for questions related to the process. Disclosures should be done via [huntr.dev](https://huntr.dev/)
> Note: Please use the email for questions related to the process. Disclosures should be done via [Github](https://github.com/chatwoot/chatwoot/security/advisories/new)
## Supported versions
| Version | Supported |
@@ -48,7 +48,7 @@ We consider the following out of scope, though there may be exceptions.
- Brute force attacks
- DNSSEC
If you are unsure about the scope, please create a [report](https://huntr.dev/repos/chatwoot/chatwoot/).
If you are unsure about the scope, please create a [report](https://github.com/chatwoot/chatwoot/security/advisories/new).
## Thanks
+1 -1
View File
@@ -1 +1 @@
3.0.0
3.1.0
+1 -1
View File
@@ -54,7 +54,7 @@ class ContactMergeAction
# attributes in base contact are given preference
merged_attributes = mergee_contact_attributes.deep_merge(base_contact_attributes)
@mergee_contact.destroy!
@mergee_contact.reload.destroy!
Rails.configuration.dispatcher.dispatch(CONTACT_MERGED, Time.zone.now, contact: @base_contact,
tokens: [@base_contact.contact_inboxes.filter_map(&:pubsub_token)])
@base_contact.update!(merged_attributes)
+2
View File
@@ -25,6 +25,8 @@ class NotificationBuilder
def build_notification
# Create conversation_creation notification only if user is subscribed to it
return if notification_type == 'conversation_creation' && !user_subscribed_to_notification?
# skip notifications for blocked conversations except for user mentions
return if primary_actor.contact.blocked? && notification_type != 'conversation_mention'
user.notifications.create!(
notification_type: notification_type,
@@ -2,52 +2,38 @@ class V2::Reports::AgentSummaryBuilder < V2::Reports::BaseSummaryBuilder
pattr_initialize [:account!, :params!]
def build
set_grouped_conversations_count
set_grouped_avg_reply_time
set_grouped_avg_first_response_time
set_grouped_avg_resolution_time
load_data
prepare_report
end
private
def set_grouped_conversations_count
@grouped_conversations_count = Current.account.conversations.where(created_at: range).group('assignee_id').count
attr_reader :conversations_count, :resolved_count,
:avg_resolution_time, :avg_first_response_time, :avg_reply_time
def fetch_conversations_count
account.conversations.where(created_at: range).group('assignee_id').count
end
def set_grouped_avg_resolution_time
@grouped_avg_resolution_time = get_grouped_average(reporting_events.where(name: 'conversation_resolved'))
def prepare_report
account.account_users.map do |account_user|
build_agent_stats(account_user)
end
end
def set_grouped_avg_first_response_time
@grouped_avg_first_response_time = get_grouped_average(reporting_events.where(name: 'first_response'))
end
def set_grouped_avg_reply_time
@grouped_avg_reply_time = get_grouped_average(reporting_events.where(name: 'reply_time'))
def build_agent_stats(account_user)
user_id = account_user.user_id
{
id: user_id,
conversations_count: conversations_count[user_id] || 0,
resolved_conversations_count: resolved_count[user_id] || 0,
avg_resolution_time: avg_resolution_time[user_id],
avg_first_response_time: avg_first_response_time[user_id],
avg_reply_time: avg_reply_time[user_id]
}
end
def group_by_key
:user_id
end
def reporting_events
@reporting_events ||= Current.account.reporting_events.where(created_at: range)
end
def prepare_report
account.account_users.each_with_object([]) do |account_user, arr|
arr << {
id: account_user.user_id,
conversations_count: @grouped_conversations_count[account_user.user_id],
avg_resolution_time: @grouped_avg_resolution_time[account_user.user_id],
avg_first_response_time: @grouped_avg_first_response_time[account_user.user_id],
avg_reply_time: @grouped_avg_reply_time[account_user.user_id]
}
end
end
def average_value_key
ActiveModel::Type::Boolean.new.cast(params[:business_hours]).present? ? :value_in_business_hours : :value
end
end
@@ -1,17 +1,50 @@
class V2::Reports::BaseSummaryBuilder
include DateRangeHelper
def build
load_data
prepare_report
end
private
def load_data
@conversations_count = fetch_conversations_count
@resolved_count = fetch_resolved_count
@avg_resolution_time = fetch_average_time('conversation_resolved')
@avg_first_response_time = fetch_average_time('first_response')
@avg_reply_time = fetch_average_time('reply_time')
end
def reporting_events
@reporting_events ||= account.reporting_events.where(created_at: range)
end
def fetch_conversations_count
# Override this method
end
def fetch_average_time(event_name)
get_grouped_average(reporting_events.where(name: event_name))
end
def fetch_resolved_count
reporting_events.where(name: 'conversation_resolved').group(group_by_key).count
end
def group_by_key
# Override this method
end
def prepare_report
# Override this method
end
def get_grouped_average(events)
events.group(group_by_key).average(average_value_key)
end
def average_value_key
params[:business_hours].present? ? :value_in_business_hours : :value
ActiveModel::Type::Boolean.new.cast(params[:business_hours]).present? ? :value_in_business_hours : :value
end
end
@@ -0,0 +1,50 @@
class V2::Reports::InboxSummaryBuilder < V2::Reports::BaseSummaryBuilder
pattr_initialize [:account!, :params!]
def build
load_data
prepare_report
end
private
attr_reader :conversations_count, :resolved_count,
:avg_resolution_time, :avg_first_response_time, :avg_reply_time
def load_data
@conversations_count = fetch_conversations_count
@resolved_count = fetch_resolved_count
@avg_resolution_time = fetch_average_time('conversation_resolved')
@avg_first_response_time = fetch_average_time('first_response')
@avg_reply_time = fetch_average_time('reply_time')
end
def fetch_conversations_count
account.conversations.where(created_at: range).group(group_by_key).count
end
def prepare_report
account.inboxes.map do |inbox|
build_inbox_stats(inbox)
end
end
def build_inbox_stats(inbox)
{
id: inbox.id,
conversations_count: conversations_count[inbox.id] || 0,
resolved_conversations_count: resolved_count[inbox.id] || 0,
avg_resolution_time: avg_resolution_time[inbox.id],
avg_first_response_time: avg_first_response_time[inbox.id],
avg_reply_time: avg_reply_time[inbox.id]
}
end
def group_by_key
:inbox_id
end
def average_value_key
ActiveModel::Type::Boolean.new.cast(params[:business_hours]) ? :value_in_business_hours : :value
end
end
+22 -34
View File
@@ -1,49 +1,37 @@
class V2::Reports::TeamSummaryBuilder < V2::Reports::BaseSummaryBuilder
pattr_initialize [:account!, :params!]
def build
set_grouped_conversations_count
set_grouped_avg_reply_time
set_grouped_avg_first_response_time
set_grouped_avg_resolution_time
prepare_report
end
private
def set_grouped_conversations_count
@grouped_conversations_count = Current.account.conversations.where(created_at: range).group('team_id').count
end
attr_reader :conversations_count, :resolved_count,
:avg_resolution_time, :avg_first_response_time, :avg_reply_time
def set_grouped_avg_resolution_time
@grouped_avg_resolution_time = get_grouped_average(reporting_events.where(name: 'conversation_resolved'))
end
def set_grouped_avg_first_response_time
@grouped_avg_first_response_time = get_grouped_average(reporting_events.where(name: 'first_response'))
end
def set_grouped_avg_reply_time
@grouped_avg_reply_time = get_grouped_average(reporting_events.where(name: 'reply_time'))
def fetch_conversations_count
account.conversations.where(created_at: range).group(:team_id).count
end
def reporting_events
@reporting_events ||= Current.account.reporting_events.where(created_at: range).joins(:conversation)
@reporting_events ||= account.reporting_events.where(created_at: range).joins(:conversation)
end
def prepare_report
account.teams.map do |team|
build_team_stats(team)
end
end
def build_team_stats(team)
{
id: team.id,
conversations_count: conversations_count[team.id] || 0,
resolved_conversations_count: resolved_count[team.id] || 0,
avg_resolution_time: avg_resolution_time[team.id],
avg_first_response_time: avg_first_response_time[team.id],
avg_reply_time: avg_reply_time[team.id]
}
end
def group_by_key
'conversations.team_id'
end
def prepare_report
account.teams.each_with_object([]) do |team, arr|
arr << {
id: team.id,
conversations_count: @grouped_conversations_count[team.id],
avg_resolution_time: @grouped_avg_resolution_time[team.id],
avg_first_response_time: @grouped_avg_first_response_time[team.id],
avg_reply_time: @grouped_avg_reply_time[team.id]
}
end
end
end
@@ -28,7 +28,7 @@ class V2::Reports::Timeseries::AverageReportBuilder < V2::Reports::Timeseries::B
end
def object_scope
scope.reporting_events.where(name: event_name, created_at: range)
scope.reporting_events.where(name: event_name, created_at: range, account_id: account.id)
end
def reporting_events
@@ -68,6 +68,7 @@ class Api::V1::Accounts::ContactsController < Api::V1::Accounts::BaseController
@contacts = fetch_contacts(contacts)
rescue CustomExceptions::CustomFilter::InvalidAttribute,
CustomExceptions::CustomFilter::InvalidOperator,
CustomExceptions::CustomFilter::InvalidQueryOperator,
CustomExceptions::CustomFilter::InvalidValue => e
render_could_not_create_error(e.message)
end
@@ -46,6 +46,7 @@ class Api::V1::Accounts::ConversationsController < Api::V1::Accounts::BaseContro
@conversations_count = result[:count]
rescue CustomExceptions::CustomFilter::InvalidAttribute,
CustomExceptions::CustomFilter::InvalidOperator,
CustomExceptions::CustomFilter::InvalidQueryOperator,
CustomExceptions::CustomFilter::InvalidValue => e
render_could_not_create_error(e.message)
end
@@ -1,78 +0,0 @@
class Api::V1::Accounts::Integrations::CaptainController < Api::V1::Accounts::BaseController
before_action :hook
def proxy
request_url = build_request_url(request_path)
response = HTTParty.send(request_method, request_url, body: permitted_params[:body].to_json, headers: headers)
render plain: response.body, status: response.code
end
def copilot
request_url = build_request_url(build_request_path("/assistants/#{hook.settings['assistant_id']}/copilot"))
params = {
previous_messages: copilot_params[:previous_messages],
conversation_history: conversation_history,
message: copilot_params[:message]
}
response = HTTParty.send(:post, request_url, body: params.to_json, headers: headers)
render plain: response.body, status: response.code
end
private
def headers
{
'X-User-Email' => hook.settings['account_email'],
'X-User-Token' => hook.settings['access_token'],
'Content-Type' => 'application/json',
'Accept' => '*/*'
}
end
def build_request_path(route)
"api/accounts/#{hook.settings['account_id']}#{route}"
end
def request_path
request_route = with_leading_hash_on_route(params[:route])
return 'api/sessions/profile' if request_route == '/sessions/profile'
build_request_path(request_route)
end
def build_request_url(request_path)
base_url = InstallationConfig.find_by(name: 'CAPTAIN_API_URL').value
URI.join(base_url, request_path).to_s
end
def hook
@hook ||= Current.account.hooks.find_by!(app_id: 'captain')
end
def request_method
method = permitted_params[:method].downcase
raise 'Invalid or missing HTTP method' unless %w[get post put patch delete options head].include?(method)
method
end
def with_leading_hash_on_route(request_route)
return '' if request_route.blank?
request_route.start_with?('/') ? request_route : "/#{request_route}"
end
def conversation_history
conversation = Current.account.conversations.find_by!(display_id: copilot_params[:conversation_id])
conversation.to_llm_text
end
def copilot_params
params.permit(:previous_messages, :conversation_id, :message)
end
def permitted_params
params.permit(:method, :route, body: {})
end
end
@@ -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]
before_action :prepare_builder_params, only: [:agent, :team, :inbox]
def agent
render_report_with(V2::Reports::AgentSummaryBuilder)
@@ -10,6 +10,10 @@ class Api::V2::Accounts::SummaryReportsController < Api::V1::Accounts::BaseContr
render_report_with(V2::Reports::TeamSummaryBuilder)
end
def inbox
render_report_with(V2::Reports::InboxSummaryBuilder)
end
private
def check_authorization
@@ -26,8 +30,7 @@ class Api::V2::Accounts::SummaryReportsController < Api::V1::Accounts::BaseContr
def render_report_with(builder_class)
builder = builder_class.new(account: Current.account, params: @builder_params)
data = builder.build
render json: data
render json: builder.build
end
def permitted_params
@@ -7,9 +7,10 @@ class Public::Api::V1::Portals::ArticlesController < Public::Api::V1::Portals::B
def index
@articles = @portal.articles.published
@articles_count = @articles.count
search_articles
order_by_sort_param
@articles.page(list_params[:page]) if list_params[:page].present?
@articles = @articles.page(list_params[:page]) if list_params[:page].present?
end
def show; end
@@ -44,7 +45,7 @@ class Public::Api::V1::Portals::ArticlesController < Public::Api::V1::Portals::B
end
def list_params
params.permit(:query, :locale, :sort, :status)
params.permit(:query, :locale, :sort, :status, :page)
end
def permitted_params
+2
View File
@@ -22,3 +22,5 @@ class AsyncDispatcher < BaseDispatcher
]
end
end
AsyncDispatcher.prepend_mod_with('AsyncDispatcher')
@@ -2,6 +2,6 @@ require 'administrate/field/base'
class Enterprise::AccountLimitsField < Administrate::Field::Base
def to_s
data.present? ? data.to_json : { agents: nil, inboxes: nil }.to_json
data.present? ? data.to_json : { agents: nil, inboxes: nil, captain_responses: nil, captain_documents: nil }.to_json
end
end
+39 -27
View File
@@ -1,58 +1,70 @@
module Api::V2::Accounts::ReportsHelper
def generate_agents_report
reports = V2::Reports::AgentSummaryBuilder.new(
account: Current.account,
params: build_params(type: :agent)
).build
Current.account.users.map do |agent|
agent_report = report_builder({ type: :agent, id: agent.id }).summary
[agent.name] + generate_readable_report_metrics(agent_report)
report = reports.find { |r| r[:id] == agent.id }
[agent.name] + generate_readable_report_metrics(report)
end
end
def generate_inboxes_report
reports = V2::Reports::InboxSummaryBuilder.new(
account: Current.account,
params: build_params(type: :inbox)
).build
Current.account.inboxes.map do |inbox|
inbox_report = generate_report({ type: :inbox, id: inbox.id })
[inbox.name, inbox.channel&.name] + generate_readable_report_metrics(inbox_report)
report = reports.find { |r| r[:id] == inbox.id }
[inbox.name, inbox.channel&.name] + generate_readable_report_metrics(report)
end
end
def generate_teams_report
reports = V2::Reports::TeamSummaryBuilder.new(
account: Current.account,
params: build_params(type: :team)
).build
Current.account.teams.map do |team|
team_report = report_builder({ type: :team, id: team.id }).summary
[team.name] + generate_readable_report_metrics(team_report)
report = reports.find { |r| r[:id] == team.id }
[team.name] + generate_readable_report_metrics(report)
end
end
def generate_labels_report
Current.account.labels.map do |label|
label_report = generate_report({ type: :label, id: label.id })
label_report = report_builder({ type: :label, id: label.id }).short_summary
[label.title] + generate_readable_report_metrics(label_report)
end
end
def report_builder(report_params)
V2::ReportBuilder.new(
Current.account,
report_params.merge(
{
since: params[:since],
until: params[:until],
business_hours: ActiveModel::Type::Boolean.new.cast(params[:business_hours])
}
)
private
def build_params(base_params)
base_params.merge(
{
since: params[:since],
until: params[:until],
business_hours: ActiveModel::Type::Boolean.new.cast(params[:business_hours])
}
)
end
def generate_report(report_params)
report_builder(report_params).short_summary
def report_builder(report_params)
V2::ReportBuilder.new(Current.account, build_params(report_params))
end
private
def generate_readable_report_metrics(report_metric)
def generate_readable_report_metrics(report)
[
report_metric[:conversations_count],
Reports::TimeFormatPresenter.new(report_metric[:avg_first_response_time]).format,
Reports::TimeFormatPresenter.new(report_metric[:avg_resolution_time]).format,
Reports::TimeFormatPresenter.new(report_metric[:reply_time]).format,
report_metric[:resolutions_count]
report[:conversations_count],
Reports::TimeFormatPresenter.new(report[:avg_first_response_time]).format,
Reports::TimeFormatPresenter.new(report[:avg_resolution_time]).format,
Reports::TimeFormatPresenter.new(report[:avg_reply_time]).format,
report[:resolved_conversations_count]
]
end
end
+8
View File
@@ -81,4 +81,12 @@ module FilterHelper
def default_filter(query_hash, filter_operator_value)
"#{filter_config[:table_name]}.#{query_hash[:attribute_key]} #{filter_operator_value} #{query_hash[:query_operator]}"
end
def validate_single_condition(condition)
return if condition['query_operator'].nil?
return if condition['query_operator'].empty?
operator = condition['query_operator'].upcase
raise CustomExceptions::CustomFilter::InvalidQueryOperator.new({}) unless %w[AND OR].include?(operator)
end
end
@@ -0,0 +1,19 @@
/* global axios */
import ApiClient from '../ApiClient';
class CaptainAssistant extends ApiClient {
constructor() {
super('captain/assistants', { accountScoped: true });
}
get({ page = 1, searchKey } = {}) {
return axios.get(this.url, {
params: {
page,
searchKey,
},
});
}
}
export default new CaptainAssistant();
@@ -0,0 +1,20 @@
/* global axios */
import ApiClient from '../ApiClient';
class CaptainDocument extends ApiClient {
constructor() {
super('captain/documents', { accountScoped: true });
}
get({ page = 1, searchKey, assistantId } = {}) {
return axios.get(this.url, {
params: {
page,
searchKey,
assistant_id: assistantId,
},
});
}
}
export default new CaptainDocument();
@@ -0,0 +1,26 @@
/* global axios */
import ApiClient from '../ApiClient';
class CaptainInboxes extends ApiClient {
constructor() {
super('captain/assistants', { accountScoped: true });
}
get({ assistantId } = {}) {
return axios.get(`${this.url}/${assistantId}/inboxes`);
}
create(params = {}) {
const { assistantId, inboxId } = params;
return axios.post(`${this.url}/${assistantId}/inboxes`, {
inbox: { inbox_id: inboxId },
});
}
delete(params = {}) {
const { assistantId, inboxId } = params;
return axios.delete(`${this.url}/${assistantId}/inboxes/${inboxId}`);
}
}
export default new CaptainInboxes();
@@ -0,0 +1,22 @@
/* global axios */
import ApiClient from '../ApiClient';
class CaptainResponses extends ApiClient {
constructor() {
super('captain/assistant_responses', { accountScoped: true });
}
get({ page = 1, searchKey, assistantId, documentId, status } = {}) {
return axios.get(this.url, {
params: {
page,
searchKey,
assistant_id: assistantId,
document_id: documentId,
status,
},
});
}
}
export default new CaptainResponses();
@@ -133,6 +133,10 @@ class ConversationApi extends ApiClient {
getAllAttachments(conversationId) {
return axios.get(`${this.url}/${conversationId}/attachments`);
}
requestCopilot(conversationId, body) {
return axios.post(`${this.url}/${conversationId}/copilot`, body);
}
}
export default new ConversationApi();
@@ -32,14 +32,6 @@ class IntegrationsAPI extends ApiClient {
deleteHook(hookId) {
return axios.delete(`${this.baseUrl()}/integrations/hooks/${hookId}`);
}
requestCaptain(body) {
return axios.post(`${this.baseUrl()}/integrations/captain/proxy`, body);
}
requestCaptainCopilot(body) {
return axios.post(`${this.baseUrl()}/integrations/captain/copilot`, body);
}
}
export default new IntegrationsAPI();
@@ -0,0 +1,40 @@
/* global axios */
import ApiClient from './ApiClient';
class SummaryReportsAPI extends ApiClient {
constructor() {
super('summary_reports', { accountScoped: true, apiVersion: 'v2' });
}
getTeamReports({ since, until, businessHours } = {}) {
return axios.get(`${this.url}/team`, {
params: {
since,
until,
business_hours: businessHours,
},
});
}
getAgentReports({ since, until, businessHours } = {}) {
return axios.get(`${this.url}/agent`, {
params: {
since,
until,
business_hours: businessHours,
},
});
}
getInboxReports({ since, until, businessHours } = {}) {
return axios.get(`${this.url}/inbox`, {
params: {
since,
until,
business_hours: businessHours,
},
});
}
}
export default new SummaryReportsAPI();
@@ -124,6 +124,19 @@
--teal-11: 0 133 115;
--teal-12: 13 61 56;
--gray-1: 252 252 252;
--gray-2: 249 249 249;
--gray-3: 240 240 240;
--gray-4: 232 232 232;
--gray-5: 224 224 224;
--gray-6: 217 217 217;
--gray-7: 206 206 206;
--gray-8: 187 187 187;
--gray-9: 141 141 141;
--gray-10: 131 131 131;
--gray-11: 100 100 100;
--gray-12: 32 32 32;
--background-color: 253 253 253;
--text-blue: 8 109 224;
--border-container: 236 236 236;
@@ -213,6 +226,19 @@
--teal-11: 11 216 182;
--teal-12: 173 240 221;
--gray-1: 17 17 17;
--gray-2: 25 25 25;
--gray-3: 34 34 34;
--gray-4: 42 42 42;
--gray-5: 49 49 49;
--gray-6: 58 58 58;
--gray-7: 72 72 72;
--gray-8: 96 96 96;
--gray-9: 110 110 110;
--gray-10: 123 123 123;
--gray-11: 180 180 180;
--gray-12: 238 238 238;
--background-color: 18 18 19;
--border-strong: 52 52 52;
--border-weak: 38 38 42;
@@ -232,7 +258,7 @@
--black-alpha-2: 0, 0, 0, 0.2;
--border-blue: 39, 129, 246, 0.5;
--border-container: 236, 236, 236, 0;
--white-alpha: 255, 255, 255, 0.8;
--white-alpha: 255, 255, 255, 0.1;
}
/* NEXT COLORS END */
@@ -1,7 +1,7 @@
.dropdown-pane {
@apply border rounded-lg hidden relative invisible shadow-lg border-slate-25 dark:border-slate-700 box-content p-2 w-fit z-[9999];
@apply border rounded-lg hidden relative invisible shadow-lg border-n-strong dark:border-n-strong box-content p-2 w-fit z-[9999];
&.dropdown-pane--open {
@apply bg-white absolute dark:bg-slate-800 block visible;
@apply bg-n-alpha-3 backdrop-blur-[100px] absolute block visible;
}
}
@@ -31,7 +31,7 @@ button {
}
.button {
@apply items-center bg-woot-500 dark:bg-woot-500 px-2.5 text-white dark:text-white inline-flex h-10 mb-0 gap-2 font-medium;
@apply items-center bg-n-brand px-2.5 text-white dark:text-white inline-flex h-10 mb-0 gap-2 font-medium;
.button__content {
@apply w-full whitespace-nowrap overflow-hidden text-ellipsis;
@@ -42,8 +42,10 @@ button {
}
}
&:hover {
@apply bg-woot-600 dark:bg-woot-600;
&:hover:not(.secondary):not(.success):not(.alert):not(.warning):not(
.clear
):not(.smooth):not(.hollow) {
@apply bg-n-brand/80 dark:bg-n-brand/80;
}
&:disabled,
@@ -52,23 +54,23 @@ button {
}
&.success {
@apply bg-[#44ce4b] dark:bg-[#44ce4b] text-white dark:text-white;
@apply bg-n-teal-9 text-white dark:text-white;
}
&.secondary {
@apply bg-slate-700 dark:bg-slate-600 text-white dark:text-white;
@apply bg-n-solid-3 text-white dark:text-white;
}
&.primary {
@apply bg-woot-500 dark:bg-woot-500 text-white dark:text-white;
@apply bg-n-brand text-white dark:text-white;
}
&.clear {
@apply text-woot-500 dark:text-woot-500 bg-transparent dark:bg-transparent;
@apply text-n-blue-text dark:text-n-blue-text bg-transparent dark:bg-transparent;
}
&.alert {
@apply bg-red-500 dark:bg-red-500 text-white dark:text-white;
@apply bg-n-ruby-9 text-white dark:text-white;
&.clear {
@apply bg-transparent dark:bg-transparent;
@@ -76,7 +78,7 @@ button {
}
&.warning {
@apply bg-[#ffc532] dark:bg-[#ffc532] text-white dark:text-white;
@apply bg-n-amber-9 text-white dark:text-white;
&.clear {
@apply bg-transparent dark:bg-transparent;
@@ -115,114 +117,74 @@ button {
}
&.hollow {
@apply border border-woot-500 bg-transparent dark:bg-transparent dark:border-woot-500 text-woot-500 dark:text-woot-500 hover:bg-woot-50 dark:hover:bg-woot-900;
@apply border border-n-brand/40 bg-transparent text-n-blue-text hover:bg-n-brand/20;
&.secondary {
@apply text-slate-700 border-slate-100 dark:border-slate-800 dark:text-slate-100 hover:bg-slate-50 dark:hover:bg-slate-700;
@apply text-n-slate-12 border-n-slate-5 hover:bg-n-slate-5;
}
&.success {
@apply text-green-700 dark:text-green-400 border-green-100 dark:border-green-600 hover:bg-green-50 dark:hover:bg-green-800;
@apply text-n-teal-9 border-n-teal-8 hover:bg-n-teal-5;
}
&.alert {
@apply text-red-700 dark:text-red-400 border-red-100 dark:border-red-600 hover:bg-red-50 dark:hover:bg-red-800;
@apply text-n-ruby-9 border-n-ruby-8 hover:bg-n-ruby-5;
}
&.warning {
@apply text-yellow-600 dark:text-yellow-600 border-yellow-600 dark:border-yellow-700 hover:bg-yellow-50 dark:hover:bg-yellow-800;
}
&:hover {
@apply bg-woot-75 dark:bg-woot-800 border-slate-100 dark:border-woot-600 dark:text-woot-400;
&.secondary {
@apply border-slate-100 dark:border-slate-700 text-slate-800 dark:text-slate-100;
}
&.success {
@apply border-slate-100 dark:border-slate-700 text-green-800 dark:text-green-100;
}
&.alert {
@apply border-slate-100 dark:border-slate-700 text-red-700 dark:text-red-100;
}
&.warning {
@apply border-slate-100 dark:border-slate-700 text-yellow-700 dark:text-yellow-500;
}
@apply text-n-amber-9 border-n-amber-8 hover:bg-n-amber-5;
}
}
// Smooth style
&.smooth {
@apply bg-woot-50 dark:bg-woot-800 text-woot-700 dark:text-woot-100 hover:text-woot-700 dark:hover:text-woot-700 hover:bg-woot-100 dark:hover:bg-woot-900;
@apply bg-n-brand/10 dark:bg-n-brand/30 text-n-blue-text hover:bg-n-brand/20 dark:hover:bg-n-brand/40;
&.secondary {
@apply bg-slate-50 dark:bg-slate-700 text-slate-700 dark:text-slate-100 hover:bg-slate-100 dark:hover:bg-slate-800;
@apply bg-n-slate-4 text-n-slate-11 hover:text-n-slate-11 hover:bg-n-slate-5;
}
&.success {
@apply bg-green-50 dark:bg-green-700 text-green-700 dark:text-green-100 hover:bg-green-100 dark:hover:bg-green-800 hover:text-green-800 dark:hover:text-green-100;
@apply bg-n-teal-4 text-n-teal-11 hover:text-n-teal-11 hover:bg-n-teal-5;
}
&.alert {
@apply bg-red-50 dark:bg-red-700 dark:bg-opacity-50 text-red-700 dark:text-red-100 hover:bg-red-100 dark:hover:bg-red-800 dark:hover:bg-opacity-30;
@apply bg-n-ruby-4 text-n-ruby-11 hover:text-n-ruby-11 hover:bg-n-ruby-5;
}
&.warning {
@apply bg-yellow-100 dark:bg-yellow-100 text-yellow-700 dark:text-yellow-700 hover:bg-yellow-200 dark:hover:bg-yellow-200;
@apply bg-n-amber-4 text-n-amber-11 hover:text-n-amber-11 hover:bg-n-amber-5;
}
}
&.clear {
@apply text-woot-500 dark:text-woot-500;
@apply text-n-blue-text hover:bg-n-brand/10 dark:hover:bg-n-brand/30;
&.secondary {
@apply text-slate-700 dark:text-slate-100;
@apply text-n-slate-12 hover:bg-n-slate-4;
}
&.success {
@apply text-green-700 dark:text-green-100;
@apply text-n-teal-10 hover:bg-n-teal-4;
}
&.alert {
@apply text-red-700 dark:text-red-100;
@apply text-n-ruby-11 hover:bg-n-ruby-4;
}
&.warning {
@apply text-yellow-700 dark:text-yellow-600;
}
&:hover {
@apply hover:bg-woot-50 dark:hover:bg-woot-900/50 hover:text-woot-500 dark:hover:text-woot-100;
&.secondary {
@apply hover:bg-slate-50 dark:hover:bg-slate-700 hover:text-slate-800 dark:hover:text-slate-100;
}
&.success {
@apply hover:bg-green-50 dark:hover:bg-green-800 hover:text-green-800 dark:hover:text-green-100;
}
&.alert {
@apply hover:bg-red-50 dark:hover:bg-red-800 hover:text-red-700 dark:hover:text-red-100;
}
&.warning {
@apply hover:bg-yellow-100 dark:hover:bg-yellow-800 hover:text-yellow-700 dark:hover:text-yellow-600;
}
@apply text-n-amber-11 hover:bg-n-amber-4;
}
&:active {
&.secondary {
@apply active:bg-slate-100 dark:active:bg-slate-900;
@apply active:bg-n-slate-3 dark:active:bg-n-slate-7;
}
}
&:focus {
&.secondary {
@apply focus:bg-slate-50 dark:focus:bg-slate-700;
@apply focus:bg-n-slate-4 dark:focus:bg-n-slate-6;
}
}
}
@@ -3,7 +3,7 @@
}
.tabs--container--with-border {
@apply border-b border-slate-50 dark:border-slate-800/50;
@apply border-b border-n-weak;
}
.tabs--container--compact.tab--chat-type {
@@ -42,7 +42,7 @@
@apply flex-shrink-0 my-0 mx-2;
.badge {
@apply bg-slate-50 dark:bg-slate-800 rounded-md text-slate-600 dark:text-slate-100 h-5 flex items-center justify-center text-xxs font-semibold my-0 mx-1 px-1 py-0;
@apply bg-n-alpha-black2 dark:bg-n-solid-3 rounded-md text-n-slate-11 h-5 flex items-center justify-center text-xxs font-semibold my-0 mx-1 px-1 py-0;
}
&:first-child {
@@ -56,22 +56,22 @@
&:hover,
&:focus {
a {
@apply text-slate-800 dark:text-slate-100;
@apply text-n-slate-12;
}
}
a {
@apply flex items-center flex-row border-b py-2.5 select-none cursor-pointer border-transparent text-slate-500 dark:text-slate-200 text-sm top-[1px] relative;
@apply flex items-center flex-row border-b py-2.5 select-none cursor-pointer border-transparent text-n-slate-11 text-sm top-[1px] relative;
transition: border-color 0.15s $swift-ease-out-function;
}
&.is-active {
a {
@apply border-b border-woot-500 text-woot-500 dark:text-woot-500;
@apply border-b border-n-brand text-n-blue-text;
}
.badge {
@apply bg-woot-50 dark:bg-woot-500 text-woot-500 dark:text-woot-50 dark:bg-opacity-40;
@apply bg-n-brand/10 dark:bg-n-brand/20 text-n-blue-text;
}
}
}
@@ -98,7 +98,7 @@ const inboxIcon = computed(() => {
</span>
</div>
<div
v-dompurify-html="formatMessage(message)"
v-dompurify-html="formatMessage(message, false, false, false)"
class="text-sm text-n-slate-11 line-clamp-1 [&>p]:mb-0 h-6"
/>
<div class="flex items-center w-full h-6 gap-2 overflow-hidden">
@@ -18,6 +18,11 @@ const route = useRoute();
const showDropdown = ref(false);
// Store the currently hovered label's ID
// Using JS state management instead of CSS :hover / group hover
// This will solve the flickering issue when hovering over the last label item
const hoveredLabel = ref(null);
const allLabels = useMapGetter('labels/getLabels');
const contactLabels = useMapGetter('contactLabels/getContactLabels');
@@ -37,7 +42,7 @@ const labelMenuItems = computed(() => {
isSelected: savedLabels.value.some(
savedLabel => savedLabel.id === label.id
),
action: 'addLabel',
action: 'contactLabel',
}))
.toSorted((a, b) => Number(a.isSelected) - Number(b.isSelected));
});
@@ -49,7 +54,7 @@ const fetchLabels = async contactId => {
store.dispatch('contactLabels/get', contactId);
};
const handleLabelAction = async ({ action, value }) => {
const handleLabelAction = async ({ value }) => {
try {
// Get current label titles
const currentLabels = savedLabels.value.map(label => label.title);
@@ -59,16 +64,15 @@ const handleLabelAction = async ({ action, value }) => {
if (!selectedLabel) return;
let updatedLabels;
if (action === 'addLabel') {
// If label is already selected, remove it (toggle behavior)
if (currentLabels.includes(selectedLabel.title)) {
updatedLabels = currentLabels.filter(
labelTitle => labelTitle !== selectedLabel.title
);
} else {
// Add the new label
updatedLabels = [...currentLabels, selectedLabel.title];
}
// If label is already selected, remove it (toggle behavior)
if (currentLabels.includes(selectedLabel.title)) {
updatedLabels = currentLabels.filter(
labelTitle => labelTitle !== selectedLabel.title
);
} else {
// Add the new label
updatedLabels = [...currentLabels, selectedLabel.title];
}
await store.dispatch('contactLabels/update', {
@@ -82,6 +86,10 @@ const handleLabelAction = async ({ action, value }) => {
}
};
const handleRemoveLabel = labelId => {
return handleLabelAction({ value: labelId });
};
watch(
() => props.contactId,
(newVal, oldVal) => {
@@ -95,11 +103,31 @@ onMounted(() => {
fetchLabels(route.params.contactId);
}
});
const handleMouseLeave = () => {
// Reset hover state when mouse leaves the container
// This ensures all labels return to their default state
hoveredLabel.value = null;
};
const handleLabelHover = labelId => {
// Added this to prevent flickering on when showing remove button on hover
// If the label item is at end of the line, it will show the remove button
// when hovering over the last label item
hoveredLabel.value = labelId;
};
</script>
<template>
<div class="flex flex-wrap items-center gap-2">
<LabelItem v-for="label in savedLabels" :key="label.id" :label="label" />
<div class="flex flex-wrap items-center gap-2" @mouseleave="handleMouseLeave">
<LabelItem
v-for="label in savedLabels"
:key="label.id"
:label="label"
:is-hovered="hoveredLabel === label.id"
@remove="handleRemoveLabel"
@hover="handleLabelHover(label.id)"
/>
<AddLabel
:label-menu-items="labelMenuItems"
@update-label="handleLabelAction"
@@ -1,7 +1,7 @@
<script setup>
import { computed, reactive, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { required, email, minLength } from '@vuelidate/validators';
import { required, email } from '@vuelidate/validators';
import { useVuelidate } from '@vuelidate/core';
import { splitName } from '@chatwoot/utils';
import countries from 'shared/constants/countries.js';
@@ -35,7 +35,7 @@ const FORM_CONFIG = {
EMAIL_ADDRESS: { field: 'email' },
PHONE_NUMBER: { field: 'phoneNumber' },
CITY: { field: 'additionalAttributes.city' },
COUNTRY: { field: 'additionalAttributes.country' },
COUNTRY: { field: 'additionalAttributes.countryCode' },
BIO: { field: 'additionalAttributes.description' },
COMPANY_NAME: { field: 'additionalAttributes.companyName' },
};
@@ -74,7 +74,7 @@ const defaultState = {
const state = reactive({ ...defaultState });
const validationRules = {
firstName: { required, minLength: minLength(2) },
firstName: { required },
email: { email },
};
@@ -94,7 +94,7 @@ const prepareStateBasedOnProps = () => {
phoneNumber,
additionalAttributes = {},
} = props.contactData || {};
const { firstName, lastName } = splitName(name);
const { firstName, lastName } = splitName(name || '');
const {
description = '',
companyName = '',
@@ -123,7 +123,7 @@ const prepareStateBasedOnProps = () => {
};
const countryOptions = computed(() =>
countries.map(({ name }) => ({ label: name, value: name }))
countries.map(({ name, id }) => ({ label: name, value: id }))
);
const editDetailsForm = computed(() =>
@@ -205,8 +205,8 @@ const getMessageType = key => {
};
const handleCountrySelection = value => {
const selectedCountry = countries.find(option => option.name === value);
state.additionalAttributes.countryCode = selectedCountry?.id || '';
const selectedCountry = countries.find(option => option.id === value);
state.additionalAttributes.country = selectedCountry?.name || '';
emit('update', state);
};
@@ -242,7 +242,7 @@ defineExpose({
<template v-for="item in editDetailsForm" :key="item.key">
<ComboBox
v-if="item.key === 'COUNTRY'"
v-model="state.additionalAttributes.country"
v-model="state.additionalAttributes.countryCode"
:options="countryOptions"
:placeholder="item.placeholder"
class="[&>div>button]:h-8"
@@ -59,6 +59,7 @@ defineExpose({ dialogRef, contactsFormRef, onSuccess });
t('CONTACTS_LAYOUT.HEADER.ACTIONS.CONTACT_CREATION.SAVE_CONTACT')
"
color="blue"
:disabled="contactsFormRef?.isFormInvalid"
:is-loading="isCreatingContact"
@click="handleDialogConfirm"
/>
@@ -2,6 +2,7 @@
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMapGetter } from 'dashboard/composables/store';
import { useUISettings } from 'dashboard/composables/useUISettings';
import ContactCustomAttributeItem from 'dashboard/components-next/Contacts/ContactsSidebar/ContactCustomAttributeItem.vue';
@@ -14,6 +15,8 @@ const props = defineProps({
const { t } = useI18n();
const { uiSettings } = useUISettings();
const searchQuery = ref('');
const contactAttributes = useMapGetter('attributes/getContactAttributes') || [];
@@ -46,20 +49,49 @@ const processContactAttributes = (
}, []);
};
const sortAttributesOrder = computed(
() =>
uiSettings.value.conversation_elements_order_conversation_contact_panel ??
[]
);
const sortByUISettings = attributes => {
// Get saved order from UI settings
// Same as conversation panel contact attribute order
const order = sortAttributesOrder.value;
// If no order defined, return original array
if (!order?.length) return attributes;
const orderMap = new Map(order.map((key, index) => [key, index]));
// Sort attributes based on their position in saved order
return [...attributes].sort((a, b) => {
// Get positions, use Infinity if not found in order (pushes to end)
const aPos = orderMap.get(a.attributeKey) ?? Infinity;
const bPos = orderMap.get(b.attributeKey) ?? Infinity;
return aPos - bPos;
});
};
const usedAttributes = computed(() => {
return processContactAttributes(
const attributes = processContactAttributes(
contactAttributes.value,
props.selectedContact?.customAttributes,
(key, custom) => key in custom
);
return sortByUISettings(attributes);
});
const unusedAttributes = computed(() => {
return processContactAttributes(
const attributes = processContactAttributes(
contactAttributes.value,
props.selectedContact?.customAttributes,
(key, custom) => !(key in custom)
);
return sortByUISettings(attributes);
});
const filteredUnusedAttributes = computed(() => {
@@ -29,7 +29,7 @@ const getWrittenBy = note => {
const isCurrentUser = note?.user?.id === currentUser.value.id;
return isCurrentUser
? t('CONTACTS_LAYOUT.SIDEBAR.NOTES.YOU')
: note.user.name;
: note?.user?.name || 'Bot';
};
const onAdd = content => {
@@ -33,8 +33,8 @@ const handleDelete = () => {
<div class="flex items-center justify-between">
<div class="flex items-center gap-1.5 py-2.5 min-w-0">
<Avatar
:name="note.user.name"
:src="note.user.thumbnail"
:name="note?.user?.name || 'Bot'"
:src="note?.user?.thumbnail || '/assets/images/chatwoot_bot.png'"
:size="16"
rounded-full
/>
@@ -21,7 +21,7 @@ const lastNonActivityMessageContent = computed(() => {
props.conversation;
const { email: { subject } = {} } = customAttributes;
return getPlainText(
subject || lastNonActivityMessage.content || t('CHAT_LIST.NO_CONTENT')
subject || lastNonActivityMessage?.content || t('CHAT_LIST.NO_CONTENT')
);
});
@@ -1,5 +1,5 @@
<script setup>
import { computed } from 'vue';
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessageFormatter } from 'shared/composables/useMessageFormatter';
@@ -20,6 +20,8 @@ const props = defineProps({
const { t } = useI18n();
const slaCardLabelRef = ref(null);
const { getPlainText } = useMessageFormatter();
const lastNonActivityMessageContent = computed(() => {
@@ -27,7 +29,7 @@ const lastNonActivityMessageContent = computed(() => {
props.conversation;
const { email: { subject } = {} } = customAttributes;
return getPlainText(
subject || lastNonActivityMessage.content || t('CHAT_LIST.NO_CONTENT')
subject || lastNonActivityMessage?.content || t('CHAT_LIST.NO_CONTENT')
);
});
@@ -45,7 +47,15 @@ const unreadMessagesCount = computed(() => {
return unreadCount;
});
const hasSlaThreshold = computed(() => props.conversation?.slaPolicyId);
const hasSlaThreshold = computed(() => {
return (
slaCardLabelRef.value?.hasSlaThreshold && props.conversation?.slaPolicyId
);
});
defineExpose({
hasSlaThreshold,
});
</script>
<template>
@@ -73,7 +83,11 @@ const hasSlaThreshold = computed(() => props.conversation?.slaPolicyId);
: 'grid-cols-[1fr_20px]'
"
>
<SLACardLabel v-if="hasSlaThreshold" :conversation="conversation" />
<SLACardLabel
v-show="hasSlaThreshold"
ref="slaCardLabelRef"
:conversation="conversation"
/>
<div v-if="hasSlaThreshold" class="w-px h-3 bg-n-slate-4" />
<div class="overflow-hidden">
<CardLabels
@@ -1,5 +1,5 @@
<script setup>
import { computed } from 'vue';
import { computed, ref } from 'vue';
import { getInboxIconByType } from 'dashboard/helper/inbox';
import { useRouter, useRoute } from 'vue-router';
import { frontendURL, conversationUrl } from 'dashboard/helper/URLHelper.js';
@@ -33,6 +33,8 @@ const props = defineProps({
const router = useRouter();
const route = useRoute();
const cardMessagePreviewWithMetaRef = ref(null);
const currentContact = computed(() => props.contact);
const currentContactName = computed(() => currentContact.value?.name);
@@ -56,8 +58,10 @@ const lastActivityAt = computed(() => {
});
const showMessagePreviewWithoutMeta = computed(() => {
const { slaPolicyId, labels = [] } = props.conversation;
return !slaPolicyId && labels.length === 0;
const { labels = [] } = props.conversation;
return (
!cardMessagePreviewWithMetaRef.value?.hasSlaThreshold && labels.length === 0
);
});
const onCardClick = e => {
@@ -82,6 +86,7 @@ const onCardClick = e => {
<template>
<div
role="button"
class="flex w-full gap-3 px-3 py-4 transition-all duration-300 ease-in-out cursor-pointer"
@click="onCardClick"
>
@@ -92,7 +97,7 @@ const onCardClick = e => {
:status="currentContactStatus"
rounded-full
/>
<div class="flex flex-col w-full gap-1">
<div class="flex flex-col w-full gap-1 min-w-0">
<div class="flex items-center justify-between h-6 gap-2">
<h4 class="text-base font-medium truncate text-n-slate-12">
{{ currentContactName }}
@@ -114,11 +119,12 @@ const onCardClick = e => {
</div>
</div>
<CardMessagePreview
v-if="showMessagePreviewWithoutMeta"
v-show="showMessagePreviewWithoutMeta"
:conversation="conversation"
/>
<CardMessagePreviewWithMeta
v-else
v-show="!showMessagePreviewWithoutMeta"
ref="cardMessagePreviewWithMetaRef"
:conversation="conversation"
:account-labels="accountLabels"
/>
@@ -31,13 +31,17 @@ const convertObjectCamelCaseToSnakeCase = object => {
const appliedSLA = computed(() => props.conversation?.appliedSla);
const isSlaMissed = computed(() => slaStatus.value?.isSlaMissed);
const hasSlaThreshold = computed(() => {
return slaStatus.value?.threshold && appliedSLA.value?.id;
});
const slaStatusText = computed(() => {
return slaStatus.value?.type?.toUpperCase();
});
const updateSlaStatus = () => {
slaStatus.value = evaluateSLAStatus({
appliedSla: convertObjectCamelCaseToSnakeCase(appliedSLA.value),
appliedSla: convertObjectCamelCaseToSnakeCase(appliedSLA.value || {}),
chat: props.conversation,
});
};
@@ -61,6 +65,21 @@ onUnmounted(() => {
});
watch(() => props.conversation, updateSlaStatus);
// This expose is to provide context to the parent component, so that it can decided weather
// a new row has to be added to the conversation card or not
// SLACardLabel > CardMessagePreviewWithMeta > ConversationCard
//
// We need to do this becuase each SLA card has it's own SLA timer
// and it's just convenient to have this logic in the SLACardLabel component
// However this is a bit hacky, and we should change this in the future
//
// TODO: A better implementation would be to have the timer as a shared composable, just like the provider pattern
// we use across the next components. Have the calculation be done on the top ConversationCard component
// and then the value be injected to the SLACardLabel component
defineExpose({
hasSlaThreshold,
});
</script>
<template>
@@ -41,6 +41,8 @@ const props = defineProps({
default: 'info',
validator: value => ['info', 'error', 'success'].includes(value),
},
enableVariables: { type: Boolean, default: false },
enableCannedResponses: { type: Boolean, default: true },
});
const emit = defineEmits(['update:modelValue']);
@@ -116,6 +118,8 @@ watch(
:placeholder="placeholder"
:focus-on-mount="focusOnMount"
:disabled="disabled"
:enable-variables="enableVariables"
:enable-canned-responses="enableCannedResponses"
@input="handleInput"
@focus="handleFocus"
@blur="handleBlur"
@@ -1,4 +1,6 @@
<script setup>
import Policy from 'dashboard/components/policy.vue';
defineProps({
title: {
type: String,
@@ -8,6 +10,10 @@ defineProps({
type: String,
required: true,
},
actionPerms: {
type: Array,
default: () => [],
},
});
</script>
@@ -16,7 +22,7 @@ defineProps({
class="relative flex flex-col items-center justify-center w-full h-full overflow-hidden"
>
<div
class="relative w-full max-w-[940px] mx-auto overflow-hidden h-full max-h-[448px]"
class="relative w-full max-w-[960px] mx-auto overflow-hidden h-full max-h-[448px]"
>
<div
class="w-full h-full space-y-4 overflow-y-hidden opacity-50 pointer-events-none"
@@ -39,7 +45,9 @@ defineProps({
{{ subtitle }}
</p>
</div>
<slot name="actions" />
<Policy :permissions="actionPerms">
<slot name="actions" />
</Policy>
</div>
</div>
</div>
@@ -60,7 +60,7 @@ const togglePortalSwitcher = () => {
<template>
<section class="flex flex-col w-full h-full overflow-hidden bg-n-background">
<header class="sticky top-0 z-10 px-6 pb-3 lg:px-0">
<div class="w-full max-w-[960px] mx-auto">
<div class="w-full max-w-[960px] mx-auto lg:px-6">
<div
v-if="showHeaderTitle"
class="flex items-center justify-start h-20 gap-2"
@@ -96,7 +96,7 @@ const togglePortalSwitcher = () => {
</div>
</header>
<main class="flex-1 px-6 overflow-y-auto lg:px-0">
<div class="w-full max-w-[960px] mx-auto py-3">
<div class="w-full max-w-[960px] mx-auto py-3 lg:px-6">
<slot name="content" />
</div>
</main>
@@ -36,6 +36,8 @@ const emit = defineEmits([
const { t } = useI18n();
const isNewArticle = computed(() => !props.article?.id);
const saveAndSync = value => {
emit('saveArticle', value);
};
@@ -52,21 +54,32 @@ const quickSave = debounce(
// 2.5 seconds is enough to know that the user has stopped typing and is taking a pause
// so we can save the data to the backend and retrieve the updated data
// this will update the local state with response data
// Only use to save for existing articles
const saveAndSyncDebounced = debounce(saveAndSync, 2500, false);
// Debounced save for new articles
const quickSaveNewArticle = debounce(saveAndSync, 400, false);
const handleSave = value => {
if (isNewArticle.value) {
quickSaveNewArticle(value);
} else {
quickSave(value);
saveAndSyncDebounced(value);
}
};
const articleTitle = computed({
get: () => props.article.title,
set: value => {
quickSave({ title: value });
saveAndSyncDebounced({ title: value });
handleSave({ title: value });
},
});
const articleContent = computed({
get: () => props.article.content,
set: content => {
quickSave({ content });
saveAndSyncDebounced({ content });
handleSave({ content });
},
});
@@ -200,7 +200,8 @@ onMounted(() => {
<DropdownMenu
v-if="openAgentsList && hasAgentList"
:menu-items="agentList"
class="z-[100] w-48 mt-2 overflow-y-auto ltr:left-0 rtl:right-0 top-full max-h-52"
show-search
class="z-[100] w-48 mt-2 overflow-y-auto ltr:left-0 rtl:right-0 top-full max-h-60"
@action="handleArticleAction"
/>
</OnClickOutside>
@@ -231,7 +232,8 @@ onMounted(() => {
<DropdownMenu
v-if="openCategoryList && hasCategoryMenuItems"
:menu-items="categoryList"
class="w-48 mt-2 z-[100] overflow-y-auto left-0 top-full max-h-52"
show-search
class="w-48 mt-2 z-[100] overflow-y-auto left-0 top-full max-h-60"
@action="handleArticleAction"
/>
</OnClickOutside>
@@ -3,6 +3,7 @@ import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import { OnClickOutside } from '@vueuse/components';
import { useUISettings } from 'dashboard/composables/useUISettings';
import {
ARTICLE_TABS,
CATEGORY_ALL,
@@ -37,6 +38,7 @@ const emit = defineEmits([
const route = useRoute();
const { t } = useI18n();
const { updateUISettings } = useUISettings();
const isCategoryMenuOpen = ref(false);
const isLocaleMenuOpen = ref(false);
@@ -111,13 +113,12 @@ const localeMenuItems = computed(() => {
}));
});
const hasMoreThanOneLocaleMenuItems = computed(() => {
return localeMenuItems.value?.length > 1;
});
const handleLocaleAction = ({ value }) => {
emit('localeChange', value);
isLocaleMenuOpen.value = false;
updateUISettings({
last_active_locale_code: value,
});
};
const handleCategoryAction = ({ value }) => {
@@ -143,7 +144,7 @@ const handleTabChange = value => {
/>
<div class="flex items-start justify-between w-full gap-2">
<div class="flex items-center gap-2">
<div v-if="hasMoreThanOneLocaleMenuItems" class="relative group">
<div class="relative group">
<OnClickOutside @trigger="isLocaleMenuOpen = false">
<Button
:label="activeLocaleName"
@@ -157,6 +158,7 @@ const handleTabChange = value => {
<DropdownMenu
v-if="isLocaleMenuOpen"
:menu-items="localeMenuItems"
show-search
class="left-0 w-40 max-w-[300px] mt-2 overflow-y-auto xl:right-0 top-full max-h-60"
@action="handleLocaleAction"
/>
@@ -177,6 +179,7 @@ const handleTabChange = value => {
<DropdownMenu
v-if="isCategoryMenuOpen"
:menu-items="categoryMenuItems"
show-search
class="left-0 w-48 mt-2 overflow-y-auto xl:right-0 top-full max-h-60"
@action="handleCategoryAction"
/>
@@ -99,11 +99,19 @@ const getStatusMessage = (status, isSuccess) => {
: '';
};
const updateMeta = () => {
const updatePortalMeta = () => {
const { portalSlug, locale } = route.params;
return store.dispatch('portals/show', { portalSlug, locale });
};
const updateArticlesMeta = () => {
const { portalSlug, locale } = route.params;
return store.dispatch('articles/updateArticleMeta', {
portalSlug,
locale,
});
};
const handleArticleAction = async (action, { status, id }) => {
const { portalSlug } = route.params;
try {
@@ -127,7 +135,8 @@ const handleArticleAction = async (action, { status, id }) => {
useTrack(PORTALS_EVENTS.PUBLISH_ARTICLE);
}
}
await updateMeta();
await updateArticlesMeta();
await updatePortalMeta();
} catch (error) {
const errorMessage =
error?.message ||
@@ -91,10 +91,7 @@ const articlesCount = computed(() => {
});
const showArticleHeaderControls = computed(
() =>
!hasNoArticlesInPortal.value &&
!props.isCategoryArticles &&
!isSwitchingPortal.value
() => !props.isCategoryArticles && !isSwitchingPortal.value
);
const showCategoryHeaderControls = computed(
@@ -141,6 +141,7 @@ const handleBreadcrumbClick = () => {
<DropdownMenu
v-if="isLocaleMenuOpen"
:menu-items="localeMenuItems"
show-search
class="left-0 w-40 mt-2 overflow-y-auto xl:right-0 top-full max-h-60"
@action="handleLocaleAction"
/>
@@ -49,8 +49,11 @@ const onCreate = async () => {
try {
await store.dispatch('portals/update', {
portalSlug: props.portal.slug,
config: { allowed_locales: updatedLocales },
portalSlug: props.portal?.slug,
config: {
allowed_locales: updatedLocales,
default_locale: props.portal?.meta?.default_locale,
},
});
useTrack(PORTALS_EVENTS.CREATE_LOCALE, {
@@ -2,6 +2,7 @@
import LocaleCard from 'dashboard/components-next/HelpCenter/LocaleCard/LocaleCard.vue';
import { useStore } from 'dashboard/composables/store';
import { useAlert, useTrack } from 'dashboard/composables';
import { useUISettings } from 'dashboard/composables/useUISettings';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import { PORTALS_EVENTS } from 'dashboard/helper/AnalyticsHelper/events';
@@ -20,6 +21,7 @@ const props = defineProps({
const store = useStore();
const { t } = useI18n();
const route = useRoute();
const { uiSettings, updateUISettings } = useUISettings();
const isLocaleDefault = code => {
return props.portal?.meta?.default_locale === code;
@@ -56,26 +58,40 @@ const changeDefaultLocale = ({ localeCode }) => {
defaultLocale: localeCode,
messageKey: 'CHANGE_DEFAULT_LOCALE',
});
useTrack(PORTALS_EVENTS.SET_DEFAULT_LOCALE, {
newLocale: localeCode,
from: route.name,
});
};
const deletePortalLocale = ({ localeCode }) => {
const updateLastActivePortal = async localeCode => {
const { last_active_locale_code: lastActiveLocaleCode } =
uiSettings.value || {};
const defaultLocale = props.portal.meta.default_locale;
// Update UI settings only if deleting locale matches the last active locale in UI settings.
if (localeCode === lastActiveLocaleCode) {
await updateUISettings({
last_active_locale_code: defaultLocale,
});
}
};
const deletePortalLocale = async ({ localeCode }) => {
const updatedLocales = props.locales
.filter(locale => locale.code !== localeCode)
.map(locale => locale.code);
const defaultLocale = props.portal.meta.default_locale;
updatePortalLocales({
await updatePortalLocales({
newAllowedLocales: updatedLocales,
defaultLocale,
messageKey: 'DELETE_LOCALE',
});
await updateLastActivePortal(localeCode);
useTrack(PORTALS_EVENTS.DELETE_LOCALE, {
deletedLocale: localeCode,
from: route.name,
@@ -0,0 +1,248 @@
<script setup>
import { computed, ref, onBeforeMount } from 'vue';
import { useI18n } from 'vue-i18n';
import { getInboxIconByType } from 'dashboard/helper/inbox';
import { dynamicTime, shortTimestamp } from 'shared/helpers/timeHelper';
import {
snoozedReopenTimeToTimestamp,
shortenSnoozeTime,
} from 'dashboard/helper/snoozeHelpers';
import { NOTIFICATION_TYPES_MAPPING } from 'dashboard/routes/dashboard/inbox/helpers/InboxViewHelpers';
import Icon from 'dashboard/components-next/icon/Icon.vue';
import Avatar from 'dashboard/components-next/avatar/Avatar.vue';
import CardPriorityIcon from 'dashboard/components-next/Conversation/ConversationCard/CardPriorityIcon.vue';
import SLACardLabel from 'dashboard/components-next/Conversation/ConversationCard/SLACardLabel.vue';
import InboxContextMenu from 'dashboard/routes/dashboard/inbox/components/InboxContextMenu.vue';
const props = defineProps({
inboxItem: { type: Object, default: () => ({}) },
stateInbox: { type: Object, default: () => ({}) },
});
const emit = defineEmits([
'click',
'contextMenuOpen',
'contextMenuClose',
'markNotificationAsRead',
'markNotificationAsUnRead',
'deleteNotification',
]);
const { t } = useI18n();
const isContextMenuOpen = ref(false);
const contextMenuPosition = ref({ x: null, y: null });
const slaCardLabel = ref(null);
const getMessageClasses = {
emphasis: 'text-sm font-medium text-n-slate-11',
emphasisUnread: 'text-sm font-medium text-n-slate-12',
normal: 'text-sm font-normal text-n-slate-11',
normalUnread: 'text-sm text-n-slate-12',
};
const primaryActor = computed(() => props.inboxItem?.primaryActor);
const meta = computed(() => primaryActor.value?.meta);
const assigneeMeta = computed(() => meta.value?.sender);
const isUnread = computed(() => !props.inboxItem?.readAt);
const inbox = computed(() => props.stateInbox);
const inboxIcon = computed(() => {
const { phoneNumber, channelType } = inbox.value;
return getInboxIconByType(channelType, phoneNumber);
});
const hasSlaThreshold = computed(() => {
return slaCardLabel.value?.hasSlaThreshold && primaryActor.value?.slaPolicyId;
});
const lastActivityAt = computed(() => {
const timestamp = props.inboxItem?.lastActivityAt;
return timestamp ? shortTimestamp(dynamicTime(timestamp)) : '';
});
const menuItems = computed(() => [
{ key: 'delete', label: t('INBOX.MENU_ITEM.DELETE') },
{
key: isUnread.value ? 'mark_as_read' : 'mark_as_unread',
label: t(`INBOX.MENU_ITEM.MARK_AS_${isUnread.value ? 'READ' : 'UNREAD'}`),
},
]);
const messageClasses = computed(() => ({
emphasis: isUnread.value
? getMessageClasses.emphasisUnread
: getMessageClasses.emphasis,
normal: isUnread.value
? getMessageClasses.normalUnread
: getMessageClasses.normal,
}));
const formatPushMessage = message => {
if (message.startsWith(': ')) {
return message.slice(2);
}
return message.replace(/^([^:]+):/g, (match, name) => {
return `<span class="${messageClasses.value.emphasis}">${name}:</span>`;
});
};
const formattedMessage = computed(() => {
const messageContent = `<span class="${messageClasses.value.normal}">${formatPushMessage(props.inboxItem?.pushMessageBody || '')}</span>`;
return isUnread.value
? `<span class="inline-flex flex-shrink-0 w-2 h-2 mb-px rounded-full bg-n-iris-10 ltr:mr-1 rtl:ml-1"></span> ${messageContent}`
: messageContent;
});
const notificationDetails = computed(() => {
const type = props.inboxItem?.notificationType?.toUpperCase() || '';
const [icon = '', color = 'text-n-blue-text'] =
NOTIFICATION_TYPES_MAPPING[type] || [];
return { text: type ? t(`INBOX.TYPES_NEXT.${type}`) : '', icon, color };
});
const snoozedUntilTime = computed(() => {
const { snoozedUntil } = props.inboxItem;
if (!snoozedUntil) return null;
return shortenSnoozeTime(
dynamicTime(snoozedReopenTimeToTimestamp(snoozedUntil))
);
});
const hasLastSnoozed = computed(() => props.inboxItem?.meta?.lastSnoozedAt);
const snoozedText = computed(() => {
return !hasLastSnoozed.value
? t('INBOX.TYPES_NEXT.SNOOZED_UNTIL', {
time: shortTimestamp(snoozedUntilTime.value),
})
: t('INBOX.TYPES_NEXT.SNOOZED_ENDS');
});
const contextMenuActions = {
close: () => {
isContextMenuOpen.value = false;
contextMenuPosition.value = { x: null, y: null };
emit('contextMenuClose');
},
open: e => {
e.preventDefault();
contextMenuPosition.value = {
x: e.pageX || e.clientX,
y: e.pageY || e.clientY,
};
isContextMenuOpen.value = true;
emit('contextMenuOpen');
},
handle: key => {
const actions = {
mark_as_read: () => emit('markNotificationAsRead', props.inboxItem),
mark_as_unread: () => emit('markNotificationAsUnRead', props.inboxItem),
delete: () => emit('deleteNotification', props.inboxItem),
};
actions[key]?.();
},
};
onBeforeMount(contextMenuActions.close);
</script>
<template>
<div
role="button"
class="flex flex-col w-full gap-2 p-3 transition-all duration-300 ease-in-out cursor-pointer"
@contextmenu="contextMenuActions.open($event)"
@click="emit('click')"
>
<div class="flex items-start gap-2">
<Avatar
:name="assigneeMeta.name"
:src="assigneeMeta.thumbnail"
:size="20"
rounded-full
class="mt-1"
/>
<p v-dompurify-html="formattedMessage" class="mb-0 line-clamp-2" />
</div>
<div class="flex items-center justify-between h-6 gap-2">
<div class="flex items-center flex-1 min-w-0 gap-1">
<div
v-if="snoozedUntilTime || hasLastSnoozed"
class="flex items-center w-full min-w-0 gap-2 ltr:pl-1 rtl:pr-1"
>
<Icon
:icon="
!hasLastSnoozed
? 'i-lucide-alarm-clock-plus'
: 'i-lucide-alarm-clock-off'
"
class="flex-shrink-0 size-4"
:class="!isUnread ? 'text-n-slate-11' : 'text-n-blue-text'"
/>
<span
class="text-xs font-medium truncate"
:class="!isUnread ? 'text-n-slate-11' : 'text-n-blue-text'"
>
{{ snoozedText }}
</span>
</div>
<div
v-else-if="notificationDetails.text"
class="flex items-center w-full min-w-0 gap-2 ltr:pl-1 rtl:pr-1"
>
<Icon
:icon="notificationDetails.icon"
:class="isUnread ? notificationDetails.color : 'text-n-slate-11'"
class="flex-shrink-0 size-4"
/>
<span
class="text-xs font-medium truncate"
:class="isUnread ? notificationDetails.color : 'text-n-slate-11'"
>
{{ notificationDetails.text }}
</span>
</div>
</div>
<div class="flex items-center flex-shrink-0 gap-2">
<SLACardLabel
v-show="hasSlaThreshold"
ref="slaCardLabel"
:conversation="primaryActor"
class="[&>span]:text-xs"
:class="
!isUnread && '[&>span]:text-n-slate-11 [&>div>svg]:fill-n-slate-11'
"
/>
<div v-if="hasSlaThreshold" class="w-px h-3 rounded-sm bg-n-slate-4" />
<CardPriorityIcon
v-if="primaryActor?.priority"
:priority="primaryActor?.priority"
class="[&>svg]:size-4"
/>
<div
v-if="inboxIcon"
v-tooltip.left="inbox?.name"
class="flex items-center justify-center flex-shrink-0 rounded-full bg-n-alpha-2 size-4"
>
<Icon
:icon="inboxIcon"
class="flex-shrink-0 text-n-slate-11 size-2.5"
/>
</div>
<span class="text-sm text-n-slate-10">
{{ lastActivityAt }}
</span>
</div>
</div>
<InboxContextMenu
v-if="isContextMenuOpen"
:context-menu-position="contextMenuPosition"
:menu-items="menuItems"
@close="contextMenuActions.close"
@select-action="contextMenuActions.handle"
/>
</div>
</template>
@@ -21,7 +21,7 @@ const showDropdown = ref(false);
<template>
<div class="relative">
<button
class="flex items-center gap-1 px-2 py-1 rounded-md outline-dashed h-[26px] outline-1 outline-n-slate-6 hover:bg-n-alpha-2"
class="flex items-center gap-1 px-2 py-1 rounded-md outline-dashed h-6 outline-1 outline-n-slate-6 hover:bg-n-alpha-2"
:class="{ 'bg-n-alpha-2': showDropdown }"
@click="showDropdown = !showDropdown"
>
@@ -1,22 +1,56 @@
<script setup>
defineProps({
import Button from 'dashboard/components-next/button/Button.vue';
const props = defineProps({
label: {
type: Object,
default: null,
},
isHovered: {
type: Boolean,
default: false,
},
});
const emit = defineEmits(['remove', 'hover']);
const handleRemoveLabel = () => {
emit('remove', props.label?.id);
};
const handleMouseEnter = () => {
// Notify parent component when this label is hovered
// Added this to show the remove button with transition when hovering over the label
// This will solve the flickering issue when hovering over the last label item
emit('hover', props.label?.id);
};
</script>
<template>
<div
class="bg-n-alpha-2 rounded-md flex items-center h-7 w-fit py-1 ltr:pl-1 rtl:pr-1 ltr:pr-1.5 rtl:pl-1.5"
class="flex items-center px-1 py-1 overflow-hidden transition-all duration-300 ease-out rounded-md bg-n-alpha-2 h-7"
@mouseenter="handleMouseEnter"
>
<div
class="w-2 h-2 m-1 rounded-sm"
:style="{ backgroundColor: label.color }"
/>
<span class="text-sm text-n-slate-12">
<span class="text-sm text-n-slate-12 ltr:mr-px rtl:ml-px">
{{ label.title }}
</span>
<div
class="w-0 flex relative ltr:left-1 rtl:right-1 flex-shrink-0 overflow-hidden transition-[width] duration-300 ease-out"
:class="{ 'w-6': isHovered }"
>
<Button
class="transition-opacity duration-200 !h-7 ltr:rounded-r-md rtl:rounded-l-md ltr:rounded-l-none rtl:rounded-r-none w-6 bg-transparent"
:class="{ 'opacity-0': !isHovered, 'opacity-100': isHovered }"
slate
xs
faded
icon="i-lucide-x"
@click="handleRemoveLabel"
/>
</div>
</div>
</template>
@@ -2,6 +2,7 @@
import { ref, computed, onMounted, watch } from 'vue';
import { useStore, useMapGetter } from 'dashboard/composables/store';
import { useI18n } from 'vue-i18n';
import { useUISettings } from 'dashboard/composables/useUISettings';
import { vOnClickOutside } from '@vueuse/components';
import { useAlert } from 'dashboard/composables';
import { ExceptionWithMessage } from 'shared/helpers/CustomErrors';
@@ -30,6 +31,8 @@ const props = defineProps({
const store = useStore();
const { t } = useI18n();
const { fetchSignatureFlagFromUISettings } = useUISettings();
const contacts = ref([]);
const selectedContact = ref(null);
const targetInbox = ref(null);
@@ -43,6 +46,11 @@ const contactsUiFlags = useMapGetter('contacts/getUIFlags');
const currentUser = useMapGetter('getCurrentUser');
const globalConfig = useMapGetter('globalConfig/get');
const uiFlags = useMapGetter('contactConversations/getUIFlags');
const messageSignature = useMapGetter('getMessageSignature');
const sendWithSignature = computed(() =>
fetchSignatureFlagFromUISettings(targetInbox.value?.channelType)
);
const directUploadsEnabled = computed(
() => globalConfig.value.directUploadsEnabled
@@ -181,7 +189,10 @@ useKeyboardEvents(keyboardEvents);
<template>
<div
v-on-click-outside="() => (showComposeNewConversation = false)"
class="relative z-40"
class="relative"
:class="{
'z-40': showComposeNewConversation,
}"
>
<slot
name="trigger"
@@ -202,6 +213,8 @@ useKeyboardEvents(keyboardEvents);
:contact-conversations-ui-flags="uiFlags"
:contacts-ui-flags="contactsUiFlags"
:class="composePopoverClass"
:message-signature="messageSignature"
:send-with-signature="sendWithSignature"
@search-contacts="onContactSearch"
@reset-contact-search="resetContacts"
@update-selected-contact="handleSelectedContact"
@@ -1,6 +1,5 @@
<script setup>
import { defineAsyncComponent, ref, computed } from 'vue';
import { useMapGetter } from 'dashboard/composables/store';
import { defineAsyncComponent, ref, computed, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import { useUISettings } from 'dashboard/composables/useUISettings';
import { useFileUpload } from 'dashboard/composables/useFileUpload';
@@ -8,51 +7,24 @@ import { vOnClickOutside } from '@vueuse/components';
import { ALLOWED_FILE_TYPES } from 'shared/constants/messages';
import { useKeyboardEvents } from 'dashboard/composables/useKeyboardEvents';
import FileUpload from 'vue-upload-component';
import { extractTextFromMarkdown } from 'dashboard/helper/editorHelper';
import Button from 'dashboard/components-next/button/Button.vue';
import WhatsAppOptions from './WhatsAppOptions.vue';
const props = defineProps({
attachedFiles: {
type: Array,
default: () => [],
},
isWhatsappInbox: {
type: Boolean,
default: false,
},
isEmailOrWebWidgetInbox: {
type: Boolean,
default: false,
},
isTwilioSmsInbox: {
type: Boolean,
default: false,
},
messageTemplates: {
type: Array,
default: () => [],
},
channelType: {
type: String,
default: '',
},
isLoading: {
type: Boolean,
default: false,
},
disableSendButton: {
type: Boolean,
default: false,
},
hasNoInbox: {
type: Boolean,
default: false,
},
isDropdownActive: {
type: Boolean,
default: false,
},
attachedFiles: { type: Array, default: () => [] },
isWhatsappInbox: { type: Boolean, default: false },
isEmailOrWebWidgetInbox: { type: Boolean, default: false },
isTwilioSmsInbox: { type: Boolean, default: false },
messageTemplates: { type: Array, default: () => [] },
channelType: { type: String, default: '' },
isLoading: { type: Boolean, default: false },
disableSendButton: { type: Boolean, default: false },
hasSelectedInbox: { type: Boolean, default: false },
hasNoInbox: { type: Boolean, default: false },
isDropdownActive: { type: Boolean, default: false },
messageSignature: { type: String, default: '' },
});
const emit = defineEmits([
@@ -74,8 +46,11 @@ const EmojiInput = defineAsyncComponent(
() => import('shared/components/emoji/EmojiInput.vue')
);
const messageSignature = useMapGetter('getMessageSignature');
const signatureToApply = computed(() => messageSignature.value);
const signatureToApply = computed(() =>
props.isEmailOrWebWidgetInbox
? props.messageSignature
: extractTextFromMarkdown(props.messageSignature)
);
const {
fetchSignatureFlagFromUISettings,
@@ -87,13 +62,9 @@ const sendWithSignature = computed(() => {
return fetchSignatureFlagFromUISettings(props.channelType);
});
const isSignatureEnabledForInbox = computed(() => {
return props.isEmailOrWebWidgetInbox && sendWithSignature.value;
});
const setSignature = () => {
if (signatureToApply.value) {
if (isSignatureEnabledForInbox.value) {
if (sendWithSignature.value) {
emit('addSignature', signatureToApply.value);
} else {
emit('removeSignature', signatureToApply.value);
@@ -106,6 +77,18 @@ const toggleMessageSignature = () => {
setSignature();
};
// Added this watch to dynamically set signature.
// Only targetInbox has value and is Advance Editor(used by isEmailOrWebWidgetInbox)
// Set the signature only if the inbox based flag is true
watch(
() => props.hasSelectedInbox,
newValue => {
nextTick(() => {
if (newValue && props.isEmailOrWebWidgetInbox) setSignature();
});
}
);
const onClickInsertEmoji = emoji => {
emit('insertEmoji', emoji);
};
@@ -213,7 +196,7 @@ useKeyboardEvents(keyboardEvents);
/>
</FileUpload>
<Button
v-if="isEmailOrWebWidgetInbox"
v-if="hasSelectedInbox && !isWhatsappInbox"
icon="i-lucide-signature"
color="slate"
size="sm"
@@ -6,6 +6,7 @@ import { INBOX_TYPES } from 'dashboard/helper/inbox';
import {
appendSignature,
removeSignature,
extractTextFromMarkdown,
} from 'dashboard/helper/editorHelper';
import {
buildContactableInboxesList,
@@ -33,6 +34,8 @@ const props = defineProps({
isDirectUploadsEnabled: { type: Boolean, default: false },
contactConversationsUiFlags: { type: Object, default: null },
contactsUiFlags: { type: Object, default: null },
messageSignature: { type: String, default: '' },
sendWithSignature: { type: Boolean, default: false },
});
const emit = defineEmits([
@@ -184,6 +187,14 @@ const handleInboxAction = ({ value, action, ...rest }) => {
const removeTargetInbox = value => {
v$.value.$reset();
// Remove the signature from message content
// Based on the Advance Editor (used in isEmailOrWebWidget) and Plain editor(all other inboxes except WhatsApp)
if (props.sendWithSignature) {
const signatureToRemove = inboxTypes.value.isEmailOrWebWidget
? props.messageSignature
: extractTextFromMarkdown(props.messageSignature);
state.message = removeSignature(state.message, signatureToRemove);
}
emit('updateTargetInbox', value);
state.attachedFiles = [];
};
@@ -302,6 +313,8 @@ const handleSendWhatsappMessage = async ({ message, templateParams }) => {
<MessageEditor
v-if="!inboxTypes.isWhatsapp && !showNoInboxAlert"
v-model="state.message"
:message-signature="messageSignature"
:send-with-signature="sendWithSignature"
:is-email-or-web-widget-inbox="inboxTypes.isEmailOrWebWidget"
:has-errors="validationStates.isMessageInvalid"
:has-attachments="state.attachedFiles.length > 0"
@@ -322,8 +335,10 @@ const handleSendWhatsappMessage = async ({ message, templateParams }) => {
:channel-type="inboxChannelType"
:is-loading="isCreating"
:disable-send-button="isCreating"
:has-selected-inbox="!!targetInbox"
:has-no-inbox="showNoInboxAlert"
:is-dropdown-active="isAnyDropdownActive"
:message-signature="messageSignature"
@insert-emoji="onClickInsertEmoji"
@add-signature="handleAddSignature"
@remove-signature="handleRemoveSignature"
@@ -1,9 +1,11 @@
<script setup>
import { computed } from 'vue';
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { INPUT_TYPES } from 'dashboard/components-next/taginput/helper/tagInputHelper.js';
import TagInput from 'dashboard/components-next/taginput/TagInput.vue';
import Button from 'dashboard/components-next/button/Button.vue';
const props = defineProps({
contacts: {
type: Array,
@@ -42,15 +44,19 @@ const props = defineProps({
default: false,
},
});
const emit = defineEmits([
'searchContacts',
'setSelectedContact',
'clearSelectedContact',
'updateDropdown',
]);
const i18nPrefix = 'COMPOSE_NEW_CONVERSATION.FORM.CONTACT_SELECTOR';
const { t } = useI18n();
const inputType = ref(INPUT_TYPES.EMAIL);
const contactsList = computed(() => {
return props.contacts?.map(({ name, id, thumbnail, email, ...rest }) => ({
id,
@@ -80,6 +86,14 @@ const errorClass = computed(() => {
? '[&_input]:placeholder:!text-n-ruby-9 [&_input]:dark:placeholder:!text-n-ruby-9'
: '';
});
const handleInput = value => {
// Update input type based on whether input starts with '+'
// If it does, set input type to 'tel'
// Otherwise, set input type to 'email'
inputType.value = value.startsWith('+') ? INPUT_TYPES.TEL : INPUT_TYPES.EMAIL;
emit('searchContacts', value);
};
</script>
<template>
@@ -126,11 +140,11 @@ const errorClass = computed(() => {
:is-loading="isLoading"
:disabled="contactableInboxesList?.length > 0 && showInboxesDropdown"
allow-create
type="email"
:type="inputType"
class="flex-1 min-h-7"
:class="errorClass"
focus-on-mount
@input="emit('searchContacts', $event)"
@input="handleInput"
@on-click-outside="emit('updateDropdown', 'contacts', false)"
@add="emit('setSelectedContact', $event)"
@remove="emit('clearSelectedContact')"
@@ -1,22 +1,22 @@
<script setup>
import { ref, watch, computed, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import {
appendSignature,
extractTextFromMarkdown,
removeSignature,
} from 'dashboard/helper/editorHelper';
import Editor from 'dashboard/components-next/Editor/Editor.vue';
import TextArea from 'dashboard/components-next/textarea/TextArea.vue';
import CannedResponse from 'dashboard/components/widgets/conversation/CannedResponse.vue';
defineProps({
isEmailOrWebWidgetInbox: {
type: Boolean,
required: true,
},
hasErrors: {
type: Boolean,
default: false,
},
hasAttachments: {
type: Boolean,
default: false,
},
const props = defineProps({
isEmailOrWebWidgetInbox: { type: Boolean, required: true },
hasErrors: { type: Boolean, default: false },
hasAttachments: { type: Boolean, default: false },
sendWithSignature: { type: Boolean, default: false },
messageSignature: { type: String, default: '' },
});
const { t } = useI18n();
@@ -25,41 +25,98 @@ const modelValue = defineModel({
type: String,
default: '',
});
const state = ref({
hasSlashCommand: false,
showMentions: false,
mentionSearchKey: '',
});
const plainTextSignature = computed(() =>
extractTextFromMarkdown(props.messageSignature)
);
watch(
modelValue,
newValue => {
if (props.isEmailOrWebWidgetInbox) return;
const bodyWithoutSignature = newValue
? removeSignature(newValue, plainTextSignature.value)
: '';
// Check if message starts with slash
const startsWithSlash = bodyWithoutSignature.startsWith('/');
// Update slash command and mentions state
state.value = {
...state.value,
hasSlashCommand: startsWithSlash,
showMentions: startsWithSlash,
mentionSearchKey: startsWithSlash ? bodyWithoutSignature.slice(1) : '',
};
},
{ immediate: true }
);
const hideMention = () => {
state.value.showMentions = false;
};
const replaceText = async message => {
// Only append signature on replace if sendWithSignature is true
const finalMessage = props.sendWithSignature
? appendSignature(message, plainTextSignature.value)
: message;
await nextTick();
modelValue.value = finalMessage;
};
</script>
<template>
<div
v-if="isEmailOrWebWidgetInbox"
class="flex-1 h-full"
:class="!hasAttachments && 'min-h-[200px]'"
>
<Editor
v-model="modelValue"
: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="
hasErrors
? '[&_.empty-node]:before:!text-n-ruby-9 [&_.empty-node]:dark:before:!text-n-ruby-9'
: ''
"
:show-character-count="false"
/>
</div>
<div v-else class="flex-1 h-full" :class="!hasAttachments && 'min-h-[200px]'">
<TextArea
v-model="modelValue"
:placeholder="
t('COMPOSE_NEW_CONVERSATION.FORM.MESSAGE_EDITOR.PLACEHOLDER')
"
class="!px-0 [&>div]:!px-4 [&>div]:!border-transparent [&>div]:!bg-transparent"
auto-height
:custom-text-area-class="
hasErrors
? 'placeholder:!text-n-ruby-9 dark:placeholder:!text-n-ruby-9'
: ''
"
/>
<div class="flex-1 h-full" :class="[!hasAttachments && 'min-h-[200px]']">
<template v-if="isEmailOrWebWidgetInbox">
<Editor
v-model="modelValue"
: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="
hasErrors
? '[&_.empty-node]:before:!text-n-ruby-9 [&_.empty-node]:dark:before:!text-n-ruby-9'
: ''
"
enable-variables
:show-character-count="false"
/>
</template>
<template v-else>
<TextArea
v-model="modelValue"
:placeholder="
t('COMPOSE_NEW_CONVERSATION.FORM.MESSAGE_EDITOR.PLACEHOLDER')
"
class="!px-0 [&>div]:!px-4 [&>div]:!border-transparent [&>div]:!bg-transparent"
:custom-text-area-class="
hasErrors
? 'placeholder:!text-n-ruby-9 dark:placeholder:!text-n-ruby-9'
: ''
"
auto-height
allow-signature
:signature="messageSignature"
:send-with-signature="sendWithSignature"
>
<CannedResponse
v-if="state.showMentions && state.hasSlashCommand"
v-on-clickaway="hideMention"
class="normal-editor__canned-box"
:search-key="state.mentionSearchKey"
@replace="replaceText"
/>
</TextArea>
</template>
</div>
</template>
@@ -193,10 +193,12 @@ export const searchContacts = async ({ keys, query }) => {
return filteredPayload || [];
};
export const createNewContact = async email => {
export const createNewContact = async input => {
const payload = {
name: getCapitalizedNameFromEmail(email),
email,
name: input.startsWith('+')
? input.slice(1) // Remove the '+' prefix if it exists
: getCapitalizedNameFromEmail(input),
...(input.startsWith('+') ? { phone_number: input } : { email: input }),
};
const {
@@ -429,6 +429,28 @@ describe('composeConversationHelper', () => {
email: 'john@example.com',
});
});
it('creates new contact with phone number', async () => {
const mockContact = {
id: 1,
name: '919999999999',
phone_number: '+919999999999',
};
ContactAPI.create.mockResolvedValue({
data: { payload: { contact: mockContact } },
});
const result = await helpers.createNewContact('+919999999999');
expect(result).toEqual({
id: 1,
name: '919999999999',
phoneNumber: '+919999999999',
});
expect(ContactAPI.create).toHaveBeenCalledWith({
name: '919999999999',
phone_number: '+919999999999',
});
});
});
describe('fetchContactableInboxes', () => {
@@ -174,7 +174,7 @@ watch(
</script>
<template>
<span class="relative inline-flex group/avatar" :style="containerStyles">
<span class="relative inline-flex group/avatar z-0" :style="containerStyles">
<!-- Status Badge -->
<slot name="badge" :size="size">
<div
@@ -0,0 +1,73 @@
<script setup>
import { computed } from 'vue';
const props = defineProps({
color: {
type: String,
default: 'slate',
validator: value =>
['blue', 'ruby', 'amber', 'slate', 'teal'].includes(value),
},
actionLabel: {
type: String,
default: null,
},
});
const emit = defineEmits(['action']);
const bannerClass = computed(() => {
const classMap = {
slate: 'bg-n-slate-3 border-n-slate-4 text-n-slate-11',
amber: 'bg-n-amber-3 border-n-amber-4 text-n-amber-11',
teal: 'bg-n-teal-3 border-n-teal-4 text-n-teal-11',
ruby: 'bg-n-ruby-3 border-n-ruby-4 text-n-ruby-11',
blue: 'bg-n-blue-3 border-n-blue-4 text-n-blue-11',
};
return classMap[props.color];
});
const buttonClass = computed(() => {
const classMap = {
slate: 'bg-n-slate-4 text-n-slate-11',
amber: 'bg-n-amber-4 text-n-amber-11',
teal: 'bg-n-teal-4 text-n-teal-11',
ruby: 'bg-n-ruby-4 text-n-ruby-11',
blue: 'bg-n-blue-4 text-n-blue-11',
};
return classMap[props.color];
});
const triggerAction = () => {
emit('action');
};
</script>
<template>
<div
class="text-sm rounded-xl flex items-center justify-between gap-2 border"
:class="[
bannerClass,
{
'py-2 px-3': !actionLabel,
'pl-3 p-2': actionLabel,
},
]"
>
<div>
<slot />
</div>
<div>
<button
v-if="actionLabel"
class="px-3 py-1 w-auto grid place-content-center rounded-lg"
:class="buttonClass"
@click="triggerAction"
>
{{ actionLabel }}
</button>
</div>
</div>
</template>
@@ -6,6 +6,7 @@ import Icon from 'dashboard/components-next/icon/Icon.vue';
import {
VARIANT_OPTIONS,
COLOR_OPTIONS,
JUSTIFY_OPTIONS,
SIZE_OPTIONS,
EXCLUDED_ATTRS,
} from './constants.js';
@@ -27,6 +28,11 @@ const props = defineProps({
default: null,
validator: value => SIZE_OPTIONS.includes(value) || value === null,
},
justify: {
type: String,
default: null,
validator: value => JUSTIFY_OPTIONS.includes(value) || value === null,
},
icon: { type: [String, Object, Function], default: '' },
trailingIcon: { type: Boolean, default: false },
isLoading: { type: Boolean, default: false },
@@ -81,6 +87,15 @@ const computedSize = computed(() => {
return 'md';
});
const computedJustify = computed(() => {
if (props.justify) return props.justify;
if (attrs.start || attrs.start === '') return 'start';
if (attrs.center || attrs.center === '') return 'center';
if (attrs.end || attrs.end === '') return 'end';
return 'center';
});
const STYLE_CONFIG = {
colors: {
blue: {
@@ -151,7 +166,12 @@ const STYLE_CONFIG = {
md: 'text-sm font-medium',
lg: 'text-base',
},
base: 'inline-flex items-center justify-center min-w-0 gap-2 transition-all duration-200 ease-in-out border-0 rounded-lg outline-1 outline disabled:cursor-not-allowed disabled:pointer-events-none disabled:opacity-50',
justify: {
start: 'justify-start',
center: 'justify-center',
end: 'justify-end',
},
base: 'inline-flex items-center min-w-0 gap-2 transition-all duration-200 ease-in-out border-0 rounded-lg outline-1 outline disabled:cursor-not-allowed disabled:pointer-events-none disabled:opacity-50',
};
const variantClasses = computed(() => {
@@ -197,6 +217,7 @@ const linkButtonClasses = computed(() => {
[STYLE_CONFIG.base]: true,
[isLink ? linkButtonClasses : buttonClasses]: true,
[STYLE_CONFIG.fontSize[computedSize]]: true,
[STYLE_CONFIG.justify[computedJustify]]: true,
'flex-row-reverse': trailingIcon && !isIconOnly,
}"
>
@@ -1,6 +1,7 @@
export const VARIANT_OPTIONS = ['solid', 'outline', 'faded', 'link', 'ghost'];
export const COLOR_OPTIONS = ['blue', 'ruby', 'amber', 'slate', 'teal'];
export const SIZE_OPTIONS = ['xs', 'sm', 'md', 'lg'];
export const JUSTIFY_OPTIONS = ['start', 'center', 'end'];
export const EXCLUDED_ATTRS = [
'variant',
@@ -12,4 +13,5 @@ export const EXCLUDED_ATTRS = [
...VARIANT_OPTIONS,
...COLOR_OPTIONS,
...SIZE_OPTIONS,
...JUSTIFY_OPTIONS,
];
@@ -0,0 +1,126 @@
<script setup>
import { computed } from 'vue';
import { useAccount } from 'dashboard/composables/useAccount';
import Button from 'dashboard/components-next/button/Button.vue';
import PaginationFooter from 'dashboard/components-next/pagination/PaginationFooter.vue';
import Spinner from 'dashboard/components-next/spinner/Spinner.vue';
import Policy from 'dashboard/components/policy.vue';
const { featureFlag } = defineProps({
currentPage: {
type: Number,
default: 1,
},
totalCount: {
type: Number,
default: 100,
},
itemsPerPage: {
type: Number,
default: 25,
},
headerTitle: {
type: String,
default: '',
},
buttonPolicy: {
type: Array,
default: () => [],
},
buttonLabel: {
type: String,
default: '',
},
featureFlag: {
type: String,
default: '',
},
isFetching: {
type: Boolean,
default: false,
},
isEmpty: {
type: Boolean,
default: false,
},
showPaginationFooter: {
type: Boolean,
default: true,
},
});
const emit = defineEmits(['click', 'close', 'update:currentPage']);
const { isCloudFeatureEnabled } = useAccount();
const showPaywall = computed(() => {
return !isCloudFeatureEnabled(featureFlag);
});
const handleButtonClick = () => {
emit('click');
};
const handlePageChange = event => {
emit('update:currentPage', event);
};
</script>
<template>
<section class="flex flex-col w-full h-full overflow-hidden bg-n-background">
<header class="sticky top-0 z-10 px-6 xl:px-0">
<div class="w-full max-w-[960px] mx-auto">
<div
class="flex items-start lg:items-center justify-between w-full py-6 lg:py-0 lg:h-20 gap-4 lg:gap-2 flex-col lg:flex-row"
>
<span class="text-xl font-medium text-n-slate-12">
{{ headerTitle }}
<slot name="headerTitle" />
</span>
<div
v-if="!showPaywall"
v-on-clickaway="() => emit('close')"
class="relative group/campaign-button"
>
<Policy :permissions="buttonPolicy">
<Button
:label="buttonLabel"
icon="i-lucide-plus"
size="sm"
class="group-hover/campaign-button:brightness-110"
@click="handleButtonClick"
/>
</Policy>
<slot name="action" />
</div>
</div>
</div>
</header>
<main class="flex-1 px-6 overflow-y-auto xl:px-0">
<div class="w-full max-w-[960px] mx-auto py-4">
<slot name="controls" />
<div
v-if="isFetching"
class="flex items-center justify-center py-10 text-n-slate-11"
>
<Spinner />
</div>
<div v-else-if="showPaywall">
<slot name="paywall" />
</div>
<div v-else-if="isEmpty">
<slot name="emptyState" />
</div>
<slot v-else name="body" />
<slot />
</div>
</main>
<footer v-if="showPaginationFooter" class="sticky bottom-0 z-10 px-4 pb-4">
<PaginationFooter
:current-page="currentPage"
:total-items="totalCount"
:items-per-page="itemsPerPage"
@update:current-page="handlePageChange"
/>
</footer>
</section>
</template>
@@ -0,0 +1,27 @@
<script setup>
import AssistantCard from './AssistantCard.vue';
import { assistantsList } from 'dashboard/components-next/captain/pageComponents/emptyStates/captainEmptyStateContent.js';
</script>
<template>
<Story
title="Captain/Assistant/AssistantCard"
:layout="{ type: 'grid', width: '700px' }"
>
<Variant title="Assistant Card">
<div
v-for="(assistant, index) in assistantsList"
:key="index"
class="px-20 py-4 bg-white dark:bg-slate-900"
>
<AssistantCard
:id="assistant.id"
:name="assistant.name"
:description="assistant.description"
:updated-at="assistant.updated_at || assistant.created_at"
:created-at="assistant.created_at"
/>
</div>
</Variant>
</Story>
</template>
@@ -0,0 +1,112 @@
<script setup>
import { computed } from 'vue';
import { useToggle } from '@vueuse/core';
import { useI18n } from 'vue-i18n';
import { dynamicTime } from 'shared/helpers/timeHelper';
import { usePolicy } from 'dashboard/composables/usePolicy';
import CardLayout from 'dashboard/components-next/CardLayout.vue';
import DropdownMenu from 'dashboard/components-next/dropdown-menu/DropdownMenu.vue';
import Button from 'dashboard/components-next/button/Button.vue';
const props = defineProps({
id: {
type: Number,
required: true,
},
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
updatedAt: {
type: Number,
required: true,
},
});
const emit = defineEmits(['action']);
const { checkPermissions } = usePolicy();
const { t } = useI18n();
const [showActionsDropdown, toggleDropdown] = useToggle();
const menuItems = computed(() => {
const allOptions = [
{
label: t('CAPTAIN.ASSISTANTS.OPTIONS.VIEW_CONNECTED_INBOXES'),
value: 'viewConnectedInboxes',
action: 'viewConnectedInboxes',
icon: 'i-lucide-link',
},
];
if (checkPermissions(['administrator'])) {
allOptions.push(
{
label: t('CAPTAIN.ASSISTANTS.OPTIONS.EDIT_ASSISTANT'),
value: 'edit',
action: 'edit',
icon: 'i-lucide-pencil-line',
},
{
label: t('CAPTAIN.ASSISTANTS.OPTIONS.DELETE_ASSISTANT'),
value: 'delete',
action: 'delete',
icon: 'i-lucide-trash',
}
);
}
return allOptions;
});
const lastUpdatedAt = computed(() => dynamicTime(props.updatedAt));
const handleAction = ({ action, value }) => {
toggleDropdown(false);
emit('action', { action, value, id: props.id });
};
</script>
<template>
<CardLayout>
<div class="flex justify-between w-full gap-1">
<span class="text-base text-n-slate-12 line-clamp-1">
{{ name }}
</span>
<div class="flex items-center gap-2">
<div
v-on-clickaway="() => toggleDropdown(false)"
class="relative flex items-center group"
>
<Button
icon="i-lucide-ellipsis-vertical"
color="slate"
size="xs"
class="rounded-md group-hover:bg-n-alpha-2"
@click="toggleDropdown()"
/>
<DropdownMenu
v-if="showActionsDropdown"
:menu-items="menuItems"
class="mt-1 ltr:right-0 rtl:left-0 top-full"
@action="handleAction($event)"
/>
</div>
</div>
</div>
<div class="flex items-center justify-between w-full gap-4">
<span class="text-sm truncate text-n-slate-11">
{{ description || 'Description not available' }}
</span>
<span class="text-sm text-n-slate-11 line-clamp-1 shrink-0">
{{ lastUpdatedAt }}
</span>
</div>
</CardLayout>
</template>
@@ -0,0 +1,27 @@
<script setup>
import DocumentCard from './DocumentCard.vue';
import { documentsList } from 'dashboard/components-next/captain/pageComponents/emptyStates/captainEmptyStateContent.js';
</script>
<template>
<Story
title="Captain/Assistant/DocumentCard"
:layout="{ type: 'grid', width: '700px' }"
>
<Variant title="Document Card">
<div
v-for="(doc, index) in documentsList"
:key="index"
class="px-20 py-4 bg-white dark:bg-slate-900"
>
<DocumentCard
:id="doc.id"
:name="doc.name"
:external-link="doc.external_link"
:assistant="doc.assistant"
:created-at="doc.created_at"
/>
</div>
</Variant>
</Story>
</template>
@@ -0,0 +1,117 @@
<script setup>
import { computed } from 'vue';
import { useToggle } from '@vueuse/core';
import { useI18n } from 'vue-i18n';
import { dynamicTime } from 'shared/helpers/timeHelper';
import { usePolicy } from 'dashboard/composables/usePolicy';
import CardLayout from 'dashboard/components-next/CardLayout.vue';
import DropdownMenu from 'dashboard/components-next/dropdown-menu/DropdownMenu.vue';
import Button from 'dashboard/components-next/button/Button.vue';
const props = defineProps({
id: {
type: Number,
required: true,
},
name: {
type: String,
default: '',
},
assistant: {
type: Object,
default: () => ({}),
},
externalLink: {
type: String,
required: true,
},
createdAt: {
type: Number,
required: true,
},
});
const emit = defineEmits(['action']);
const { checkPermissions } = usePolicy();
const { t } = useI18n();
const [showActionsDropdown, toggleDropdown] = useToggle();
const menuItems = computed(() => {
const allOptions = [
{
label: t('CAPTAIN.DOCUMENTS.OPTIONS.VIEW_RELATED_RESPONSES'),
value: 'viewRelatedQuestions',
action: 'viewRelatedQuestions',
icon: 'i-ph-tree-view-duotone',
},
];
if (checkPermissions(['administrator'])) {
allOptions.push({
label: t('CAPTAIN.DOCUMENTS.OPTIONS.DELETE_DOCUMENT'),
value: 'delete',
action: 'delete',
icon: 'i-lucide-trash',
});
}
return allOptions;
});
const createdAt = computed(() => dynamicTime(props.createdAt));
const handleAction = ({ action, value }) => {
toggleDropdown(false);
emit('action', { action, value, id: props.id });
};
</script>
<template>
<CardLayout>
<div class="flex justify-between w-full gap-1">
<span class="text-base text-n-slate-12 line-clamp-1">
{{ name }}
</span>
<div class="flex items-center gap-2">
<div
v-on-clickaway="() => toggleDropdown(false)"
class="relative flex items-center group"
>
<Button
icon="i-lucide-ellipsis-vertical"
color="slate"
size="xs"
class="rounded-md group-hover:bg-n-alpha-2"
@click="toggleDropdown()"
/>
<DropdownMenu
v-if="showActionsDropdown"
:menu-items="menuItems"
class="mt-1 ltr:right-0 rtl:left-0 xl:ltr:right-0 xl:rtl:left-0 top-full"
@action="handleAction($event)"
/>
</div>
</div>
</div>
<div class="flex items-center justify-between w-full gap-4">
<span
class="text-sm shrink-0 truncate text-n-slate-11 flex items-center gap-1"
>
<i class="i-woot-captain" />
{{ assistant?.name || '' }}
</span>
<span
class="text-n-slate-11 text-sm truncate flex justify-start flex-1 items-center gap-1"
>
<i class="i-ph-link-simple shrink-0" />
<span class="truncate">{{ externalLink }}</span>
</span>
<div class="shrink-0 text-sm text-n-slate-11 line-clamp-1">
{{ createdAt }}
</div>
</div>
</CardLayout>
</template>
@@ -0,0 +1,21 @@
<script setup>
import InboxCard from './InboxCard.vue';
import { inboxes } from 'dashboard/components-next/captain/pageComponents/emptyStates/captainEmptyStateContent.js';
</script>
<template>
<Story
title="Captain/Assistant/InboxCard"
:layout="{ type: 'grid', width: '700px' }"
>
<Variant title="Inbox Card">
<div
v-for="inbox in inboxes"
:key="inbox.id"
class="px-20 py-4 bg-white dark:bg-slate-900"
>
<InboxCard :id="inbox.id" :inbox="inbox" />
</div>
</Variant>
</Story>
</template>
@@ -0,0 +1,102 @@
<script setup>
import { computed } from 'vue';
import { useToggle } from '@vueuse/core';
import { useI18n } from 'vue-i18n';
import CardLayout from 'dashboard/components-next/CardLayout.vue';
import DropdownMenu from 'dashboard/components-next/dropdown-menu/DropdownMenu.vue';
import Button from 'dashboard/components-next/button/Button.vue';
import Policy from 'dashboard/components/policy.vue';
import { INBOX_TYPES, getInboxIconByType } from 'dashboard/helper/inbox';
const props = defineProps({
id: {
type: Number,
required: true,
},
inbox: {
type: Object,
required: true,
},
});
const emit = defineEmits(['action']);
const { t } = useI18n();
const [showActionsDropdown, toggleDropdown] = useToggle();
const inboxName = computed(() => {
const inbox = props.inbox;
if (!inbox?.name) {
return '';
}
const isTwilioChannel = inbox.channel_type === INBOX_TYPES.TWILIO;
const isWhatsAppChannel = inbox.channel_type === INBOX_TYPES.WHATSAPP;
const isEmailChannel = inbox.channel_type === INBOX_TYPES.EMAIL;
if (isTwilioChannel || isWhatsAppChannel) {
const identifier = inbox.messaging_service_sid || inbox.phone_number;
return identifier ? `${inbox.name} (${identifier})` : inbox.name;
}
if (isEmailChannel && inbox.email) {
return `${inbox.name} (${inbox.email})`;
}
return inbox.name;
});
const menuItems = computed(() => [
{
label: t('CAPTAIN.INBOXES.OPTIONS.DISCONNECT'),
value: 'delete',
action: 'delete',
icon: 'i-lucide-trash',
},
]);
const icon = computed(() =>
getInboxIconByType(props.inbox.channel_type, '', 'outline')
);
const handleAction = ({ action, value }) => {
toggleDropdown(false);
emit('action', { action, value, id: props.id });
};
</script>
<template>
<CardLayout>
<div class="flex justify-between w-full gap-1">
<span
class="text-base text-n-slate-12 line-clamp-1 flex items-center gap-2"
>
<span :class="icon" />
{{ inboxName }}
</span>
<div class="flex items-center gap-2">
<Policy
v-on-clickaway="() => toggleDropdown(false)"
:permissions="['administrator']"
class="relative flex items-center group"
>
<Button
icon="i-lucide-ellipsis-vertical"
color="slate"
size="xs"
class="rounded-md group-hover:bg-n-alpha-2"
@click="toggleDropdown()"
/>
<DropdownMenu
v-if="showActionsDropdown"
:menu-items="menuItems"
class="mt-1 ltr:right-0 rtl:left-0 top-full"
@action="handleAction($event)"
/>
</Policy>
</div>
</div>
</CardLayout>
</template>
@@ -0,0 +1,28 @@
<script setup>
import ResponseCard from './ResponseCard.vue';
import { responsesList } from 'dashboard/components-next/captain/pageComponents/emptyStates/captainEmptyStateContent.js';
</script>
<template>
<Story
title="Captain/Assistant/ResponseCard"
:layout="{ type: 'grid', width: '700px' }"
>
<Variant title="Article Card">
<div
v-for="(response, index) in responsesList"
:key="index"
class="px-20 py-4 bg-white dark:bg-slate-900"
>
<ResponseCard
:id="response.id"
:question="response.question"
:answer="response.answer"
:status="response.status"
:assistant="response.assistant"
:created-at="response.created_at"
/>
</div>
</Variant>
</Story>
</template>
@@ -0,0 +1,204 @@
<script setup>
import { computed } from 'vue';
import { useToggle } from '@vueuse/core';
import { useI18n } from 'vue-i18n';
import { dynamicTime } from 'shared/helpers/timeHelper';
import CardLayout from 'dashboard/components-next/CardLayout.vue';
import DropdownMenu from 'dashboard/components-next/dropdown-menu/DropdownMenu.vue';
import Button from 'dashboard/components-next/button/Button.vue';
import Policy from 'dashboard/components/policy.vue';
const props = defineProps({
id: {
type: Number,
required: true,
},
question: {
type: String,
required: true,
},
answer: {
type: String,
required: true,
},
compact: {
type: Boolean,
default: false,
},
status: {
type: String,
default: 'approved',
},
documentable: {
type: Object,
default: null,
},
assistant: {
type: Object,
default: () => ({}),
},
updatedAt: {
type: Number,
required: true,
},
createdAt: {
type: Number,
required: true,
},
});
const emit = defineEmits(['action', 'navigate']);
const { t } = useI18n();
const [showActionsDropdown, toggleDropdown] = useToggle();
const statusAction = computed(() => {
if (props.status === 'pending') {
return [
{
label: t('CAPTAIN.RESPONSES.OPTIONS.APPROVE'),
value: 'approve',
action: 'approve',
icon: 'i-lucide-circle-check-big',
},
];
}
return [];
});
const menuItems = computed(() => [
...statusAction.value,
{
label: t('CAPTAIN.RESPONSES.OPTIONS.EDIT_RESPONSE'),
value: 'edit',
action: 'edit',
icon: 'i-lucide-pencil-line',
},
{
label: t('CAPTAIN.RESPONSES.OPTIONS.DELETE_RESPONSE'),
value: 'delete',
action: 'delete',
icon: 'i-lucide-trash',
},
]);
const timestamp = computed(() =>
dynamicTime(props.updatedAt || props.createdAt)
);
const handleAssistantAction = ({ action, value }) => {
toggleDropdown(false);
emit('action', { action, value, id: props.id });
};
const handleDocumentableClick = () => {
emit('navigate', {
id: props.documentable.id,
type: props.documentable.type,
});
};
</script>
<template>
<CardLayout :class="{ 'rounded-md': compact }">
<div class="flex justify-between w-full gap-1">
<span class="text-base text-n-slate-12 line-clamp-1">
{{ question }}
</span>
<div v-if="!compact" class="flex items-center gap-2">
<Policy
v-on-clickaway="() => toggleDropdown(false)"
:permissions="['administrator']"
class="relative flex items-center group"
>
<Button
icon="i-lucide-ellipsis-vertical"
color="slate"
size="xs"
class="rounded-md group-hover:bg-n-alpha-2"
@click="toggleDropdown()"
/>
<DropdownMenu
v-if="showActionsDropdown"
:menu-items="menuItems"
class="mt-1 ltr:right-0 rtl:right-0 top-full"
@action="handleAssistantAction($event)"
/>
</Policy>
</div>
</div>
<span class="text-n-slate-11 text-sm line-clamp-5">
{{ answer }}
</span>
<div v-if="!compact" class="items-center justify-between hidden lg:flex">
<div class="inline-flex items-center">
<span
class="text-sm shrink-0 truncate text-n-slate-11 inline-flex items-center gap-1"
>
<i class="i-woot-captain" />
{{ assistant?.name || '' }}
</span>
<div
v-if="documentable"
class="shrink-0 text-sm text-n-slate-11 inline-flex line-clamp-1 gap-1 ml-3"
>
<span
v-if="documentable.type === 'Captain::Document'"
class="inline-flex items-center gap-1 truncate over"
>
<i class="i-ph-chat-circle-dots text-base" />
<span class="max-w-96 truncate" :title="documentable.name">
{{ documentable.name }}
</span>
</span>
<span
v-if="documentable.type === 'User'"
class="inline-flex items-center gap-1"
>
<i class="i-ph-user-circle-plus text-base" />
<span
class="max-w-96 truncate"
:title="documentable.available_name"
>
{{ documentable.available_name }}
</span>
</span>
<span
v-else-if="documentable.type === 'Conversation'"
class="inline-flex items-center gap-1 group cursor-pointer"
role="button"
@click="handleDocumentableClick"
>
<i class="i-ph-chat-circle-dots text-base" />
<span class="group-hover:underline">
{{
t(`CAPTAIN.RESPONSES.DOCUMENTABLE.CONVERSATION`, {
id: documentable.display_id,
})
}}
</span>
</span>
<span v-else />
</div>
<div
v-if="status !== 'approved'"
class="shrink-0 text-sm text-n-slate-11 line-clamp-1 inline-flex items-center gap-1 ml-3"
>
<i
class="i-ph-stack text-base"
:title="t('CAPTAIN.RESPONSES.STATUS.TITLE')"
/>
{{ t(`CAPTAIN.RESPONSES.STATUS.${status.toUpperCase()}`) }}
</div>
</div>
<div
class="shrink-0 text-sm text-n-slate-11 line-clamp-1 inline-flex items-center gap-1 ml-3"
>
<i class="i-ph-calendar-dot" />
{{ timestamp }}
</div>
</div>
</CardLayout>
</template>
@@ -0,0 +1,68 @@
<script setup>
import { computed, ref } from 'vue';
import { useMapGetter } from 'dashboard/composables/store';
import { useI18n } from 'vue-i18n';
import { OnClickOutside } from '@vueuse/components';
import Button from 'dashboard/components-next/button/Button.vue';
import DropdownMenu from 'dashboard/components-next/dropdown-menu/DropdownMenu.vue';
const props = defineProps({
assistantId: {
type: [String, Number],
required: true,
},
});
const emit = defineEmits(['update']);
const { t } = useI18n();
const isFilterOpen = ref(false);
const assistants = useMapGetter('captainAssistants/getRecords');
const assistantOptions = computed(() => [
{
label: t(`CAPTAIN.RESPONSES.FILTER.ALL_ASSISTANTS`),
value: 'all',
action: 'filter',
},
...assistants.value.map(assistant => ({
value: assistant.id,
label: assistant.name,
action: 'filter',
})),
]);
const selectedAssistantLabel = computed(() => {
const assistant = assistantOptions.value.find(
option => option.value === props.assistantId
);
return t('CAPTAIN.RESPONSES.FILTER.ASSISTANT', {
selected: assistant ? assistant.label : '',
});
});
const handleAssistantFilterChange = ({ value }) => {
isFilterOpen.value = false;
emit('update', value);
};
</script>
<template>
<OnClickOutside @trigger="isFilterOpen = false">
<Button
:label="selectedAssistantLabel"
icon="i-lucide-chevron-down"
size="sm"
color="slate"
trailing-icon
class="max-w-48"
@click="isFilterOpen = !isFilterOpen"
/>
<DropdownMenu
v-if="isFilterOpen"
:menu-items="assistantOptions"
class="mt-2"
@action="handleAssistantFilterChange"
/>
</OnClickOutside>
</template>
@@ -0,0 +1,59 @@
<script setup>
import { ref, computed } from 'vue';
import { useStore } from 'dashboard/composables/store';
import { useI18n } from 'vue-i18n';
import { useAlert } from 'dashboard/composables';
import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
const props = defineProps({
type: {
type: String,
required: true,
},
entity: {
type: Object,
required: true,
},
deletePayload: {
type: Object,
default: null,
},
});
const emit = defineEmits(['deleteSuccess']);
const { t } = useI18n();
const store = useStore();
const deleteDialogRef = ref(null);
const i18nKey = computed(() => props.type.toUpperCase());
const deleteEntity = async payload => {
if (!payload) return;
try {
await store.dispatch(`captain${props.type}/delete`, payload);
emit('deleteSuccess');
useAlert(t(`CAPTAIN.${i18nKey.value}.DELETE.SUCCESS_MESSAGE`));
} catch (error) {
useAlert(t(`CAPTAIN.${i18nKey.value}.DELETE.ERROR_MESSAGE`));
}
};
const handleDialogConfirm = async () => {
await deleteEntity(props.deletePayload || props.entity.id);
deleteDialogRef.value?.close();
};
defineExpose({ dialogRef: deleteDialogRef });
</script>
<template>
<Dialog
ref="deleteDialogRef"
type="alert"
:title="t(`CAPTAIN.${i18nKey}.DELETE.TITLE`)"
:description="t(`CAPTAIN.${i18nKey}.DELETE.DESCRIPTION`)"
:confirm-button-label="t(`CAPTAIN.${i18nKey}.DELETE.CONFIRM`)"
@confirm="handleDialogConfirm"
/>
</template>
@@ -0,0 +1,41 @@
<script setup>
import { computed } from 'vue';
import { useRouter } from 'vue-router';
import { useMapGetter } from 'dashboard/composables/store';
import { useAccount } from 'dashboard/composables/useAccount';
import BasePaywallModal from 'dashboard/routes/dashboard/settings/components/BasePaywallModal.vue';
const router = useRouter();
const currentUser = useMapGetter('getCurrentUser');
const isSuperAdmin = computed(() => {
return currentUser.value.type === 'SuperAdmin';
});
const { accountId, isOnChatwootCloud } = useAccount();
const i18nKey = computed(() =>
isOnChatwootCloud.value ? 'PAYWALL' : 'ENTERPRISE_PAYWALL'
);
const openBilling = () => {
router.push({
name: 'billing_settings_index',
params: { accountId: accountId.value },
});
};
</script>
<template>
<div
class="w-full max-w-[960px] mx-auto h-full max-h-[448px] grid place-content-center"
>
<BasePaywallModal
class="mx-auto"
feature-prefix="CAPTAIN"
:i18n-key="i18nKey"
:is-super-admin="isSuperAdmin"
:is-on-chatwoot-cloud="isOnChatwootCloud"
@upgrade="openBilling"
/>
</div>
</template>
@@ -0,0 +1,174 @@
<script setup>
import { reactive, computed, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useVuelidate } from '@vuelidate/core';
import { required, minLength } from '@vuelidate/validators';
import { useMapGetter } from 'dashboard/composables/store';
import Input from 'dashboard/components-next/input/Input.vue';
import Button from 'dashboard/components-next/button/Button.vue';
import Editor from 'dashboard/components-next/Editor/Editor.vue';
const props = defineProps({
mode: {
type: String,
required: true,
validator: value => ['edit', 'create'].includes(value),
},
assistant: {
type: Object,
default: () => ({}),
},
});
const emit = defineEmits(['submit', 'cancel']);
const { t } = useI18n();
const formState = {
uiFlags: useMapGetter('captainAssistants/getUIFlags'),
};
const initialState = {
name: '',
description: '',
productName: '',
featureFaq: false,
featureMemory: false,
};
const state = reactive({ ...initialState });
const validationRules = {
name: { required, minLength: minLength(1) },
description: { required, minLength: minLength(1) },
productName: { required, minLength: minLength(1) },
};
const v$ = useVuelidate(validationRules, state);
const isLoading = computed(() => formState.uiFlags.value.creatingItem);
const getErrorMessage = (field, errorKey) => {
return v$.value[field].$error
? t(`CAPTAIN.ASSISTANTS.FORM.${errorKey}.ERROR`)
: '';
};
const formErrors = computed(() => ({
name: getErrorMessage('name', 'NAME'),
description: getErrorMessage('description', 'DESCRIPTION'),
productName: getErrorMessage('productName', 'PRODUCT_NAME'),
}));
const handleCancel = () => emit('cancel');
const prepareAssistantDetails = () => ({
name: state.name,
description: state.description,
config: {
product_name: state.productName,
feature_faq: state.featureFaq,
feature_memory: state.featureMemory,
},
});
const handleSubmit = async () => {
const isFormValid = await v$.value.$validate();
if (!isFormValid) {
return;
}
emit('submit', prepareAssistantDetails());
};
const updateStateFromAssistant = assistant => {
if (!assistant) return;
const { name, description, config } = assistant;
Object.assign(state, {
name,
description,
productName: config.product_name,
featureFaq: config.feature_faq || false,
featureMemory: config.feature_memory || false,
});
};
watch(
() => props.assistant,
newAssistant => {
if (props.mode === 'edit' && newAssistant) {
updateStateFromAssistant(newAssistant);
}
},
{ immediate: true }
);
</script>
<template>
<form class="flex flex-col gap-4" @submit.prevent="handleSubmit">
<Input
v-model="state.name"
:label="t('CAPTAIN.ASSISTANTS.FORM.NAME.LABEL')"
:placeholder="t('CAPTAIN.ASSISTANTS.FORM.NAME.PLACEHOLDER')"
:message="formErrors.name"
:message-type="formErrors.name ? 'error' : 'info'"
/>
<Editor
v-model="state.description"
:label="t('CAPTAIN.ASSISTANTS.FORM.DESCRIPTION.LABEL')"
:placeholder="t('CAPTAIN.ASSISTANTS.FORM.DESCRIPTION.PLACEHOLDER')"
:message="formErrors.description"
:message-type="formErrors.description ? 'error' : 'info'"
/>
<Input
v-model="state.productName"
:label="t('CAPTAIN.ASSISTANTS.FORM.PRODUCT_NAME.LABEL')"
:placeholder="t('CAPTAIN.ASSISTANTS.FORM.PRODUCT_NAME.PLACEHOLDER')"
:message="formErrors.productName"
:message-type="formErrors.productName ? 'error' : 'info'"
/>
<fieldset class="flex flex-col gap-2.5">
<legend class="mb-3 text-sm font-medium text-n-slate-12">
{{ t('CAPTAIN.ASSISTANTS.FORM.FEATURES.TITLE') }}
</legend>
<label class="flex items-center gap-2">
<input v-model="state.featureFaq" type="checkbox" />
<span class="text-sm font-medium text-n-slate-12">
{{ t('CAPTAIN.ASSISTANTS.FORM.FEATURES.ALLOW_CONVERSATION_FAQS') }}
</span>
</label>
<label class="flex items-center gap-2">
<input v-model="state.featureMemory" type="checkbox" />
<span class="text-sm font-medium text-n-slate-12">
{{ t('CAPTAIN.ASSISTANTS.FORM.FEATURES.ALLOW_MEMORIES') }}
</span>
</label>
</fieldset>
<div class="flex items-center justify-between w-full gap-3">
<Button
type="button"
variant="faded"
color="slate"
:label="t('CAPTAIN.FORM.CANCEL')"
class="w-full bg-n-alpha-2 n-blue-text hover:bg-n-alpha-3"
@click="handleCancel"
/>
<Button
type="submit"
:label="t(`CAPTAIN.FORM.${mode.toUpperCase()}`)"
class="w-full"
:is-loading="isLoading"
:disabled="isLoading"
/>
</div>
</form>
</template>
@@ -0,0 +1,87 @@
<script setup>
import { ref, computed } from 'vue';
import { useStore } from 'dashboard/composables/store';
import { useAlert } from 'dashboard/composables';
import { useI18n } from 'vue-i18n';
import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
import AssistantForm from './AssistantForm.vue';
const props = defineProps({
selectedAssistant: {
type: Object,
default: () => ({}),
},
type: {
type: String,
default: 'create',
validator: value => ['create', 'edit'].includes(value),
},
});
const emit = defineEmits(['close']);
const { t } = useI18n();
const store = useStore();
const dialogRef = ref(null);
const assistantForm = ref(null);
const updateAssistant = assistantDetails =>
store.dispatch('captainAssistants/update', {
id: props.selectedAssistant.id,
...assistantDetails,
});
const i18nKey = computed(
() => `CAPTAIN.ASSISTANTS.${props.type.toUpperCase()}`
);
const createAssistant = assistantDetails =>
store.dispatch('captainAssistants/create', assistantDetails);
const handleSubmit = async updatedAssistant => {
try {
if (props.type === 'edit') {
await updateAssistant(updatedAssistant);
} else {
await createAssistant(updatedAssistant);
}
useAlert(t(`${i18nKey.value}.SUCCESS_MESSAGE`));
dialogRef.value.close();
} catch (error) {
const errorMessage = error?.message || t(`${i18nKey.value}.ERROR_MESSAGE`);
useAlert(errorMessage);
}
};
const handleClose = () => {
emit('close');
};
const handleCancel = () => {
dialogRef.value.close();
};
defineExpose({ dialogRef });
</script>
<template>
<Dialog
ref="dialogRef"
type="edit"
:title="t(`${i18nKey}.TITLE`)"
:description="t('CAPTAIN.ASSISTANTS.FORM_DESCRIPTION')"
:show-cancel-button="false"
:show-confirm-button="false"
overflow-y-auto
@close="handleClose"
>
<AssistantForm
ref="assistantForm"
:mode="type"
:assistant="selectedAssistant"
@submit="handleSubmit"
@cancel="handleCancel"
/>
<template #footer />
</Dialog>
</template>
@@ -0,0 +1,58 @@
<script setup>
import { ref } from 'vue';
import { useStore } from 'dashboard/composables/store';
import { useAlert } from 'dashboard/composables';
import { useI18n } from 'vue-i18n';
import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
import DocumentForm from './DocumentForm.vue';
const emit = defineEmits(['close']);
const { t } = useI18n();
const store = useStore();
const dialogRef = ref(null);
const documentForm = ref(null);
const i18nKey = 'CAPTAIN.DOCUMENTS.CREATE';
const handleSubmit = async newDocument => {
try {
await store.dispatch('captainDocuments/create', newDocument);
useAlert(t(`${i18nKey}.SUCCESS_MESSAGE`));
dialogRef.value.close();
} catch (error) {
const errorMessage =
error?.response?.message || t(`${i18nKey}.ERROR_MESSAGE`);
useAlert(errorMessage);
}
};
const handleClose = () => {
emit('close');
};
const handleCancel = () => {
dialogRef.value.close();
};
defineExpose({ dialogRef });
</script>
<template>
<Dialog
ref="dialogRef"
:title="$t(`${i18nKey}.TITLE`)"
:description="$t('CAPTAIN.DOCUMENTS.FORM_DESCRIPTION')"
:show-cancel-button="false"
:show-confirm-button="false"
@close="handleClose"
>
<DocumentForm
ref="documentForm"
@submit="handleSubmit"
@cancel="handleCancel"
/>
<template #footer />
</Dialog>
</template>
@@ -0,0 +1,114 @@
<script setup>
import { reactive, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useVuelidate } from '@vuelidate/core';
import { required, minLength, url } from '@vuelidate/validators';
import { useMapGetter } from 'dashboard/composables/store';
import Input from 'dashboard/components-next/input/Input.vue';
import Button from 'dashboard/components-next/button/Button.vue';
import ComboBox from 'dashboard/components-next/combobox/ComboBox.vue';
const emit = defineEmits(['submit', 'cancel']);
const { t } = useI18n();
const formState = {
uiFlags: useMapGetter('captainDocuments/getUIFlags'),
assistants: useMapGetter('captainAssistants/getRecords'),
};
const initialState = {
name: '',
assistantId: null,
};
const state = reactive({ ...initialState });
const validationRules = {
url: { required, url, minLength: minLength(1) },
assistantId: { required },
};
const assistantList = computed(() =>
formState.assistants.value.map(assistant => ({
value: assistant.id,
label: assistant.name,
}))
);
const v$ = useVuelidate(validationRules, state);
const isLoading = computed(() => formState.uiFlags.value.creatingItem);
const getErrorMessage = (field, errorKey) => {
return v$.value[field].$error
? t(`CAPTAIN.DOCUMENTS.FORM.${errorKey}.ERROR`)
: '';
};
const formErrors = computed(() => ({
url: getErrorMessage('url', 'URL'),
assistantId: getErrorMessage('assistantId', 'ASSISTANT'),
}));
const handleCancel = () => emit('cancel');
const prepareDocumentDetails = () => ({
external_link: state.url,
assistant_id: state.assistantId,
});
const handleSubmit = async () => {
const isFormValid = await v$.value.$validate();
if (!isFormValid) {
return;
}
emit('submit', prepareDocumentDetails());
};
</script>
<template>
<form class="flex flex-col gap-4" @submit.prevent="handleSubmit">
<Input
v-model="state.url"
:label="t('CAPTAIN.DOCUMENTS.FORM.URL.LABEL')"
:placeholder="t('CAPTAIN.DOCUMENTS.FORM.URL.PLACEHOLDER')"
:message="formErrors.url"
:message-type="formErrors.url ? 'error' : 'info'"
/>
<div class="flex flex-col gap-1">
<label for="assistant" class="mb-0.5 text-sm font-medium text-n-slate-12">
{{ t('CAPTAIN.DOCUMENTS.FORM.ASSISTANT.LABEL') }}
</label>
<ComboBox
id="assistant"
v-model="state.assistantId"
:options="assistantList"
:has-error="!!formErrors.assistantId"
:placeholder="t('CAPTAIN.DOCUMENTS.FORM.ASSISTANT.PLACEHOLDER')"
class="[&>div>button]:bg-n-alpha-black2 [&>div>button:not(.focused)]:dark:outline-n-weak [&>div>button:not(.focused)]:hover:!outline-n-slate-6"
:message="formErrors.assistantId"
/>
</div>
<div class="flex items-center justify-between w-full gap-3">
<Button
type="button"
variant="faded"
color="slate"
:label="t('CAPTAIN.FORM.CANCEL')"
class="w-full bg-n-alpha-2 n-blue-text hover:bg-n-alpha-3"
@click="handleCancel"
/>
<Button
type="submit"
:label="t('CAPTAIN.FORM.CREATE')"
class="w-full"
:is-loading="isLoading"
:disabled="isLoading"
/>
</div>
</form>
</template>
@@ -0,0 +1,40 @@
<script setup>
import { onMounted, computed } from 'vue';
import { useAccount } from 'dashboard/composables/useAccount';
import { useCaptain } from 'dashboard/composables/useCaptain';
import { useRouter } from 'vue-router';
import Banner from 'dashboard/components-next/banner/Banner.vue';
const router = useRouter();
const { accountId } = useAccount();
const { documentLimits, fetchLimits } = useCaptain();
const openBilling = () => {
router.push({
name: 'billing_settings_index',
params: { accountId: accountId.value },
});
};
const showBanner = computed(() => {
if (!documentLimits.value) return false;
const { currentAvailable } = documentLimits.value;
return currentAvailable === 0;
});
onMounted(fetchLimits);
</script>
<template>
<Banner
v-show="showBanner"
color="amber"
:action-label="$t('CAPTAIN.PAYWALL.UPGRADE_NOW')"
@action="openBilling"
>
{{ $t('CAPTAIN.BANNER.DOCUMENTS') }}
</Banner>
</template>
@@ -0,0 +1,69 @@
<script setup>
import { ref, computed, onMounted } from 'vue';
import { useStore, useMapGetter } from 'dashboard/composables/store';
import { useI18n } from 'vue-i18n';
import Spinner from 'dashboard/components-next/spinner/Spinner.vue';
import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
import ResponseCard from '../../assistant/ResponseCard.vue';
const props = defineProps({
captainDocument: {
type: Object,
required: true,
},
});
const emit = defineEmits(['close']);
const { t } = useI18n();
const store = useStore();
const dialogRef = ref(null);
const uiFlags = useMapGetter('captainResponses/getUIFlags');
const responses = useMapGetter('captainResponses/getRecords');
const isFetching = computed(() => uiFlags.value.fetchingList);
const handleClose = () => {
emit('close');
};
onMounted(() => {
store.dispatch('captainResponses/get', {
assistantId: props.captainDocument.assistant.id,
documentId: props.captainDocument.id,
});
});
defineExpose({ dialogRef });
</script>
<template>
<Dialog
ref="dialogRef"
type="edit"
:title="t('CAPTAIN.DOCUMENTS.RELATED_RESPONSES.TITLE')"
:description="t('CAPTAIN.DOCUMENTS.RELATED_RESPONSES.DESCRIPTION')"
:show-cancel-button="false"
:show-confirm-button="false"
overflow-y-auto
width="3xl"
@close="handleClose"
>
<div
v-if="isFetching"
class="flex items-center justify-center py-10 text-n-slate-11"
>
<Spinner />
</div>
<div v-else class="flex flex-col gap-3 min-h-48">
<ResponseCard
v-for="response in responses"
:id="response.id"
:key="response.id"
:question="response.question"
:status="response.status"
:answer="response.answer"
:assistant="response.assistant"
:created-at="response.created_at"
:updated-at="response.updated_at"
compact
/>
</div>
</Dialog>
</template>
@@ -0,0 +1,40 @@
<script setup>
import EmptyStateLayout from 'dashboard/components-next/EmptyStateLayout.vue';
import Button from 'dashboard/components-next/button/Button.vue';
import AssistantCard from 'dashboard/components-next/captain/assistant/AssistantCard.vue';
import { assistantsList } from 'dashboard/components-next/captain/pageComponents/emptyStates/captainEmptyStateContent.js';
const emit = defineEmits(['click']);
const onClick = () => {
emit('click');
};
</script>
<template>
<EmptyStateLayout
:title="$t('CAPTAIN.ASSISTANTS.EMPTY_STATE.TITLE')"
:subtitle="$t('CAPTAIN.ASSISTANTS.EMPTY_STATE.SUBTITLE')"
:action-perms="['administrator']"
>
<template #empty-state-item>
<div class="grid grid-cols-1 gap-4 p-px overflow-hidden">
<AssistantCard
v-for="(assistant, index) in assistantsList.slice(0, 5)"
:id="assistant.id"
:key="`assistant-${index}`"
:name="assistant.name"
:description="assistant.description"
:updated-at="assistant.created_at"
/>
</div>
</template>
<template #actions>
<Button
:label="$t('CAPTAIN.ASSISTANTS.ADD_NEW')"
icon="i-lucide-plus"
@click="onClick"
/>
</template>
</EmptyStateLayout>
</template>
@@ -0,0 +1,41 @@
<script setup>
import EmptyStateLayout from 'dashboard/components-next/EmptyStateLayout.vue';
import Button from 'dashboard/components-next/button/Button.vue';
import DocumentCard from 'dashboard/components-next/captain/assistant/DocumentCard.vue';
import { documentsList } from 'dashboard/components-next/captain/pageComponents/emptyStates/captainEmptyStateContent.js';
const emit = defineEmits(['click']);
const onClick = () => {
emit('click');
};
</script>
<template>
<EmptyStateLayout
:title="$t('CAPTAIN.DOCUMENTS.EMPTY_STATE.TITLE')"
:subtitle="$t('CAPTAIN.DOCUMENTS.EMPTY_STATE.SUBTITLE')"
:action-perms="['administrator']"
>
<template #empty-state-item>
<div class="grid grid-cols-1 gap-4 p-px overflow-hidden">
<DocumentCard
v-for="(document, index) in documentsList.slice(0, 5)"
:id="document.id"
:key="`document-${index}`"
:name="document.name"
:assistant="document.assistant"
:external-link="document.external_link"
:created-at="document.created_at"
/>
</div>
</template>
<template #actions>
<Button
:label="$t('CAPTAIN.DOCUMENTS.ADD_NEW')"
icon="i-lucide-plus"
@click="onClick"
/>
</template>
</EmptyStateLayout>
</template>
@@ -0,0 +1,38 @@
<script setup>
import EmptyStateLayout from 'dashboard/components-next/EmptyStateLayout.vue';
import Button from 'dashboard/components-next/button/Button.vue';
import InboxCard from 'dashboard/components-next/captain/assistant/InboxCard.vue';
import { inboxes } from 'dashboard/components-next/captain/pageComponents/emptyStates/captainEmptyStateContent.js';
const emit = defineEmits(['click']);
const onClick = () => {
emit('click');
};
</script>
<template>
<EmptyStateLayout
:title="$t('CAPTAIN.INBOXES.EMPTY_STATE.TITLE')"
:subtitle="$t('CAPTAIN.INBOXES.EMPTY_STATE.SUBTITLE')"
:action-perms="['administrator']"
>
<template #empty-state-item>
<div class="grid grid-cols-1 gap-4 p-px overflow-hidden">
<InboxCard
v-for="(inbox, index) in inboxes.slice(0, 5)"
:id="inbox.id"
:key="`inbox-${index}`"
:inbox="inbox"
/>
</div>
</template>
<template #actions>
<Button
:label="$t('CAPTAIN.INBOXES.ADD_NEW')"
icon="i-lucide-plus"
@click="onClick"
/>
</template>
</EmptyStateLayout>
</template>
@@ -0,0 +1,43 @@
<script setup>
import EmptyStateLayout from 'dashboard/components-next/EmptyStateLayout.vue';
import Button from 'dashboard/components-next/button/Button.vue';
import ResponseCard from 'dashboard/components-next/captain/assistant/ResponseCard.vue';
import { responsesList } from 'dashboard/components-next/captain/pageComponents/emptyStates/captainEmptyStateContent.js';
const emit = defineEmits(['click']);
const onClick = () => {
emit('click');
};
</script>
<template>
<EmptyStateLayout
:title="$t('CAPTAIN.RESPONSES.EMPTY_STATE.TITLE')"
:subtitle="$t('CAPTAIN.RESPONSES.EMPTY_STATE.SUBTITLE')"
:action-perms="['administrator']"
>
<template #empty-state-item>
<div class="grid grid-cols-1 gap-4 p-px overflow-hidden">
<ResponseCard
v-for="(response, index) in responsesList.slice(0, 5)"
:id="response.id"
:key="`response-${index}`"
:question="response.question"
:answer="response.answer"
:status="response.status"
:assistant="response.assistant"
:created-at="response.created_at"
:updated-at="response.created_at"
/>
</div>
</template>
<template #actions>
<Button
:label="$t('CAPTAIN.RESPONSES.ADD_NEW')"
icon="i-lucide-plus"
@click="onClick"
/>
</template>
</EmptyStateLayout>
</template>
@@ -0,0 +1,286 @@
import { INBOX_TYPES } from 'dashboard/helper/inbox';
export const assistantsList = [
{
account_id: 2,
config: { product_name: 'HelpDesk Pro' },
created_at: 1736033561,
description:
'An advanced AI assistant designed to enhance customer support solutions by automating workflows and providing instant responses.',
id: 4,
name: 'Support Genie',
},
{
account_id: 3,
config: { product_name: 'CRM Tools' },
created_at: 1736033562,
description:
'Helps streamline customer relationship management by organizing contacts, automating follow-ups, and providing insights.',
id: 5,
name: 'CRM Assistant',
},
{
account_id: 4,
config: { product_name: 'SalesFlow' },
created_at: 1736033563,
description:
'Optimizes your sales pipeline by tracking prospects, forecasting sales, and automating administrative tasks.',
id: 6,
name: 'SalesBot',
},
{
account_id: 5,
config: { product_name: 'TicketMaster AI' },
created_at: 1736033564,
description:
'Automates ticket assignment, categorization, and customer query responses to enhance support efficiency.',
id: 7,
name: 'TicketBot',
},
{
account_id: 6,
config: { product_name: 'FinanceAssist' },
created_at: 1736033565,
description:
'Provides financial analytics, reporting, and insights, helping teams make data-driven financial decisions.',
id: 8,
name: 'Finance Wizard',
},
{
account_id: 8,
config: { product_name: 'HR Assistant' },
created_at: 1736033567,
description:
'Streamlines HR operations including employee management, payroll, and recruitment processes.',
id: 10,
name: 'HR Helper',
},
];
export const documentsList = [
{
account_id: 1,
assistant: { id: 1, name: 'Helper Pro' },
content:
'Comprehensive guide on using conversation filters to manage chats effectively.',
created_at: 1736143272,
external_link:
'https://www.chatwoot.com/hc/user-guide/articles/1677688192-how-to-use-conversation-filters',
id: 3059,
name: 'How to use Conversation Filters? | User Guide | Chatwoot',
status: 'available',
},
{
account_id: 2,
assistant: { id: 2, name: 'Support Genie' },
content:
'Step-by-step guide for automating ticket assignments and improving support workflow in Chatwoot.',
created_at: 1736143273,
external_link:
'https://www.chatwoot.com/hc/user-guide/articles/1677688200-automating-ticket-assignments',
id: 3060,
name: 'Automating Ticket Assignments | User Guide | Chatwoot',
status: 'available',
},
{
account_id: 3,
assistant: { id: 3, name: 'CRM Assistant' },
content:
'A detailed guide on managing and organizing customer profiles for better relationship management.',
created_at: 1736143274,
external_link:
'https://www.chatwoot.com/hc/user-guide/articles/1677688210-managing-customer-profiles',
id: 3061,
name: 'Managing Customer Profiles | User Guide | Chatwoot',
status: 'available',
},
{
account_id: 4,
assistant: { id: 4, name: 'SalesBot' },
content:
'Learn how to optimize sales tracking and improve your sales forecasting using advanced features.',
created_at: 1736143275,
external_link:
'https://www.chatwoot.com/hc/user-guide/articles/1677688220-sales-tracking-guide',
id: 3062,
name: 'Sales Tracking Guide | User Guide | Chatwoot',
status: 'available',
},
{
account_id: 5,
assistant: { id: 5, name: 'TicketBot' },
content:
'How to efficiently create, manage, and resolve tickets in Chatwoot.',
created_at: 1736143276,
external_link:
'https://www.chatwoot.com/hc/user-guide/articles/1677688230-managing-tickets',
id: 3063,
name: 'Managing Tickets | User Guide | Chatwoot',
status: 'available',
},
{
account_id: 6,
assistant: { id: 6, name: 'Finance Wizard' },
content:
'Detailed guide on how to use financial reporting tools and generate insightful analytics.',
created_at: 1736143277,
external_link:
'https://www.chatwoot.com/hc/user-guide/articles/1677688240-financial-reporting',
id: 3064,
name: 'Financial Reporting | User Guide | Chatwoot',
status: 'available',
},
];
export const responsesList = [
{
account_id: 1,
answer:
'Messenger may be deactivated because you are on a free plan or the limit for inboxes might have been reached.',
created_at: 1736283330,
id: 87,
question: 'Why is my Messenger in Chatwoot deactivated?',
status: 'pending',
assistant: {
account_id: 1,
config: { product_name: 'Chatwoot' },
created_at: 1736033280,
description: 'Assists with general queries and system-wide issues.',
id: 1,
name: 'Assistant 2',
},
},
{
account_id: 2,
answer:
'You can integrate your WhatsApp account by navigating to the Integrations section and selecting the WhatsApp integration option.',
created_at: 1736283340,
id: 88,
question: 'How do I integrate WhatsApp with Chatwoot?',
assistant: {
account_id: 2,
config: { product_name: 'Chatwoot' },
created_at: 1736033281,
description: 'Helps with integration and setup-related inquiries.',
id: 2,
name: 'Assistant 3',
},
},
{
account_id: 3,
answer:
"To reset your password, go to the login page and click on 'Forgot Password', then follow the instructions sent to your email.",
created_at: 1736283350,
id: 89,
question: 'How can I reset my password in Chatwoot?',
assistant: {
account_id: 3,
config: { product_name: 'Chatwoot' },
created_at: 1736033282,
description: 'Handles account management and recovery support.',
id: 3,
name: 'Assistant 4',
},
},
{
account_id: 4,
answer:
"You can enable the dark mode in settings by navigating to 'Appearance' and selecting 'Dark Mode'.",
created_at: 1736283360,
id: 90,
question: 'How do I enable dark mode in Chatwoot?',
assistant: {
account_id: 4,
config: { product_name: 'Chatwoot' },
created_at: 1736033283,
description: 'Helps with UI and theme-related inquiries.',
id: 4,
name: 'Assistant 5',
},
},
{
account_id: 5,
answer:
"To add a new team member, navigate to 'Settings', then 'Team', and click on 'Add Team Member'.",
created_at: 1736283370,
id: 91,
question: 'How do I add a new team member in Chatwoot?',
assistant: {
account_id: 5,
config: { product_name: 'Chatwoot' },
created_at: 1736033284,
description: 'Supports team management and user access-related queries.',
id: 5,
name: 'Assistant 6',
},
},
{
account_id: 6,
answer:
"Campaigns in Chatwoot allow you to send targeted messages to specific user segments. You can create them in the 'Campaigns' section.",
created_at: 1736283380,
id: 92,
question: 'What are campaigns in Chatwoot?',
assistant: {
account_id: 6,
config: { product_name: 'Chatwoot' },
created_at: 1736033285,
description:
'Specialized in marketing, campaign management, and messaging strategies.',
id: 6,
name: 'Assistant 7',
},
},
];
export const inboxes = [
{
id: 7,
name: 'Email Support',
channel_type: INBOX_TYPES.EMAIL,
email: 'support@company.com',
},
{
id: 1,
name: 'Website Chat',
channel_type: INBOX_TYPES.WEB,
},
{
id: 2,
name: 'Facebook Support',
channel_type: INBOX_TYPES.FB,
},
{
id: 5,
name: 'SMS Service',
channel_type: INBOX_TYPES.TWILIO,
messaging_service_sid: 'MGxxxxxx',
},
{
id: 6,
name: 'WhatsApp Support',
channel_type: INBOX_TYPES.WHATSAPP,
phone_number: '+1987654321',
},
{
id: 8,
name: 'Telegram Support',
channel_type: INBOX_TYPES.TELEGRAM,
},
{
id: 9,
name: 'LINE Support',
channel_type: INBOX_TYPES.LINE,
},
{
id: 10,
name: 'API Channel',
channel_type: INBOX_TYPES.API,
},
{
id: 11,
name: 'SMS Basic',
channel_type: INBOX_TYPES.SMS,
phone_number: '+1555555555',
},
];
@@ -0,0 +1,65 @@
<script setup>
import { ref } from 'vue';
import { useStore } from 'dashboard/composables/store';
import { useAlert } from 'dashboard/composables';
import { useI18n } from 'vue-i18n';
import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
import ConnectInboxForm from './ConnectInboxForm.vue';
defineProps({
assistantId: {
type: Number,
required: true,
},
});
const emit = defineEmits(['close']);
const { t } = useI18n();
const store = useStore();
const dialogRef = ref(null);
const connectForm = ref(null);
const i18nKey = 'CAPTAIN.INBOXES.CREATE';
const handleSubmit = async payload => {
try {
await store.dispatch('captainInboxes/create', payload);
useAlert(t(`${i18nKey}.SUCCESS_MESSAGE`));
dialogRef.value.close();
} catch (error) {
const errorMessage = error?.message || t(`${i18nKey}.ERROR_MESSAGE`);
useAlert(errorMessage);
}
};
const handleClose = () => {
emit('close');
};
const handleCancel = () => {
dialogRef.value.close();
};
defineExpose({ dialogRef });
</script>
<template>
<Dialog
ref="dialogRef"
type="create"
:title="$t(`${i18nKey}.TITLE`)"
:description="$t('CAPTAIN.INBOXES.FORM_DESCRIPTION')"
:show-cancel-button="false"
:show-confirm-button="false"
@close="handleClose"
>
<ConnectInboxForm
ref="connectForm"
:assistant-id="assistantId"
@submit="handleSubmit"
@cancel="handleCancel"
/>
<template #footer />
</Dialog>
</template>
@@ -0,0 +1,115 @@
<script setup>
import { reactive, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useVuelidate } from '@vuelidate/core';
import { required } from '@vuelidate/validators';
import { useMapGetter } from 'dashboard/composables/store';
import Button from 'dashboard/components-next/button/Button.vue';
import ComboBox from 'dashboard/components-next/combobox/ComboBox.vue';
const props = defineProps({
assistantId: {
type: Number,
required: true,
},
});
const emit = defineEmits(['submit', 'cancel']);
const { t } = useI18n();
const formState = {
uiFlags: useMapGetter('captainInboxes/getUIFlags'),
inboxes: useMapGetter('inboxes/getInboxes'),
captainInboxes: useMapGetter('captainInboxes/getRecords'),
};
const initialState = {
inboxId: null,
};
const state = reactive({ ...initialState });
const validationRules = {
inboxId: { required },
};
const inboxList = computed(() => {
const captainInboxIds = formState.captainInboxes.value.map(inbox => inbox.id);
return formState.inboxes.value
.filter(inbox => !captainInboxIds.includes(inbox.id))
.map(inbox => ({
value: inbox.id,
label: inbox.name,
}));
});
const v$ = useVuelidate(validationRules, state);
const isLoading = computed(() => formState.uiFlags.value.creatingItem);
const getErrorMessage = (field, errorKey) => {
return v$.value[field].$error
? t(`CAPTAIN.INBOXES.FORM.${errorKey}.ERROR`)
: '';
};
const formErrors = computed(() => ({
inboxId: getErrorMessage('inboxId', 'INBOX'),
}));
const handleCancel = () => emit('cancel');
const prepareInboxPayload = () => ({
inboxId: state.inboxId,
assistantId: props.assistantId,
});
const handleSubmit = async () => {
const isFormValid = await v$.value.$validate();
if (!isFormValid) {
return;
}
emit('submit', prepareInboxPayload());
};
</script>
<template>
<form class="flex flex-col gap-4" @submit.prevent="handleSubmit">
<div class="flex flex-col gap-1">
<label for="inbox" class="mb-0.5 text-sm font-medium text-n-slate-12">
{{ t('CAPTAIN.INBOXES.FORM.INBOX.LABEL') }}
</label>
<ComboBox
id="inbox"
v-model="state.inboxId"
:options="inboxList"
:has-error="!!formErrors.inboxId"
:placeholder="t('CAPTAIN.INBOXES.FORM.INBOX.PLACEHOLDER')"
class="[&>div>button]:bg-n-alpha-black2 [&>div>button:not(.focused)]:dark:outline-n-weak [&>div>button:not(.focused)]:hover:!outline-n-slate-6"
:message="formErrors.inboxId"
/>
</div>
<div class="flex items-center justify-between w-full gap-3">
<Button
type="button"
variant="faded"
color="slate"
:label="t('CAPTAIN.FORM.CANCEL')"
class="w-full bg-n-alpha-2 n-blue-text hover:bg-n-alpha-3"
@click="handleCancel"
/>
<Button
type="submit"
:label="t('CAPTAIN.FORM.CREATE')"
class="w-full"
:is-loading="isLoading"
:disabled="isLoading"
/>
</div>
</form>
</template>
@@ -0,0 +1,84 @@
<script setup>
import { ref, computed } from 'vue';
import { useStore } from 'dashboard/composables/store';
import { useAlert } from 'dashboard/composables';
import { useI18n } from 'vue-i18n';
import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
import ResponseForm from './ResponseForm.vue';
const props = defineProps({
selectedResponse: {
type: Object,
default: () => ({}),
},
type: {
type: String,
default: 'create',
validator: value => ['create', 'edit'].includes(value),
},
});
const emit = defineEmits(['close']);
const { t } = useI18n();
const store = useStore();
const dialogRef = ref(null);
const responseForm = ref(null);
const updateResponse = responseDetails =>
store.dispatch('captainResponses/update', {
id: props.selectedResponse.id,
...responseDetails,
});
const i18nKey = computed(() => `CAPTAIN.RESPONSES.${props.type.toUpperCase()}`);
const createResponse = responseDetails =>
store.dispatch('captainResponses/create', responseDetails);
const handleSubmit = async updatedResponse => {
try {
if (props.type === 'edit') {
await updateResponse(updatedResponse);
} else {
await createResponse(updatedResponse);
}
useAlert(t(`${i18nKey.value}.SUCCESS_MESSAGE`));
dialogRef.value.close();
} catch (error) {
const errorMessage =
error?.response?.message || t(`${i18nKey.value}.ERROR_MESSAGE`);
useAlert(errorMessage);
}
};
const handleClose = () => {
emit('close');
};
const handleCancel = () => {
dialogRef.value.close();
};
defineExpose({ dialogRef });
</script>
<template>
<Dialog
ref="dialogRef"
:title="$t(`${i18nKey}.TITLE`)"
:description="$t('CAPTAIN.RESPONSES.FORM_DESCRIPTION')"
:show-cancel-button="false"
:show-confirm-button="false"
@close="handleClose"
>
<ResponseForm
ref="responseForm"
:mode="type"
:response="selectedResponse"
@submit="handleSubmit"
@cancel="handleCancel"
/>
<template #footer />
</Dialog>
</template>

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