Compare commits

..

4 Commits

Author SHA1 Message Date
Piyush Gupta
5267fff6b2 fix: flex alignment 2024-10-01 19:34:44 +05:30
Aashish Anand
a6d592307c Merge branch 'main' into fix-dark-mode-3209 2024-10-01 18:07:27 +05:30
Aashish Anand
d5bc70846e Merge branch 'main' into fix-dark-mode-3209 2024-10-01 17:52:35 +05:30
anandaashish74711
49e0b8fc0f Fix dark mode in demo apps #3209 2024-10-01 17:05:56 +05:30
110 changed files with 1980 additions and 744 deletions

View File

@@ -1,9 +1,9 @@
Copyright (c) 2024 Formbricks GmbH
Copyright (c) 2023 Formbricks GmbH
Portions of this software are licensed as follows:
- All content that resides under the "packages/ee/" directory of this repository, if that directory exists, is licensed under the license defined in "packages/ee/LICENSE".
- All content that resides under the "packages/js/", "packages/react-native/" and "packages/api/" directories of this repository, if that directories exist, is licensed under the "MIT" license as defined in the "LICENSE" files of these packages.
- All content that resides under the "packages/js/", "packages/errors/" and "packages/api/" directories of this repository, if that directories exist, is licensed under the "MIT" license as defined in the "LICENSE" files of these packages.
- All third party components incorporated into the Formbricks Software are licensed under the original license provided by the owner of the applicable component.
- Content outside of the above mentioned directories or restrictions above is available under the "AGPLv3" license as defined below.

View File

@@ -2,4 +2,4 @@
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.

View File

@@ -4,20 +4,25 @@ import I1 from "./images/I1.webp";
import I2 from "./images/I2.webp";
export const metadata = {
title: "Using Actions in Formbricks",
title: "Using Actions in Formbricks | Fine-tuning User Moments",
description:
"Dive deep into how actions in Formbricks help products and organizations to engage users at precise moments in their journey. Discover the power of actions, from coding to no-code setups, to refine user targeting and generate richer, more detailed user insights.",
};
#### App Surveys
# Actions
# Actions & Targeting
Actions are predefined events within your app that prompt Formbricks to display a survey when triggered. These are detected by the Formbricks widget, which then presents the appropriate survey based on your predefined settings.
Understanding user thoughts and feelings at critical moments in their journey is pivotal. To achieve this, Formbricks uses user-centric actions that trigger surveys at precisely the right time. Actions are essentially notifications sent from your application to Formbricks when predefined user activities occur, making it possible to gather insights during key interactions.
<Note>
Ensure that youve **initialized Formbricks with a userId** to fully utilize this feature along with other
app survey capabilities.
</Note>
## **How Do Actions Work?**
Actions in Formbricks App Surveys are deeply integrated with user activities within your app. When a user performs a specified action, the Formbricks widget detects this activity and can present a survey to that specific user if the trigger conditions match for that survey. This capability ensures that surveys are triggered at the right time. You can set up these actions through a user-friendly No-Code interface within the Formbricks dashboard.
Actions in Formbricks App Surveys are deeply integrated with user activities within your app. When a user performs a specified action, the Formbricks widget detects this activity and can present a survey to that specific user if the trigger conditions match of that survey, while also recording the event. This capability ensures that surveys are not only triggered at the right time but are also tailored to the users recent interactions within the app. You can set up these actions through a user-friendly No-Code interface within the Formbricks dashboard.
## **Why Are Actions Useful?**
@@ -25,7 +30,8 @@ Actions are invaluable for enhancing survey relevance and effectiveness:
- **Personalized Engagement**: Surveys triggered by user actions ensure content is highly relevant and engaging, matching each users current context.
- **User Attributes**: By tying surveys to specific user attributes, such as activity levels or feature usage, you can customize the survey experience to reflect individual user profiles.
- **User Targeting**: Precise targeting based on user attributes ensures that surveys are shown only to users who meet certain criteria, enhancing the relevance and effectiveness of each survey.
- **User Segments**: Analyze action data to create detailed user segments, targeting specific groups with surveys that are pertinent to their behaviors or interactions within the app.
- **User Targeting**: Precise targeting based on user actions and attributes ensures that surveys are shown only to users who meet certain criteria, enhancing the relevance and effectiveness of each survey.
## **Setting Up No-Code Actions**
@@ -121,3 +127,5 @@ return <button onClick={handleClick}>Click Me</button>;
</CodeGroup>
</Col>
This documentation frames actions around user interactions, emphasizing the connection between the user's activities and the survey experience. By leveraging user-centric actions, you can create highly targeted and timely surveys that resonate with users and yield valuable insights.

View File

@@ -1,18 +1,39 @@
import { MdxImage } from "@/components/MdxImage";
import { ResponsiveVideo } from "@/components/ResponsiveVideo";
import GermansGpt from "./germans-gpt.webp";
import Hni from "./hni.webp";
import PowerUsers from "./power-users.webp";
import RideHailing from "./ride-hailing.webp";
import UpsellMiro from "./upsell-miro.webp";
export const metadata = {
title: "Advanced Targeting for App Surveys | Formbricks",
title: "Advanced Targeting for In-app Surveys | Formbricks",
description:
"Advanced Targeting allows you to show surveys to just the right group of people. You can target surveys based on user attributes, metadata, and other segments. This helps you get more relevant feedback and make data-driven decisions.",
"Advanced Targeting allows you to show surveys to just the right group of people. You can target surveys based on user attributes, user events, and metadata. This helps you get more relevant feedback and make data-driven decisions.",
};
#### App Surveys
# Advanced Targeting
<Note>
Targeting based on actions is deprecated in Advanced Targeting and will be removed soon. We recommend using
filters on user attributes to target the survey only to specific groups of users.
</Note>
Advanced Targeting allows you to show surveys to the right group of people. You can target surveys based on user attributes, device type, and more instead of spraying and praying. This helps you get more relevant feedback and make data-driven decisions. All of this without writing a single line of code.
# How to setup Advanced Targeting
<ResponsiveVideo
title="Formbricks Multi-language Surveys"
src="https://www.youtube-nocookie.com/embed/0BQp6N4cXzU?si=KeBM7G7Ch1xtrsOm&amp;controls=0"
/>
<Note>Advanced Targeting is only available on the Pro plan!</Note>
## How to setup Advanced Targeting
<Note>
Advanced Targeting is available on the Pro plan!
</Note>
1. On the Formbricks dashboard, click on **People** tab from the top navigation bar.
@@ -20,7 +41,7 @@ Advanced Targeting allows you to show surveys to the right group of people. You
3. Give your segment a title & a description to help you remember what this segment is about.
4. Now click on the **Add Filter** button to add a filter. You can filter based on user attributes, other segments, devices, and more.
4. Now click on the **Add Filter** button to add a filter. You can filter based on actions, user attributes, other segments, devices, and more.
5. To group a set of filters together, click on the Three Dots icon on the right side of the filter and click on **Create Group**.
@@ -29,3 +50,32 @@ Advanced Targeting allows you to show surveys to the right group of people. You
7. Once you are happy with the segment, click on **Save Segment**.
8. Now, when you create a survey, you can select this segment to target your survey to.
## Examples:
1. Let's say you want to upsell to: Miro, Loom, Figma, Slack and Asana.
<MdxImage
src={UpsellMiro}
alt="Upselling Opportunity"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
2. Post-experience surveying for a ride hailing app where users who have taken more than 1 ride are shown a survey.
<MdxImage
src={RideHailing}
alt="Ride Hailing Targeting"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
3. Sneak Peak: How we at Formbricks automate inviting power users to chat with us
<MdxImage
src={PowerUsers}
alt="Automate inviting power users to chat with us at Formbricks"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>

View File

@@ -37,9 +37,8 @@ To display the Product-Market Fit survey in your app you want to proceed as foll
3. Setup the user action to display survey at good point in time
<Note>
## Formbricks Widget running? We assume that you have already installed the Formbricks Widget in your web
app. Its required to display messages and surveys in your app. If not, please follow the [Quick Start Guide
(15mins).](/app-surveys/quickstart)
## Formbricks Widget running?
We assume that you have already installed the Formbricks Widget in your web app. Its required to display messages and surveys in your app. If not, please follow the [Quick Start Guide (15mins).](/app-surveys/quickstart)
</Note>
### 1. Create new PMF survey
@@ -70,12 +69,25 @@ _Want to change the button color? You can do so in the product settings!_
Save, and move over to where the magic happens: The “Audience” tab.
### 3. Pre-segment your audience
### 3. Pre-segment your audience (coming soon)
<Note>
## Filter by attribute coming soon We're working on pre-segmenting users by attributes. We will update this
manual in the next days.
</Note>
To run this survey properly, you should pre-segment your user base. As touched upon earlier: if you ask every user youll get lots of opinions which are often misleading. You only want to gather feedback from people who invested the time to get to know and use your product:
**Filter by attribute**: You can keep the logic to decide if a user has (or has not) experienced value in your application. This makes most sense if you want to use historic usage data to decide if a user qualifies or not. Create your logic and if it applies, send an attribute to Formbricks by e.g. `formbricks.setAttribute("Loyalty", "Experienced Value");` Here is the full manual on how to [set attributes](/app-surveys/user-identification).
**Filter by actions (coming soon)**: Later, you can also segment users based on events tracked with Formbricks. However, this makes it impossible to use historic usage data (pre Formbricks usage). Here we will have a few options to achieve that:
- Check the time passed since sign-up (e.g. signed up 4 weeks ago)
- User has performed a specific action a certain number of times or (e.g. created 5 reports)
- User has performed a combination of actions (e.g. created a report **and** invited a organization member)
This way you make sure that you separate potentially misleading opinions from valuable insights.
### 4. Set up a trigger for the Product-Market Fit survey:
You need a trigger to display the survey but in this case, the filtering does all the work. Its up to you to decide to display the survey after the user viewed a specific subpage (pageURL) or after clicking an element. Have a look at the [Actions manual](/app-surveys/actions/) if you are not sure how to set them up:

View File

@@ -6,7 +6,7 @@ import ApiKeySecret from "./images/api-key-secret.webp";
export const metadata = {
title: "Formbricks API Overview: Public Client & Management API Breakdown",
description:
"Formbricks provides a powerful API to manage your surveys, responses, users, displays, attributes & webhooks programmatically. Get a detailed understanding of Formbricks' dual API offerings: the unauthenticated Public Client API optimized for client-side tasks and the secured Management API for advanced account operations. Choose the perfect fit for your integration needs and ensure robust data handling",
"Formbricks provides a powerful API to manage your surveys, responses, users, displays, actions, attributes & webhooks programmatically. Get a detailed understanding of Formbricks' dual API offerings: the unauthenticated Public Client API optimized for client-side tasks and the secured Management API for advanced account operations. Choose the perfect fit for your integration needs and ensure robust data handling",
};
#### API
@@ -23,6 +23,7 @@ The [Public Client API](https://documenter.getpostman.com/view/11026000/2sA3Bq5X
We currently have the following Client API methods exposed and below is their documentation attached in Postman:
- [Actions API](https://documenter.getpostman.com/view/11026000/2sA3Bq5XEh#b8f3a10e-1642-4d82-a629-fef0a8c6c86c) - Create actions for a Person
- [Displays API](https://documenter.getpostman.com/view/11026000/2sA3Bq5XEh#949272bf-daec-4d72-9b52-47af3d74a62c) - Mark Survey as Displayed or Update an existing Display by linking it with a Response for a Person
- [People API](https://documenter.getpostman.com/view/11026000/2sA3Bq5XEh#ee3d2188-4253-4bca-9238-6b76455805a9) - Create & Update a Person (e.g. attributes, email, userId, etc)
- [Responses API](https://documenter.getpostman.com/view/11026000/2sA3Bq5XEh#8c773032-536c-483c-a237-c7697347946e) - Create & Update a Response for a Survey

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

View File

@@ -1,171 +1,136 @@
import { MdxImage } from "@/components/MdxImage";
import ActionCalculateOperators from "./images/action-calculate-operators.webp";
import ActionCalculateValue from "./images/action-calculate-value.webp";
import ActionCalculateVariables from "./images/action-calculate-variables.webp";
import ActionCalculate from "./images/action-calculate.webp";
import ActionJump from "./images/action-jump.webp";
import ActionOptions from "./images/action-options.webp";
import ActionRequire from "./images/action-require.webp";
import AddLogic from "./images/add-logic.webp";
import ConditionChaining from "./images/condition-chaining.webp";
import ConditionOperators from "./images/condition-operators.webp";
import ConditionOptions from "./images/condition-options.webp";
import ConditionValue from "./images/condition-value.webp";
import Conditions from "./images/conditions.webp";
import Editor from "./images/editor.webp";
import QuestionLogic from "./images/question-logic.webp";
import StepEight from "./images/StepEight.webp";
import StepFive from "./images/StepFive.webp";
import StepFour from "./images/StepFour.webp";
import StepOne from "./images/StepOne.webp";
import StepSeven from "./images/StepSeven.webp";
import StepSix from "./images/StepSix.webp";
import StepThree from "./images/StepThree.webp";
import StepTwo from "./images/StepTwo.webp";
export const metadata = {
title: "Conditional Logic",
title: "Conditional Logic in Formbricks Surveys",
description:
"Create complex survey logic with the Logic Editor. Use conditions, actions, and variables to create a personalized survey experience.",
"Enhance your surveys with Conditional Logic to create a dynamic and responsive survey experience. Guide respondents through different paths based on their answers, ensuring each survey is tailored to the users responses. This feature is applicable for all kinds of surveys!",
};
# Logic Editor
# Conditional Logic
Create complex survey logic with the Logic Editor. Use conditions, actions, and variables to create a personalized survey experience.
With Formbricks, enhance your surveys with Conditional Logic to create a dynamic and responsive survey experience. This feature allows you to guide respondents through different paths based on their answers, ensuring each survey is tailored to the users responses. This feature is applicable for all kinds of surveys!
<MdxImage src={Editor} alt="Logic Editor" quality="100" className="max-w-full rounded-lg sm:max-w-3xl" />
### Setting Up Conditional Logic
## Terminology
Conditional Logic can be applied to any question within your survey to direct the flow based on specific responses.
- **Condition**: A rule that determines when an action should be executed.
- **Action**: A task that is executed when a condition is met.
## **Creating Logic**
1. **Add a Logic Block**: Click the `Add logic +` button to add a new logic block.
<MdxImage src={AddLogic} alt="Add Logic" quality="100" className="max-w-full rounded-lg sm:max-w-3xl" />
<Note>
You can add multiple logic blocks to a survey. Logic blocks are executed in the order they are added. You
can rearrange the order of logic blocks.
</Note>
2. **Add Conditions**: Add conditions to the logic block. Conditions are rules that determine when an action should be executed.
1. **Create or Edit a Question**: Start by adding a new question or editing an existing one within your survey.
<MdxImage
src={Conditions}
alt="Add Conditions"
src={StepOne}
alt="Choose a link survey template"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
className="max-w-full rounded-lg sm:max-w-3xl "
/>
Conditons can be based on:
- **Question**: The answer to a question.
- **Variable**: A variable value.
- **Hidden Field**: The value of a hidden field.
2.a **Condition Options**: Choose from a list of available conditions.
<MdxImage
src={ConditionOptions}
alt="Condition Options"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
2.b **Condition Operators**: Choose an operator to compare the condition value.
<MdxImage
src={ConditionOperators}
alt="Condition Operators"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
2.c **Condition Value**: Enter a value to compare the condition against.
Comparisons can be made against a fixed value or a dynamic value.
Dynamic values can be based on a question, variable, or hidden field.
<MdxImage
src={ConditionValue}
alt="Condition Value"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
<Note>
- Conditions can be grouped. - Conditions can be combined using AND or OR operators. You can add multiple
conditions to a logic block. Conditions are evaluated in the order they are added.
</Note>
2. **Access Advanced Settings**: Click on **Advanced Settings** beneath the question setup area to access additional configuration options.
<MdxImage
src={ConditionChaining}
alt="Condition Chaining"
src={StepTwo}
alt="Choose a link survey template"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
className="max-w-full rounded-lg sm:max-w-3xl "
/>
3. **Add Actions**: Add actions to the logic block. Actions are tasks that are executed when a condition is met.
<Note>You can add multiple actions to a logic block. Actions are executed in the order they are added.</Note>
- 3.a **Action Options**: Choose from a list of available actions.
<MdxImage
src={ActionOptions}
alt="Add Actions"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
Action is of the following types:
- **Calculate**: Perform a calculation. These variables are then available for use in other questions.
- Calculations can be performed on variables.
- Calculations can be based on fixed values or dynamic values.
<MdxImage
src={ActionCalculateVariables}
alt="Action Calculate Variables"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
<MdxImage
src={ActionCalculateOperators}
alt="Action Calculate Variables"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
<MdxImage
src={ActionCalculateValue}
alt="Action Calculate Variables"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
<MdxImage
src={ActionCalculate}
alt="Action Calculate"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
- **Require Answer**: Make a question required. Only the optional questions can be marked as required while filling the survey.
<MdxImage
src={ActionRequire}
alt="Action Require"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
- **Jump to Question**: Skip to a specific question. The user will be redirected to the specified question based on the condition.
<MdxImage
src={ActionJump}
alt="Action Jump"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
4. **Save Logic**: Click the `Save` button to save the logic block.
# Question Logic
This logic is executed when the user answers the question. Logic can be as simple as showing a follow-up question based on the answer or as complex as calculating a score based on multiple answers.
3. **Configure Logic Jumps**: Choose **Logic Jumps** to set up conditions that dictate the survey's progression based on responses.
<MdxImage
src={QuestionLogic}
alt="Question Logic"
src={StepThree}
alt="Choose a link survey template"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
className="max-w-full rounded-lg sm:max-w-3xl "
/>
### Configuring Logic Conditions
Enhance survey interactivity by setting up triggers based on respondent answers. You can specify different paths for each type of response:
**General Conditions (Available in All Question Types):**
- **Answer Submitted/Skipped**: Initiate different survey paths based on whether a question is answered or skipped.
<MdxImage
src={StepFour}
alt="Choose a link survey template"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl "
/>
**Choice-Based Conditions:**
<MdxImage
src={StepFive}
alt="Choose a link survey template"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl "
/>
- **One of Multiple Choice Values**: Activate if the answer is among selected options. (Single select and Multi select)
- **Equals: Exactly the Selected Values**: Initiate a jump if the response matches exactly the selected values provided in the options. (Single select and Multi select)
- **Includes All Selected Values**: Activate if all selected values match those chosen by the survey creator. (Multi select only)
**Numeric Conditions (Rating & NPS Questions Only)**
<MdxImage
src={StepSix}
alt="Choose a link survey template"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl "
/>
- **Value Comparisons**: Initiate jumps based on numerical criteria—equals, does not equal, less than, less than or equal to, greater than, or greater than equal to.
**Matrix-Specific Conditions**
<MdxImage
src={StepSeven}
alt="Choose a link survey template"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl "
/>
- **Submission Completeness**: Initiate based on whether the response is completely or partially submitted.
### **Specifying Survey Paths**
After setting conditions, you specify the paths to take when those conditions are met:
- **Jump to a Specific Question**: Direct the respondent to a particular question elsewhere in the survey.
- **Jump to Survey End**: Conclude the survey early based on the respondent's answers.
<MdxImage
src={StepEight}
alt="Choose a link survey template"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl "
/>
### **Multiple Logic Jumps**
You can add multiple Logic Jumps to a single question. These jumps work in an **OR** fashion, meaning any of the conditions can initiate the specified survey path. The logic jumps are evaluated in the **order they are created**, and the first true condition will take precedence.
---
### **Example Scenario**
Suppose youre conducting a survey about technology usage:
1. **Question (Single Select)**: What devices do you use daily?
2. **Answers**: Smartphone, Laptop, Tablet, None
**Logic Jump Setup**:
- If the respondent selects **None**, jump to the end of the survey.
- If the respondent selects **Smartphone**, jump to a question specific to smartphone usage.
This setup allows for a tailored survey experience that adapts to the respondent's input, making your data collection more targeted and efficient.
Thats it! Now go and configure your surveys to bring down your survey fatigue to 0% and ask respondents through customized paths. Enhance their relevance and engagement with your survey, leading to higher quality responses and better data.

View File

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 19 KiB

View File

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

View File

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 19 KiB

View File

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 18 KiB

View File

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 30 KiB

View File

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 34 KiB

View File

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 29 KiB

View File

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 30 KiB

View File

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 16 KiB

View File

Before

Width:  |  Height:  |  Size: 9.8 KiB

After

Width:  |  Height:  |  Size: 9.8 KiB

View File

Before

Width:  |  Height:  |  Size: 41 KiB

After

Width:  |  Height:  |  Size: 41 KiB

View File

@@ -0,0 +1,171 @@
import { MdxImage } from "@/components/MdxImage";
import ActionCalculateOperators from "./images/action-calculate-operators.webp";
import ActionCalculateValue from "./images/action-calculate-value.webp";
import ActionCalculateVariables from "./images/action-calculate-variables.webp";
import ActionCalculate from "./images/action-calculate.webp";
import ActionJump from "./images/action-jump.webp";
import ActionOptions from "./images/action-options.webp";
import ActionRequire from "./images/action-require.webp";
import AddLogic from "./images/add-logic.webp";
import ConditionChaining from "./images/condition-chaining.webp";
import ConditionOperators from "./images/condition-operators.webp";
import ConditionOptions from "./images/condition-options.webp";
import ConditionValue from "./images/condition-value.webp";
import Conditions from "./images/conditions.webp";
import Editor from "./images/editor.webp";
import QuestionLogic from "./images/question-logic.webp";
export const metadata = {
title: "Logic Editor",
description:
"Create complex survey logic with the Logic Editor. Use conditions, actions, and variables to create a personalized survey experience.",
};
# Logic Editor
Create complex survey logic with the Logic Editor. Use conditions, actions, and variables to create a personalized survey experience.
<MdxImage src={Editor} alt="Logic Editor" quality="100" className="max-w-full rounded-lg sm:max-w-3xl" />
## Terminology
- **Condition**: A rule that determines when an action should be executed.
- **Action**: A task that is executed when a condition is met.
## **Creating Logic**
1. **Add a Logic Block**: Click the `Add logic +` button to add a new logic block.
<MdxImage src={AddLogic} alt="Add Logic" quality="100" className="max-w-full rounded-lg sm:max-w-3xl" />
<Note>
You can add multiple logic blocks to a survey. Logic blocks are executed in the order they are added. You
can rearrange the order of logic blocks.
</Note>
2. **Add Conditions**: Add conditions to the logic block. Conditions are rules that determine when an action should be executed.
<MdxImage
src={Conditions}
alt="Add Conditions"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
Conditons can be based on:
- **Question**: The answer to a question.
- **Variable**: A variable value.
- **Hidden Field**: The value of a hidden field.
2.a **Condition Options**: Choose from a list of available conditions.
<MdxImage
src={ConditionOptions}
alt="Condition Options"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
2.b **Condition Operators**: Choose an operator to compare the condition value.
<MdxImage
src={ConditionOperators}
alt="Condition Operators"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
2.c **Condition Value**: Enter a value to compare the condition against.
Comparisons can be made against a fixed value or a dynamic value.
Dynamic values can be based on a question, variable, or hidden field.
<MdxImage
src={ConditionValue}
alt="Condition Value"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
<Note>
- Conditions can be grouped. - Conditions can be combined using AND or OR operators. You can add multiple
conditions to a logic block. Conditions are evaluated in the order they are added.
</Note>
<MdxImage
src={ConditionChaining}
alt="Condition Chaining"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
3. **Add Actions**: Add actions to the logic block. Actions are tasks that are executed when a condition is met.
<Note>You can add multiple actions to a logic block. Actions are executed in the order they are added.</Note>
- 3.a **Action Options**: Choose from a list of available actions.
<MdxImage
src={ActionOptions}
alt="Add Actions"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
Action is of the following types:
- **Calculate**: Perform a calculation. These variables are then available for use in other questions.
- Calculations can be performed on variables.
- Calculations can be based on fixed values or dynamic values.
<MdxImage
src={ActionCalculateVariables}
alt="Action Calculate Variables"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
<MdxImage
src={ActionCalculateOperators}
alt="Action Calculate Variables"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
<MdxImage
src={ActionCalculateValue}
alt="Action Calculate Variables"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
<MdxImage
src={ActionCalculate}
alt="Action Calculate"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
- **Require Answer**: Make a question required. Only the optional questions can be marked as required while filling the survey.
<MdxImage
src={ActionRequire}
alt="Action Require"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
- **Jump to Question**: Skip to a specific question. The user will be redirected to the specified question based on the condition.
<MdxImage
src={ActionJump}
alt="Action Jump"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>
4. **Save Logic**: Click the `Save` button to save the logic block.
# Question Logic
This logic is executed when the user answers the question. Logic can be as simple as showing a follow-up question based on the answer or as complex as calculating a score based on multiple answers.
<MdxImage
src={QuestionLogic}
alt="Question Logic"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
/>

View File

@@ -23,10 +23,6 @@ This guide will help you understand how to generate and use single-use links wit
- The primary purpose of single-use links is to assure that no respondent submits a survey twice.
<Note>
Want to create up to 5,000 single-use links? Use our [API endpoint for that.](https://documenter.getpostman.com/view/11026000/2sA3Bq5XEh#c49ef758-a78a-4ef4-a282-262621151f08).
</Note>
## Using Single-Use Links with Formbricks
Using single-use links with Formbricks is quite straight-forward:

View File

@@ -39,7 +39,7 @@ To link a response to a user in your Formbricks database, you can pass your inte
## Where do I find my userId?
The `userId` we are referring to is the `userId` of your own system. For example, a user signs up to your app and gets the Id `ABC123` assigned then this is the Id you pass along in the URL parameter.
The `userId` we are refering to is the `userId` of your own system. For example, a user signs up to your app and gets the Id `ABC123` assigned then this is the Id you pass along in the URL parameter.
This allows you to connect the response to the user profile of this specific in the Formbricks database. You can then use the response data to create segments for further surveying or invite them to an interview, etc.

View File

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 53 KiB

View File

@@ -11,9 +11,11 @@ export const metadata = {
#### Website Surveys
# Actions
# Actions & Targeting
Actions are triggers based on interactions with your website, allowing you to capture feedback precisely when it's most relevant.
For public-facing websites, landing pages, and pages without user authentication walls, actions serve as effective triggers for displaying surveys. This method is particularly suitable for engaging general audiences, where **individual user tracking is not required or feasible**.
Actions in this context are straightforward triggers based on interactions with your website, allowing you to capture feedback precisely when it's most relevant.
<Note>
These actions operate **independently** as website surveys do not involve user identification. If you have
@@ -44,7 +46,7 @@ Formbricks provides an intuitive No-Code interface for configuring actions, enab
src={StepOne}
alt="Choose a link survey template"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
className="max-w-full rounded-lg sm:max-w-3xl "
/>
2. Now click on “Add Action”
@@ -53,7 +55,7 @@ Formbricks provides an intuitive No-Code interface for configuring actions, enab
src={StepTwo}
alt="Choose a link survey template"
quality="100"
className="max-w-full rounded-lg sm:max-w-3xl"
className="max-w-full rounded-lg sm:max-w-3xl "
/>
Here are four types of No-Code actions you can set up:

View File

@@ -53,7 +53,7 @@ export const SideNavigation = ({ pathname }) => {
onClick={() => setSelectedId(heading.id)}
className={`${
heading.id === selectedId
? "text-brand-dark font-medium"
? "text-brand font-medium"
: "font-normal text-slate-600 hover:text-slate-950 dark:text-white dark:hover:text-slate-50"
}`}>
{heading.text}

View File

@@ -57,7 +57,7 @@ export const navigation: Array<NavGroup> = [
{
title: "Features",
children: [
{ title: "Actions", href: "/website-surveys/actions" },
{ title: "Actions & Targeting", href: "/website-surveys/actions-and-targeting" },
{ title: "Show Survey to % of users", href: "/global/show-survey-to-percent-of-users" }, // app and website
{ title: "Recontact Options", href: "/app-surveys/recontact" },
{ title: "Hidden Fields", href: "/global/hidden-fields" }, // global
@@ -109,6 +109,7 @@ export const navigation: Array<NavGroup> = [
links: [
{ title: "Access Roles", href: "/global/access-roles" },
{ title: "Styling Theme", href: "/global/styling-theme" },
{ title: "Logic Editor", href: "/global/logic-editor" },
],
},
{

View File

@@ -110,11 +110,6 @@ const nextConfig = {
destination: "/global/schedule-start-end-dates",
permanent: true,
},
{
source: "/global/logic-editor",
destination: "/global/conditional-logic",
permanent: true,
},
// Integrations
{
source: "/integrations/:path",

View File

@@ -1,6 +1,9 @@
"use client";
import Dance from "@/images/onboarding-dance.gif";
import Lost from "@/images/onboarding-lost.gif";
import { ArrowRight } from "lucide-react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { cn } from "@formbricks/lib/cn";
@@ -59,21 +62,20 @@ export const ConnectWithFormbricks = ({
</div>
<div
className={cn(
"flex h-[30rem] w-1/2 flex-col items-center justify-center rounded-lg border text-center",
widgetSetupCompleted ? "border-green-500 bg-green-100" : "border-slate-300 bg-slate-200"
"flex h-[30rem] w-1/2 flex-col items-center justify-center rounded-lg border bg-slate-200 text-center shadow",
widgetSetupCompleted ? "border-green-500 bg-green-100" : ""
)}>
{widgetSetupCompleted ? (
<div>
<p className="text-3xl">Congrats!</p>
<p className="pt-4 text-sm font-medium text-slate-600">Well done! We&apos;re connected.</p>
<Image src={Dance} alt="lost" height={250} />
<p className="mt-6 text-xl font-bold">Connection successful </p>
</div>
) : (
<div className="flex animate-pulse flex-col items-center space-y-4">
<span className="relative flex h-10 w-10">
<span className="animate-ping-slow absolute inline-flex h-full w-full rounded-full bg-slate-400 opacity-75"></span>
<span className="relative inline-flex h-10 w-10 rounded-full bg-slate-500"></span>
</span>
<p className="pt-4 text-sm font-medium text-slate-600">Waiting for your signal...</p>
<div className="space-y-4">
<Image src={Lost} alt="lost" height={250} />
<p className="animate-pulse pt-4 text-sm font-semibold text-slate-700">
Waiting for your signal...
</p>
</div>
)}
</div>

View File

@@ -102,7 +102,7 @@ export const InviteOrganizationMember = ({ organization, environmentId }: Invite
<div className="flex w-full justify-end space-x-2">
<Button
id="onboarding-inapp-invite-have-a-look-first"
className="text-slate-400"
className="font-normal text-slate-400"
variant="minimal"
onClick={(e) => {
e.preventDefault();

View File

@@ -33,7 +33,7 @@ const Page = async ({ params }: InvitePageProps) => {
<div className="flex min-h-full min-w-full flex-col items-center justify-center">
<Header
title="Who is your favorite engineer?"
subtitle="Invite your tech-savvy co-worker to help with the setup."
subtitle="Invite your tech-savvy co-worker to help with the setup 🤓"
/>
<div className="space-y-4 text-center">
<p className="text-4xl font-medium text-slate-800"></p>

View File

@@ -28,7 +28,10 @@ const Page = async ({ params }: ConnectPageProps) => {
return (
<div className="flex min-h-full flex-col items-center justify-center py-10">
<Header title={`Let's connect your product with Formbricks`} subtitle="It takes less than 4 minutes." />
<Header
title={`Let's connect your product with Formbricks`}
subtitle="It takes less than 4 minutes, pinky promise!"
/>
<div className="space-y-4 text-center">
<p className="text-4xl font-medium text-slate-800"></p>
<p className="text-sm text-slate-500"></p>

View File

@@ -7,7 +7,6 @@ import { TI18nString, TSurvey, TSurveyMatrixQuestion } from "@formbricks/types/s
import { Button } from "@formbricks/ui/components/Button";
import { Label } from "@formbricks/ui/components/Label";
import { QuestionFormInput } from "@formbricks/ui/components/QuestionFormInput";
import { ShuffleOptionSelect } from "@formbricks/ui/components/ShuffleOptionSelect";
import { isLabelValidForAllLanguages } from "../lib/validation";
interface MatrixQuestionFormProps {
@@ -79,24 +78,6 @@ export const MatrixQuestionForm = ({
}
};
const shuffleOptionsTypes = {
none: {
id: "none",
label: "Keep current order",
show: true,
},
all: {
id: "all",
label: "Randomize all",
show: true,
},
exceptLast: {
id: "exceptLast",
label: "Randomize all except last option",
show: true,
},
};
return (
<form>
<QuestionFormInput
@@ -154,7 +135,7 @@ export const MatrixQuestionForm = ({
{question.rows.map((_, index) => (
<div className="flex items-center" onKeyDown={(e) => handleKeyDown(e, "row")}>
<QuestionFormInput
key={`row-${index}-${question.rows.length}`}
key={`row-${index}`}
id={`row-${index}`}
label={""}
localSurvey={localSurvey}
@@ -196,7 +177,7 @@ export const MatrixQuestionForm = ({
{question.columns.map((_, index) => (
<div className="flex items-center" onKeyDown={(e) => handleKeyDown(e, "column")}>
<QuestionFormInput
key={`column-${index}-${question.columns.length}`}
key={`column-${index}`}
id={`column-${index}`}
label={""}
localSurvey={localSurvey}
@@ -230,14 +211,6 @@ export const MatrixQuestionForm = ({
<span>Add column</span>
</Button>
</div>
<div className="mt-3 flex flex-1 items-center justify-end gap-2">
<ShuffleOptionSelect
shuffleOptionsTypes={shuffleOptionsTypes}
questionIdx={questionIdx}
updateQuestion={updateQuestion}
shuffleOption={question.shuffleOption}
/>
</div>
</div>
</div>
</form>

View File

@@ -19,7 +19,13 @@ import {
import { Button } from "@formbricks/ui/components/Button";
import { Label } from "@formbricks/ui/components/Label";
import { QuestionFormInput } from "@formbricks/ui/components/QuestionFormInput";
import { ShuffleOptionSelect } from "@formbricks/ui/components/ShuffleOptionSelect";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@formbricks/ui/components/Select";
import { QuestionOptionChoice } from "./QuestionOptionChoice";
interface OpenQuestionFormProps {
@@ -284,12 +290,29 @@ export const MultipleChoiceQuestionForm = ({
</Button>
<div className="flex flex-1 items-center justify-end gap-2">
<ShuffleOptionSelect
questionIdx={questionIdx}
shuffleOption={question.shuffleOption}
updateQuestion={updateQuestion}
shuffleOptionsTypes={shuffleOptionsTypes}
/>
<Select
defaultValue={question.shuffleOption}
value={question.shuffleOption}
onValueChange={(e: TShuffleOption) => {
updateQuestion(questionIdx, { shuffleOption: e });
}}>
<SelectTrigger className="w-fit space-x-2 overflow-hidden border-0 font-medium text-slate-600">
<SelectValue placeholder="Select ordering" />
</SelectTrigger>
<SelectContent>
{Object.values(shuffleOptionsTypes).map(
(shuffleOptionsType) =>
shuffleOptionsType.show && (
<SelectItem
key={shuffleOptionsType.id}
value={shuffleOptionsType.id}
title={shuffleOptionsType.label}>
{shuffleOptionsType.label}
</SelectItem>
)
)}
</SelectContent>
</Select>
</div>
</div>
</div>

View File

@@ -7,11 +7,22 @@ import { PlusIcon } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { createI18nString, extractLanguageCodes } from "@formbricks/lib/i18n/utils";
import { TAttributeClass } from "@formbricks/types/attribute-classes";
import { TI18nString, TSurvey, TSurveyRankingQuestion } from "@formbricks/types/surveys/types";
import {
TI18nString,
TShuffleOption,
TSurvey,
TSurveyRankingQuestion,
} from "@formbricks/types/surveys/types";
import { Button } from "@formbricks/ui/components/Button";
import { Label } from "@formbricks/ui/components/Label";
import { QuestionFormInput } from "@formbricks/ui/components/QuestionFormInput";
import { ShuffleOptionSelect } from "@formbricks/ui/components/ShuffleOptionSelect";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@formbricks/ui/components/Select";
import { QuestionOptionChoice } from "./QuestionOptionChoice";
interface RankingQuestionFormProps {
@@ -216,12 +227,29 @@ export const RankingQuestionForm = ({
onClick={() => addOption()}>
Add option
</Button>
<ShuffleOptionSelect
shuffleOptionsTypes={shuffleOptionsTypes}
updateQuestion={updateQuestion}
shuffleOption={question.shuffleOption}
questionIdx={questionIdx}
/>
<Select
defaultValue={question.shuffleOption}
value={question.shuffleOption}
onValueChange={(option: TShuffleOption) => {
updateQuestion(questionIdx, { shuffleOption: option });
}}>
<SelectTrigger className="w-fit space-x-2 overflow-hidden border-0 font-medium text-slate-600">
<SelectValue placeholder="Select ordering" />
</SelectTrigger>
<SelectContent>
{Object.values(shuffleOptionsTypes).map(
(shuffleOptionsType) =>
shuffleOptionsType.show && (
<SelectItem
key={shuffleOptionsType.id}
value={shuffleOptionsType.id}
title={shuffleOptionsType.label}>
{shuffleOptionsType.label}
</SelectItem>
)
)}
</SelectContent>
</Select>
</div>
</div>
</div>

View File

@@ -73,6 +73,7 @@ export const SettingsView = ({
setLocalSurvey={setLocalSurvey}
environmentId={environment.id}
attributeClasses={attributeClasses}
actionClasses={actionClasses}
segments={segments}
initialSegment={segments.find((segment) => segment.id === localSurvey.segment?.id)}
/>

View File

@@ -178,11 +178,6 @@ export const isEndingCardValid = (
surveyLanguages: TSurveyLanguage[]
) => {
if (card.type === "endScreen") {
const parseResult = z.string().url().safeParse(card.buttonLink);
if (card.buttonLabel !== undefined && !parseResult.success) {
return false;
}
return (
isContentValid(card.headline, surveyLanguages) &&
isContentValid(card.subheader, surveyLanguages) &&
@@ -193,6 +188,7 @@ export const isEndingCardValid = (
if (parseResult.success) {
return card.label?.trim() !== "";
} else {
toast.error("Invalid Redirect Url in Ending card");
return false;
}
}

View File

@@ -2,6 +2,7 @@
import { UsersIcon } from "lucide-react";
import { SegmentSettings } from "@formbricks/ee/advanced-targeting/components/segment-settings";
import { TActionClass } from "@formbricks/types/action-classes";
import { TAttributeClass } from "@formbricks/types/attribute-classes";
import { TSegment, TSegmentWithSurveyNames } from "@formbricks/types/segment";
import { ModalWithTabs } from "@formbricks/ui/components/ModalWithTabs";
@@ -15,6 +16,7 @@ interface EditSegmentModalProps {
currentSegment: TSegmentWithSurveyNames;
segments: TSegment[];
attributeClasses: TAttributeClass[];
actionClasses: TActionClass[];
isAdvancedTargetingAllowed: boolean;
isFormbricksCloud: boolean;
}
@@ -24,6 +26,7 @@ export const EditSegmentModal = ({
open,
setOpen,
currentSegment,
actionClasses,
attributeClasses,
segments,
isAdvancedTargetingAllowed,
@@ -33,6 +36,7 @@ export const EditSegmentModal = ({
if (isAdvancedTargetingAllowed) {
return (
<SegmentSettings
actionClasses={actionClasses}
attributeClasses={attributeClasses}
environmentId={environmentId}
initialSegment={currentSegment}

View File

@@ -1,3 +1,4 @@
import { TActionClass } from "@formbricks/types/action-classes";
import { TAttributeClass } from "@formbricks/types/attribute-classes";
import { TSegment } from "@formbricks/types/segment";
import { SegmentTableDataRowContainer } from "./SegmentTableDataRowContainer";
@@ -5,11 +6,13 @@ import { SegmentTableDataRowContainer } from "./SegmentTableDataRowContainer";
type TSegmentTableProps = {
segments: TSegment[];
attributeClasses: TAttributeClass[];
actionClasses: TActionClass[];
isAdvancedTargetingAllowed: boolean;
};
export const SegmentTable = ({
segments,
actionClasses,
attributeClasses,
isAdvancedTargetingAllowed,
}: TSegmentTableProps) => {
@@ -29,6 +32,7 @@ export const SegmentTable = ({
<SegmentTableDataRowContainer
currentSegment={segment}
segments={segments}
actionClasses={actionClasses}
attributeClasses={attributeClasses}
isAdvancedTargetingAllowed={isAdvancedTargetingAllowed}
/>

View File

@@ -3,6 +3,7 @@
import { format, formatDistanceToNow } from "date-fns";
import { UsersIcon } from "lucide-react";
import { useState } from "react";
import { TActionClass } from "@formbricks/types/action-classes";
import { TAttributeClass } from "@formbricks/types/attribute-classes";
import { TSegment, TSegmentWithSurveyNames } from "@formbricks/types/segment";
import { EditSegmentModal } from "./EditSegmentModal";
@@ -11,12 +12,14 @@ type TSegmentTableDataRowProps = {
currentSegment: TSegmentWithSurveyNames;
segments: TSegment[];
attributeClasses: TAttributeClass[];
actionClasses: TActionClass[];
isAdvancedTargetingAllowed: boolean;
isFormbricksCloud: boolean;
};
export const SegmentTableDataRow = ({
currentSegment,
actionClasses,
attributeClasses,
segments,
isAdvancedTargetingAllowed,
@@ -62,6 +65,7 @@ export const SegmentTableDataRow = ({
open={isEditSegmentModalOpen}
setOpen={setIsEditSegmentModalOpen}
currentSegment={currentSegment}
actionClasses={actionClasses}
attributeClasses={attributeClasses}
segments={segments}
isAdvancedTargetingAllowed={isAdvancedTargetingAllowed}

View File

@@ -1,5 +1,6 @@
import { IS_FORMBRICKS_CLOUD } from "@formbricks/lib/constants";
import { getSurveysBySegmentId } from "@formbricks/lib/survey/service";
import { TActionClass } from "@formbricks/types/action-classes";
import { TAttributeClass } from "@formbricks/types/attribute-classes";
import { TSegment } from "@formbricks/types/segment";
import { SegmentTableDataRow } from "./SegmentTableDataRow";
@@ -8,12 +9,14 @@ type TSegmentTableDataRowProps = {
currentSegment: TSegment;
segments: TSegment[];
attributeClasses: TAttributeClass[];
actionClasses: TActionClass[];
isAdvancedTargetingAllowed: boolean;
};
export const SegmentTableDataRowContainer = async ({
currentSegment,
segments,
actionClasses,
attributeClasses,
isAdvancedTargetingAllowed,
}: TSegmentTableDataRowProps) => {
@@ -35,6 +38,7 @@ export const SegmentTableDataRowContainer = async ({
inactiveSurveys,
}}
segments={segments}
actionClasses={actionClasses}
attributeClasses={attributeClasses}
isAdvancedTargetingAllowed={isAdvancedTargetingAllowed}
isFormbricksCloud={IS_FORMBRICKS_CLOUD}

View File

@@ -3,6 +3,7 @@ import { BasicCreateSegmentModal } from "@/app/(app)/environments/[environmentId
import { SegmentTable } from "@/app/(app)/environments/[environmentId]/(people)/segments/components/SegmentTable";
import { CreateSegmentModal } from "@formbricks/ee/advanced-targeting/components/create-segment-modal";
import { getAdvancedTargetingPermission } from "@formbricks/ee/lib/service";
import { getActionClasses } from "@formbricks/lib/actionClass/service";
import { getAttributeClasses } from "@formbricks/lib/attributeClass/service";
import { IS_FORMBRICKS_CLOUD } from "@formbricks/lib/constants";
import { getEnvironment } from "@formbricks/lib/environment/service";
@@ -12,10 +13,11 @@ import { PageContentWrapper } from "@formbricks/ui/components/PageContentWrapper
import { PageHeader } from "@formbricks/ui/components/PageHeader";
const Page = async ({ params }) => {
const [environment, segments, attributeClasses, organization] = await Promise.all([
const [environment, segments, attributeClasses, actionClasses, organization] = await Promise.all([
getEnvironment(params.environmentId),
getSegments(params.environmentId),
getAttributeClasses(params.environmentId),
getActionClasses(params.environmentId),
getOrganizationByEnvironmentId(params.environmentId),
]);
@@ -39,6 +41,7 @@ const Page = async ({ params }) => {
isAdvancedTargetingAllowed ? (
<CreateSegmentModal
environmentId={params.environmentId}
actionClasses={actionClasses}
attributeClasses={attributeClasses}
segments={filteredSegments}
/>
@@ -57,6 +60,7 @@ const Page = async ({ params }) => {
</PageHeader>
<SegmentTable
segments={filteredSegments}
actionClasses={actionClasses}
attributeClasses={attributeClasses}
isAdvancedTargetingAllowed={isAdvancedTargetingAllowed}
/>

View File

@@ -84,7 +84,7 @@ export const DisableTwoFactorModal = ({ open, setOpen }: TDisableTwoFactorModalP
placeholder="*******"
aria-placeholder="password"
required
className="focus:border-brand-dark focus:ring-brand-dark block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
className="focus:border-brand focus:ring-brand block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
{...field}
/>

View File

@@ -83,7 +83,7 @@ const ConfirmPasswordForm = ({
placeholder="*******"
aria-placeholder="password"
required
className="focus:border-brand-dark focus:ring-brand-dark block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
className="focus:border-brand focus:ring-brand block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
{...field}
/>

View File

@@ -29,7 +29,6 @@ export const SuccessMessage = ({ environment, survey }: SummaryMetadataProps) =>
? "Almost there! Install widget to start receiving responses."
: "Congrats! Your survey is live.",
{
id: "survey-publish-success-toast",
icon: isAppSurvey && !widgetSetupCompleted ? "🤏" : "🎉",
duration: 5000,
position: "bottom-right",

View File

@@ -53,7 +53,7 @@ export const PasswordResetForm = ({}) => {
type="email"
autoComplete="email"
required
className="focus:border-brand-dark focus:ring-brand-dark block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
className="focus:border-brand focus:ring-brand block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
/>
</div>
</div>

View File

@@ -69,7 +69,7 @@ export const ResetPasswordForm = () => {
autoComplete="current-password"
placeholder="*******"
required
className="focus:border-brand-dark focus:ring-brand-dark mt-2 block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
className="focus:border-brand focus:ring-brand mt-2 block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
/>
</div>
<div>
@@ -84,7 +84,7 @@ export const ResetPasswordForm = () => {
autoComplete="current-password"
placeholder="*******"
required
className="focus:border-brand-dark focus:ring-brand-dark mt-2 block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
className="focus:border-brand focus:ring-brand mt-2 block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
/>
</div>

View File

@@ -156,7 +156,7 @@ export const SigninForm = ({
required
placeholder="work@email.com"
defaultValue={searchParams?.get("email") || ""}
className="focus:border-brand-dark focus:ring-brand-dark block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
className="focus:border-brand focus:ring-brand block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
{...formMethods.register("email", {
required: true,
pattern: /\S+@\S+\.\S+/,
@@ -178,7 +178,7 @@ export const SigninForm = ({
aria-placeholder="password"
onFocus={() => setIsPasswordFocused(true)}
required
className="focus:border-brand-dark focus:ring-brand-dark block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
className="focus:border-brand focus:ring-brand block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
{...field}
/>
)}

View File

@@ -17,7 +17,7 @@ export const TwoFactorBackup = () => {
id="totpBackup"
required
placeholder="XXXXX-XXXXX"
className="focus:border-brand-dark focus:ring-brand-dark block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
className="focus:border-brand focus:ring-brand block w-full rounded-md border-slate-300 shadow-sm sm:text-sm"
{...register("backupCode")}
/>
</div>

View File

@@ -2,9 +2,9 @@ import { responses } from "@/app/lib/api/response";
import fs from "fs/promises";
import { NextRequest } from "next/server";
export const GET = async (_: NextRequest, { params }: { params: { package: string } }) => {
export const GET = async (_: NextRequest, { params }: { params: { slug: string } }) => {
let path: string;
const packageRequested = params.package;
const packageRequested = params["package"];
switch (packageRequested) {
case "app":
@@ -21,7 +21,7 @@ export const GET = async (_: NextRequest, { params }: { params: { package: strin
"package",
packageRequested,
true,
"public, max-age=600, s-maxage=600, stale-while-revalidate=600, stale-if-error=600" // 10 minutes cache for not found
"public, s-maxage=600, max-age=1800, stale-while-revalidate=600, stale-if-error=600"
);
}
@@ -30,26 +30,16 @@ export const GET = async (_: NextRequest, { params }: { params: { package: strin
return new Response(packageSrcCode, {
headers: {
"Content-Type": "application/javascript",
"Cache-Control":
"public, max-age=3600, s-maxage=604800, stale-while-revalidate=3600, stale-if-error=3600",
"Cache-Control": "public, s-maxage=600, max-age=1800, stale-while-revalidate=600, stale-if-error=600",
"Access-Control-Allow-Origin": "*",
},
});
} catch (error: any) {
if (error.code === "ENOENT") {
return responses.notFoundResponse(
"package",
packageRequested,
true,
"public, max-age=600, s-maxage=600, stale-while-revalidate=600, stale-if-error=600" // 10 minutes cache for file not found errors
);
} else {
console.error("Error reading file:", error);
return responses.internalServerErrorResponse(
"internal server error",
true,
"public, max-age=600, s-maxage=600, stale-while-revalidate=600, stale-if-error=600" // 10 minutes cache for internal errors
);
}
} catch (error) {
console.error("Error reading file:", error);
return responses.internalServerErrorResponse(
"file not found:",
true,
"public, s-maxage=600, max-age=1800, stale-while-revalidate=600, stale-if-error=600"
);
}
};

View File

@@ -1,5 +1,6 @@
import { responses } from "@/app/lib/api/response";
import { transformErrorToDetails } from "@/app/lib/api/validator";
import { Prisma } from "@prisma/client";
import { headers } from "next/headers";
import { prisma } from "@formbricks/database";
import { sendResponseFinishedEmail } from "@formbricks/email";
@@ -114,7 +115,7 @@ export const POST = async (request: Request) => {
},
notificationSettings: {
path: ["alert", surveyId],
equals: true,
not: Prisma.JsonNull,
},
},
select: { email: true },

View File

@@ -9,13 +9,17 @@ import { getDisplaysByUserId } from "@formbricks/lib/display/service";
import { environmentCache } from "@formbricks/lib/environment/cache";
import { getEnvironment } from "@formbricks/lib/environment/service";
import { organizationCache } from "@formbricks/lib/organization/cache";
import { getOrganizationByEnvironmentId } from "@formbricks/lib/organization/service";
import {
getMonthlyActiveOrganizationPeopleCount,
getOrganizationByEnvironmentId,
} from "@formbricks/lib/organization/service";
import { personCache } from "@formbricks/lib/person/cache";
import { getPersonByUserId } from "@formbricks/lib/person/service";
import { getIsPersonMonthlyActive, getPersonByUserId } from "@formbricks/lib/person/service";
import { sendPlanLimitsReachedEventToPosthogWeekly } from "@formbricks/lib/posthogServer";
import { responseCache } from "@formbricks/lib/response/cache";
import { getResponsesByUserId } from "@formbricks/lib/response/service";
import { segmentCache } from "@formbricks/lib/segment/cache";
import { ResourceNotFoundError } from "@formbricks/types/errors";
import { OperationNotAllowedError, ResourceNotFoundError } from "@formbricks/types/errors";
import { TJsPersonState } from "@formbricks/types/js";
/**
@@ -26,6 +30,7 @@ import { TJsPersonState } from "@formbricks/types/js";
* @returns The person state
* @throws {ValidationError} - If the input is invalid
* @throws {ResourceNotFoundError} - If the environment or organization is not found
* @throws {OperationNotAllowedError} - If the MAU limit is reached and the person has not been active this month
*/
export const getPersonState = async ({
environmentId,
@@ -51,21 +56,60 @@ export const getPersonState = async ({
throw new ResourceNotFoundError(`organization`, environmentId);
}
let isMauLimitReached = false;
if (IS_FORMBRICKS_CLOUD) {
const currentMau = await getMonthlyActiveOrganizationPeopleCount(organization.id);
const monthlyMiuLimit = organization.billing.limits.monthly.miu;
isMauLimitReached = monthlyMiuLimit !== null && currentMau >= monthlyMiuLimit;
}
let person = await getPersonByUserId(environmentId, userId);
if (!person) {
person = await prisma.person.create({
data: {
environment: {
connect: {
id: environmentId,
if (isMauLimitReached) {
// MAU limit reached: check if person has been active this month; only continue if person has been active
try {
await sendPlanLimitsReachedEventToPosthogWeekly(environmentId, {
plan: organization.billing.plan,
limits: {
monthly: {
miu: organization.billing.limits.monthly.miu,
responses: organization.billing.limits.monthly.responses,
},
},
userId,
},
});
});
} catch (err) {
console.error(`Error sending plan limits reached event to Posthog: ${err}`);
}
revalidatePerson = true;
const errorMessage = `Monthly Active Users limit in the current plan is reached in ${environmentId}`;
if (!person) {
// if it's a new person and MAU limit is reached, throw an error
throw new OperationNotAllowedError(errorMessage);
}
// check if person has been active this month
const isPersonMonthlyActive = await getIsPersonMonthlyActive(person.id);
if (!isPersonMonthlyActive) {
throw new OperationNotAllowedError(errorMessage);
}
} else {
// MAU limit not reached: create person if not exists
if (!person) {
person = await prisma.person.create({
data: {
environment: {
connect: {
id: environmentId,
},
},
userId,
},
});
revalidatePerson = true;
}
}
const personResponses = await getResponsesByUserId(environmentId, userId);

View File

@@ -32,6 +32,7 @@ export const getPersonSegmentIds = (
const isIncluded = await evaluateSegment(
{
attributes,
actionIds: [],
deviceType,
environmentId,
personId: person.id,

View File

@@ -7,10 +7,11 @@ import { getAttributes } from "@formbricks/lib/attribute/service";
import { IS_FORMBRICKS_CLOUD } from "@formbricks/lib/constants";
import { getEnvironment, updateEnvironment } from "@formbricks/lib/environment/service";
import {
getMonthlyActiveOrganizationPeopleCount,
getMonthlyOrganizationResponseCount,
getOrganizationByEnvironmentId,
} from "@formbricks/lib/organization/service";
import { createPerson, getPersonByUserId } from "@formbricks/lib/person/service";
import { createPerson, getIsPersonMonthlyActive, getPersonByUserId } from "@formbricks/lib/person/service";
import {
capturePosthogEnvironmentEvent,
sendPlanLimitsReachedEventToPosthogWeekly,
@@ -83,31 +84,81 @@ export const GET = async (
throw new Error("Organization does not exist");
}
// check if response limit is reached
let isAppSurveyResponseLimitReached = false;
// check if MAU limit is reached
let isMauLimitReached = false;
let isMonthlyResponsesLimitReached = false;
if (IS_FORMBRICKS_CLOUD) {
const currentResponseCount = await getMonthlyOrganizationResponseCount(organization.id);
const currentMau = await getMonthlyActiveOrganizationPeopleCount(organization.id);
const monthlyResponseLimit = organization.billing.limits.monthly.responses;
const monthlyMiuLimit = organization.billing.limits.monthly.miu;
isAppSurveyResponseLimitReached =
isMauLimitReached = monthlyMiuLimit !== null && currentMau >= monthlyMiuLimit;
const currentResponseCount = await getMonthlyOrganizationResponseCount(organization.id);
isMonthlyResponsesLimitReached =
monthlyResponseLimit !== null && currentResponseCount >= monthlyResponseLimit;
if (isAppSurveyResponseLimitReached) {
try {
await sendPlanLimitsReachedEventToPosthogWeekly(environmentId, {
plan: organization.billing.plan,
limits: { monthly: { responses: monthlyResponseLimit, miu: null } },
});
} catch (error) {
console.error(`Error sending plan limits reached event to Posthog: ${error}`);
}
}
}
let person = await getPersonByUserId(environmentId, userId);
if (!person) {
person = await createPerson(environmentId, userId);
if (isMauLimitReached) {
// MAU limit reached: check if person has been active this month; only continue if person has been active
try {
await sendPlanLimitsReachedEventToPosthogWeekly(environmentId, {
plan: organization.billing.plan,
limits: {
monthly: {
miu: organization.billing.limits.monthly.miu,
responses: organization.billing.limits.monthly.responses,
},
},
});
} catch (err) {
console.error(`Error sending plan limits reached event to Posthog: ${err}`);
}
const errorMessage = `Monthly Active Users limit in the current plan is reached in ${environmentId}`;
if (!person) {
// if it's a new person and MAU limit is reached, throw an error
return responses.tooManyRequestsResponse(
errorMessage,
true,
"public, s-maxage=600, max-age=840, stale-while-revalidate=600, stale-if-error=600"
);
}
// check if person has been active this month
const isPersonMonthlyActive = await getIsPersonMonthlyActive(person.id);
if (!isPersonMonthlyActive) {
return responses.tooManyRequestsResponse(
errorMessage,
true,
"public, s-maxage=600, max-age=840, stale-while-revalidate=600, stale-if-error=600"
);
}
} else {
// MAU limit not reached: create person if not exists
if (!person) {
person = await createPerson(environmentId, userId);
}
}
if (isMonthlyResponsesLimitReached) {
try {
await sendPlanLimitsReachedEventToPosthogWeekly(environmentId, {
plan: organization.billing.plan,
limits: {
monthly: {
miu: organization.billing.limits.monthly.miu,
responses: organization.billing.limits.monthly.responses,
},
},
});
} catch (err) {
console.error(`Error sending plan limits reached event to Posthog: ${err}`);
}
}
const [surveys, actionClasses] = await Promise.all([
@@ -135,7 +186,7 @@ export const GET = async (
// creating state object
let state: TJsAppStateSync = {
surveys: !isAppSurveyResponseLimitReached
surveys: !isMonthlyResponsesLimitReached
? transformedSurveys.map((survey) => replaceAttributeRecall(survey, attributes))
: [],
actionClasses,

View File

@@ -16,8 +16,8 @@ export const LegalFooter = ({
if (!IMPRINT_URL && !PRIVACY_URL && !IS_FORMBRICKS_CLOUD) return null;
return (
<div className="absolute bottom-0 z-[1500] h-10 w-full">
<div className="mx-auto flex h-full max-w-lg items-center justify-center p-2 text-center text-xs text-slate-400 text-opacity-50">
<div className="absolute bottom-0 h-10 w-full">
<div className="mx-auto max-w-lg p-2 text-center text-xs text-slate-400 text-opacity-50">
{IMPRINT_URL && (
<Link href={IMPRINT_URL} target="_blank" className="hover:underline">
Imprint

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 415 KiB

View File

@@ -2,4 +2,4 @@
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.

View File

@@ -16,16 +16,6 @@ Your turn 👇
////////////////////////////
---
» 02-October-2024 by [@Jemeni11\_](https://x.com/Jemeni11_)
---
» 03-October-2024 by [@adityadeshlahre](https://x.com/adityadeshlahre/)
» 03-October-2024 by [@HarshBhatX](https://x.com/HarshBhatX/status/HarshBhatX)
---
» 03-October-2024 by [@Ionfinisher](https://x.com/ion_finisher/)
» 01-October-2024 by X
---

View File

@@ -17,5 +17,5 @@ Your turn 👇
////////////////////////////
» 01-October-2024 by X
» 03-October-2024 by [@Recent-Highlight-449](https://www.reddit.com/user/Recent-Highlight-449/)
---

View File

@@ -19,10 +19,7 @@ Your turn 👇
////////////////////////////
» 03-Octobet-2024 by Harsh Bhat
» Link 1: https://youtu.be/pcC4Dr6Wj2Q?si=j1Rftb57M0V6vfLS
» Link 2: https://youtu.be/NQi1CdGo6dU?si=Dhe_sVaT27MOrYVj
» Link 3: https://youtu.be/hI4RksyFE2k?si=tgREw0wQ_tirD41O
» 05-April-2024 by X
» Link 1: https...
---

View File

@@ -1,88 +0,0 @@
/* eslint-disable @typescript-eslint/restrict-template-expressions -- using template strings for logging */
/* eslint-disable no-console -- logging is allowed in migration scripts */
import { PrismaClient } from "@prisma/client";
import type { TBaseFilter, TBaseFilters } from "@formbricks/types/segment";
const prisma = new PrismaClient();
function removeActionFilters(filters: TBaseFilters): TBaseFilters {
const cleanedFilters = filters.reduce((acc: TBaseFilters, filter: TBaseFilter) => {
if (Array.isArray(filter.resource)) {
// If it's a group, recursively clean it
const cleanedGroup = removeActionFilters(filter.resource);
if (cleanedGroup.length > 0) {
acc.push({
...filter,
resource: cleanedGroup,
});
}
// @ts-expect-error -- we're checking for an older type of filter
} else if (filter.resource.root.type !== "action") {
// If it's not an action filter, keep it
acc.push(filter);
}
// Action filters are implicitly removed by not being added to acc
return acc;
}, []);
// Ensure the first filter in the group has a null connector
return cleanedFilters.map((filter, index) => {
if (index === 0) {
return { ...filter, connector: null };
}
return filter;
});
}
async function runMigration(): Promise<void> {
await prisma.$transaction(
async (tx) => {
console.log("Starting the data migration...");
const segmentsToUpdate = await tx.segment.findMany({});
console.log(`Found ${segmentsToUpdate.length} total segments`);
let changedFiltersCount = 0;
const updatePromises = segmentsToUpdate.map((segment) => {
const updatedFilters = removeActionFilters(segment.filters);
if (JSON.stringify(segment.filters) !== JSON.stringify(updatedFilters)) {
changedFiltersCount++;
}
return tx.segment.update({
where: { id: segment.id },
data: { filters: updatedFilters },
});
});
await Promise.all(updatePromises);
console.log(`Successfully updated ${changedFiltersCount} segments`);
},
{
timeout: 180000, // 3 minutes
}
);
}
function handleError(error: unknown): void {
console.error("An error occurred during migration:", error);
process.exit(1);
}
function handleDisconnectError(): void {
console.error("Failed to disconnect Prisma client");
process.exit(1);
}
function main(): void {
runMigration()
.catch(handleError)
.finally(() => {
prisma.$disconnect().catch(handleDisconnectError);
});
}
main();

View File

@@ -1,14 +0,0 @@
/*
Warnings:
- You are about to drop the `Action` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropForeignKey
ALTER TABLE "Action" DROP CONSTRAINT "Action_actionClassId_fkey";
-- DropForeignKey
ALTER TABLE "Action" DROP CONSTRAINT "Action_personId_fkey";
-- DropTable
DROP TABLE "Action";

View File

@@ -50,8 +50,7 @@
"data-migration:v2.5": "pnpm data-migration:remove-dismissed-value-inconsistency",
"data-migration:add-display-id-to-response": "ts-node ./data-migrations/20240905120500_refactor_display_response_relationship/data-migration.ts",
"data-migration:address-question": "ts-node ./data-migrations/20240924123456_migrate_address_question/data-migration.ts",
"data-migration:advanced-logic": "ts-node ./data-migrations/20240828122408_advanced_logic_editor/data-migration.ts",
"data-migration:segments-actions-cleanup": "ts-node ./data-migrations/20240904091113_removed_actions_table/data-migration.ts"
"data-migration:advanced-logic": "ts-node ./data-migrations/20240828122408_advanced_logic_editor/data-migration.ts"
},
"dependencies": {
"@prisma/client": "^5.18.0",

View File

@@ -100,6 +100,7 @@ model Person {
responses Response[]
attributes Attribute[]
displays Display[]
actions Action[]
@@unique([environmentId, userId])
@@index([environmentId])
@@ -354,12 +355,30 @@ model ActionClass {
environment Environment @relation(fields: [environmentId], references: [id], onDelete: Cascade)
environmentId String
surveyTriggers SurveyTrigger[]
actions Action[]
@@unique([key, environmentId])
@@unique([name, environmentId])
@@index([environmentId, createdAt])
}
model Action {
id String @id @default(cuid())
createdAt DateTime @default(now()) @map(name: "created_at")
actionClass ActionClass @relation(fields: [actionClassId], references: [id], onDelete: Cascade)
actionClassId String
person Person @relation(fields: [personId], references: [id], onDelete: Cascade)
personId String
/// @zod.custom(imports.ZActionProperties)
/// @zod.custom(imports.ZActionProperties)
/// [ActionProperties]
properties Json @default("{}")
@@index([personId, actionClassId, createdAt])
@@index([actionClassId, createdAt])
@@index([personId, createdAt])
}
enum EnvironmentType {
production
development

View File

@@ -1,9 +1,10 @@
"use client";
import { createId } from "@paralleldrive/cuid2";
import { FingerprintIcon, MonitorSmartphoneIcon, TagIcon, Users2Icon } from "lucide-react";
import { FingerprintIcon, MonitorSmartphoneIcon, MousePointerClick, TagIcon, Users2Icon } from "lucide-react";
import React, { useMemo, useState } from "react";
import { cn } from "@formbricks/lib/cn";
import type { TActionClass } from "@formbricks/types/action-classes";
import type { TAttributeClass } from "@formbricks/types/attribute-classes";
import type {
TBaseFilter,
@@ -19,11 +20,12 @@ interface TAddFilterModalProps {
open: boolean;
setOpen: (open: boolean) => void;
onAddFilter: (filter: TBaseFilter) => void;
actionClasses: TActionClass[];
attributeClasses: TAttributeClass[];
segments: TSegment[];
}
type TFilterType = "attribute" | "segment" | "device" | "person";
type TFilterType = "action" | "attribute" | "segment" | "device" | "person";
const handleAddFilter = ({
type,
@@ -31,15 +33,41 @@ const handleAddFilter = ({
setOpen,
attributeClassName,
deviceType,
actionClassId,
segmentId,
}: {
type: TFilterType;
onAddFilter: (filter: TBaseFilter) => void;
setOpen: (open: boolean) => void;
actionClassId?: string;
attributeClassName?: string;
segmentId?: string;
deviceType?: string;
}): void => {
if (type === "action") {
if (!actionClassId) return;
const newFilter: TBaseFilter = {
id: createId(),
connector: "and",
resource: {
id: createId(),
root: {
type,
actionClassId,
},
qualifier: {
metric: "occuranceCount",
operator: "greaterThan",
},
value: "",
},
};
onAddFilter(newFilter);
setOpen(false);
}
if (type === "attribute") {
if (!attributeClassName) return;
@@ -204,6 +232,7 @@ export function AddFilterModal({
onAddFilter,
open,
setOpen,
actionClasses,
attributeClasses,
segments,
}: TAddFilterModalProps) {
@@ -229,6 +258,14 @@ export function AddFilterModal({
[]
);
const actionClassesFiltered = useMemo(() => {
if (!searchValue) return actionClasses;
return actionClasses.filter((actionClass) =>
actionClass.name.toLowerCase().includes(searchValue.toLowerCase())
);
}, [actionClasses, searchValue]);
const attributeClassesFiltered = useMemo(() => {
if (!attributeClasses) return [];
@@ -268,11 +305,18 @@ export function AddFilterModal({
{
attributes: attributeClassesFiltered,
personAttributes: personAttributesFiltered,
actions: actionClassesFiltered,
segments: segmentsFiltered,
devices: deviceTypesFiltered,
},
],
[attributeClassesFiltered, deviceTypesFiltered, personAttributesFiltered, segmentsFiltered]
[
actionClassesFiltered,
attributeClassesFiltered,
deviceTypesFiltered,
personAttributesFiltered,
segmentsFiltered,
]
);
const getAllTabContent = () => {
@@ -370,6 +414,35 @@ export function AddFilterModal({
);
};
const getActionsTabContent = () => {
return (
<>
{actionClassesFiltered.length === 0 && (
<div className="flex w-full items-center justify-center gap-4 rounded-lg px-2 py-1 text-sm">
<p>There are no actions yet!</p>
</div>
)}
{actionClassesFiltered.map((actionClass) => {
return (
<div
className="flex cursor-pointer items-center gap-4 rounded-lg px-2 py-1 text-sm hover:bg-slate-50"
onClick={() => {
handleAddFilter({
type: "action",
onAddFilter,
setOpen,
actionClassId: actionClass.id,
});
}}>
<MousePointerClick className="h-4 w-4" />
<p>{actionClass.name}</p>
</div>
);
})}
</>
);
};
const getAttributesTabContent = () => {
return (
<AttributeTabContent
@@ -439,6 +512,9 @@ export function AddFilterModal({
case "all": {
return getAllTabContent();
}
case "actions": {
return getActionsTabContent();
}
case "attributes": {
return getAttributesTabContent();
}

View File

@@ -8,6 +8,7 @@ import React, { useEffect, useMemo, useState } from "react";
import toast from "react-hot-toast";
import { cn } from "@formbricks/lib/cn";
import { structuredClone } from "@formbricks/lib/pollyfills/structuredClone";
import type { TActionClass } from "@formbricks/types/action-classes";
import type { TAttributeClass } from "@formbricks/types/attribute-classes";
import type {
TBaseFilter,
@@ -36,6 +37,7 @@ interface UserTargetingAdvancedCardProps {
localSurvey: TSurvey;
setLocalSurvey: React.Dispatch<React.SetStateAction<TSurvey>>;
environmentId: string;
actionClasses: TActionClass[];
attributeClasses: TAttributeClass[];
segments: TSegment[];
initialSegment?: TSegment;
@@ -45,6 +47,7 @@ export function AdvancedTargetingCard({
localSurvey,
setLocalSurvey,
environmentId,
actionClasses,
attributeClasses,
segments,
initialSegment,
@@ -210,6 +213,7 @@ export function AdvancedTargetingCard({
{Boolean(segment?.filters.length) && (
<div className="w-full">
<SegmentEditor
actionClasses={actionClasses}
attributeClasses={attributeClasses}
environmentId={environmentId}
group={segment.filters}
@@ -265,6 +269,7 @@ export function AdvancedTargetingCard({
</div>
<AddFilterModal
actionClasses={actionClasses}
attributeClasses={attributeClasses}
onAddFilter={(filter) => {
handleAddFilterInGroup(filter);
@@ -297,6 +302,7 @@ export function AdvancedTargetingCard({
{segmentEditorViewOnly && segment ? (
<div className="opacity-60">
<SegmentEditor
actionClasses={actionClasses}
attributeClasses={attributeClasses}
environmentId={environmentId}
group={segment.filters}

View File

@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import toast from "react-hot-toast";
import { structuredClone } from "@formbricks/lib/pollyfills/structuredClone";
import type { TActionClass } from "@formbricks/types/action-classes";
import type { TAttributeClass } from "@formbricks/types/attribute-classes";
import type { TBaseFilter, TSegment } from "@formbricks/types/segment";
import { ZSegmentFilters } from "@formbricks/types/segment";
@@ -19,9 +20,15 @@ interface TCreateSegmentModalProps {
environmentId: string;
segments: TSegment[];
attributeClasses: TAttributeClass[];
actionClasses: TActionClass[];
}
export function CreateSegmentModal({ environmentId, attributeClasses, segments }: TCreateSegmentModalProps) {
export function CreateSegmentModal({
environmentId,
actionClasses,
attributeClasses,
segments,
}: TCreateSegmentModalProps) {
const router = useRouter();
const initialSegmentState = {
title: "",
@@ -190,6 +197,7 @@ export function CreateSegmentModal({ environmentId, attributeClasses, segments }
)}
<SegmentEditor
actionClasses={actionClasses}
attributeClasses={attributeClasses}
environmentId={environmentId}
group={segment.filters}
@@ -209,6 +217,7 @@ export function CreateSegmentModal({ environmentId, attributeClasses, segments }
</Button>
<AddFilterModal
actionClasses={actionClasses}
attributeClasses={attributeClasses}
onAddFilter={(filter) => {
handleAddFilterInGroup(filter);

View File

@@ -11,6 +11,7 @@ import {
moveResource,
toggleGroupConnector,
} from "@formbricks/lib/segment/utils";
import type { TActionClass } from "@formbricks/types/action-classes";
import type { TAttributeClass } from "@formbricks/types/attribute-classes";
import type { TBaseFilter, TBaseFilters, TSegment, TSegmentConnector } from "@formbricks/types/segment";
import { Button } from "@formbricks/ui/components/Button";
@@ -28,6 +29,7 @@ interface TSegmentEditorProps {
environmentId: string;
segment: TSegment;
segments: TSegment[];
actionClasses: TActionClass[];
attributeClasses: TAttributeClass[];
setSegment: React.Dispatch<React.SetStateAction<TSegment | null>>;
viewOnly?: boolean;
@@ -38,6 +40,7 @@ export function SegmentEditor({
environmentId,
setSegment,
segment,
actionClasses,
attributeClasses,
segments,
viewOnly = false,
@@ -119,6 +122,7 @@ export function SegmentEditor({
if (isResourceFilter(resource)) {
return (
<SegmentFilter
actionClasses={actionClasses}
attributeClasses={attributeClasses}
connector={connector}
environmentId={environmentId}
@@ -161,6 +165,7 @@ export function SegmentEditor({
<div className="rounded-lg border-2 border-slate-300 bg-white p-4">
<SegmentEditor
actionClasses={actionClasses}
attributeClasses={attributeClasses}
environmentId={environmentId}
group={resource}
@@ -184,6 +189,7 @@ export function SegmentEditor({
</div>
<AddFilterModal
actionClasses={actionClasses}
attributeClasses={attributeClasses}
onAddFilter={(filter) => {
if (addFilterModalOpenedFromBelow) {

View File

@@ -2,6 +2,7 @@ import {
FingerprintIcon,
MonitorSmartphoneIcon,
MoreVertical,
MousePointerClick,
TagIcon,
Trash2,
Users2Icon,
@@ -11,24 +12,31 @@ import { z } from "zod";
import { cn } from "@formbricks/lib/cn";
import { structuredClone } from "@formbricks/lib/pollyfills/structuredClone";
import {
convertMetricToText,
convertOperatorToText,
convertOperatorToTitle,
toggleFilterConnector,
updateActionClassIdInFilter,
updateAttributeClassNameInFilter,
updateDeviceTypeInFilter,
updateFilterValue,
updateMetricInFilter,
updateOperatorInFilter,
updatePersonIdentifierInFilter,
updateSegmentIdInFilter,
} from "@formbricks/lib/segment/utils";
import { isCapitalized } from "@formbricks/lib/utils/strings";
import type { TActionClass } from "@formbricks/types/action-classes";
import type { TAttributeClass } from "@formbricks/types/attribute-classes";
import type {
TActionMetric,
TArithmeticOperator,
TAttributeOperator,
TBaseFilter,
TBaseOperator,
TDeviceOperator,
TSegment,
TSegmentActionFilter,
TSegmentAttributeFilter,
TSegmentConnector,
TSegmentDeviceFilter,
@@ -39,8 +47,10 @@ import type {
TSegmentSegmentFilter,
} from "@formbricks/types/segment";
import {
ACTION_METRICS,
ARITHMETIC_OPERATORS,
ATTRIBUTE_OPERATORS,
BASE_OPERATORS,
DEVICE_OPERATORS,
PERSON_OPERATORS,
} from "@formbricks/types/segment";
@@ -67,6 +77,7 @@ interface TSegmentFilterProps {
environmentId: string;
segment: TSegment;
segments: TSegment[];
actionClasses: TActionClass[];
attributeClasses: TAttributeClass[];
setSegment: (segment: TSegment) => void;
handleAddFilterBelow: (resourceId: string, filter: TBaseFilter) => void;
@@ -555,6 +566,188 @@ function PersonSegmentFilter({
);
}
type TActionSegmentFilterProps = TSegmentFilterProps & {
onAddFilterBelow: () => void;
resource: TSegmentActionFilter;
updateValueInLocalSurvey: (filterId: string, newValue: TSegmentFilterValue) => void;
};
function ActionSegmentFilter({
connector,
resource,
segment,
setSegment,
onAddFilterBelow,
onCreateGroup,
onDeleteFilter,
onMoveFilter,
updateValueInLocalSurvey,
actionClasses,
viewOnly,
}: TActionSegmentFilterProps) {
const { actionClassId } = resource.root;
const operatorText = convertOperatorToText(resource.qualifier.operator);
const qualifierMetric = resource.qualifier.metric;
const [valueError, setValueError] = useState("");
const operatorArr = BASE_OPERATORS.map((operator) => ({
id: operator,
name: convertOperatorToText(operator),
}));
const actionMetrics = ACTION_METRICS.map((metric) => ({
id: metric,
name: convertMetricToText(metric),
}));
const actionClass = actionClasses.find((actionClass) => actionClass.id === actionClassId)?.name;
const updateOperatorInSegment = (filterId: string, newOperator: TBaseOperator) => {
const updatedSegment = structuredClone(segment);
if (updatedSegment.filters) {
updateOperatorInFilter(updatedSegment.filters, filterId, newOperator);
}
setSegment(updatedSegment);
};
const updateActionClassIdInSegment = (filterId: string, actionClassId: string) => {
const updatedSegment = structuredClone(segment);
if (updatedSegment.filters) {
updateActionClassIdInFilter(updatedSegment.filters, filterId, actionClassId);
}
setSegment(updatedSegment);
};
const updateActionMetricInLocalSurvey = (filterId: string, newMetric: TActionMetric) => {
const updatedSegment = structuredClone(segment);
if (updatedSegment.filters) {
updateMetricInFilter(updatedSegment.filters, filterId, newMetric);
}
setSegment(updatedSegment);
};
const checkValueAndUpdate = (e: React.ChangeEvent<HTMLInputElement>) => {
const { value } = e.target;
updateValueInLocalSurvey(resource.id, value);
if (!value) {
setValueError("Value cannot be empty");
return;
}
const isNumber = z.coerce.number().safeParse(value);
if (isNumber.success) {
setValueError("");
updateValueInLocalSurvey(resource.id, parseInt(value, 10));
} else {
setValueError("Value must be a number");
updateValueInLocalSurvey(resource.id, value);
}
};
return (
<div className="flex items-center gap-2 text-sm">
<SegmentFilterItemConnector
connector={connector}
filterId={resource.id}
key={connector}
segment={segment}
setSegment={setSegment}
viewOnly={viewOnly}
/>
<Select
disabled={viewOnly}
onValueChange={(value) => {
updateActionClassIdInSegment(resource.id, value);
}}
value={actionClass}>
<SelectTrigger
className="w-auto items-center justify-center whitespace-nowrap bg-white capitalize"
hideArrow>
<SelectValue>
<div className="flex items-center gap-1">
<MousePointerClick className="h-4 w-4 text-sm" />
<p>{actionClass}</p>
</div>
</SelectValue>
</SelectTrigger>
<SelectContent className="bottom-0">
{actionClasses.map((actionClass) => (
<SelectItem value={actionClass.id}>{actionClass.name}</SelectItem>
))}
</SelectContent>
</Select>
<Select
disabled={viewOnly}
onValueChange={(value: TActionMetric) => {
updateActionMetricInLocalSurvey(resource.id, value);
}}
value={qualifierMetric}>
<SelectTrigger
className="flex w-auto items-center justify-center whitespace-nowrap bg-white capitalize"
hideArrow>
<SelectValue />
</SelectTrigger>
<SelectContent>
{actionMetrics.map((metric) => (
<SelectItem value={metric.id}>{metric.name}</SelectItem>
))}
</SelectContent>
</Select>
<Select
disabled={viewOnly}
onValueChange={(operator: TBaseOperator) => {
updateOperatorInSegment(resource.id, operator);
}}
value={operatorText}>
<SelectTrigger
className="flex w-full max-w-[40px] items-center justify-center bg-white text-center"
hideArrow>
<SelectValue>
<p>{operatorText}</p>
</SelectValue>
</SelectTrigger>
<SelectContent>
{operatorArr.map((operator) => (
<SelectItem title={convertOperatorToTitle(operator.id)} value={operator.id}>
{operator.name}
</SelectItem>
))}
</SelectContent>
</Select>
<div className="relative flex flex-col gap-1">
<Input
className={cn("w-auto bg-white", valueError && "border border-red-500 focus:border-red-500")}
disabled={viewOnly}
onChange={(e) => {
if (viewOnly) return;
checkValueAndUpdate(e);
}}
value={resource.value}
/>
{valueError ? (
<p className="absolute right-2 -mt-1 rounded-md bg-white px-2 text-xs text-red-500">{valueError}</p>
) : null}
</div>
<SegmentFilterItemContextMenu
filterId={resource.id}
onAddFilterBelow={onAddFilterBelow}
onCreateGroup={onCreateGroup}
onDeleteFilter={onDeleteFilter}
onMoveFilter={onMoveFilter}
viewOnly={viewOnly}
/>
</div>
);
}
type TSegmentSegmentFilterProps = TSegmentFilterProps & {
onAddFilterBelow: () => void;
resource: TSegmentSegmentFilter;
@@ -779,6 +972,7 @@ export function SegmentFilter({
environmentId,
segment,
segments,
actionClasses,
attributeClasses,
setSegment,
handleAddFilterBelow,
@@ -804,6 +998,7 @@ export function SegmentFilter({
function RenderFilterModal() {
return (
<AddFilterModal
actionClasses={actionClasses}
attributeClasses={attributeClasses}
onAddFilter={(filter) => {
handleAddFilterBelow(resource.id, filter);
@@ -816,10 +1011,36 @@ export function SegmentFilter({
}
switch (resource.root.type) {
case "action":
return (
<>
<ActionSegmentFilter
actionClasses={actionClasses}
attributeClasses={attributeClasses}
connector={connector}
environmentId={environmentId}
handleAddFilterBelow={handleAddFilterBelow}
onAddFilterBelow={onAddFilterBelow}
onCreateGroup={onCreateGroup}
onDeleteFilter={onDeleteFilter}
onMoveFilter={onMoveFilter}
resource={resource as TSegmentActionFilter}
segment={segment}
segments={segments}
setSegment={setSegment}
updateValueInLocalSurvey={updateFilterValueInSegment}
viewOnly={viewOnly}
/>
<RenderFilterModal />
</>
);
case "attribute":
return (
<>
<AttributeSegmentFilter
actionClasses={actionClasses}
attributeClasses={attributeClasses}
connector={connector}
environmentId={environmentId}
@@ -844,6 +1065,7 @@ export function SegmentFilter({
return (
<>
<PersonSegmentFilter
actionClasses={actionClasses}
attributeClasses={attributeClasses}
connector={connector}
environmentId={environmentId}
@@ -868,6 +1090,7 @@ export function SegmentFilter({
return (
<>
<SegmentSegmentFilter
actionClasses={actionClasses}
attributeClasses={attributeClasses}
connector={connector}
environmentId={environmentId}
@@ -891,6 +1114,7 @@ export function SegmentFilter({
return (
<>
<DeviceFilter
actionClasses={actionClasses}
attributeClasses={attributeClasses}
connector={connector}
environmentId={environmentId}

View File

@@ -6,6 +6,7 @@ import { useMemo, useState } from "react";
import toast from "react-hot-toast";
import { cn } from "@formbricks/lib/cn";
import { structuredClone } from "@formbricks/lib/pollyfills/structuredClone";
import type { TActionClass } from "@formbricks/types/action-classes";
import type { TAttributeClass } from "@formbricks/types/attribute-classes";
import type { TBaseFilter, TSegment, TSegmentWithSurveyNames } from "@formbricks/types/segment";
import { ZSegmentFilters } from "@formbricks/types/segment";
@@ -22,12 +23,14 @@ interface TSegmentSettingsTabProps {
initialSegment: TSegmentWithSurveyNames;
segments: TSegment[];
attributeClasses: TAttributeClass[];
actionClasses: TActionClass[];
}
export function SegmentSettings({
environmentId,
initialSegment,
setOpen,
actionClasses,
attributeClasses,
segments,
}: TSegmentSettingsTabProps) {
@@ -179,6 +182,7 @@ export function SegmentSettings({
)}
<SegmentEditor
actionClasses={actionClasses}
attributeClasses={attributeClasses}
environmentId={environmentId}
group={segment.filters}
@@ -199,6 +203,7 @@ export function SegmentSettings({
</div>
<AddFilterModal
actionClasses={actionClasses}
attributeClasses={attributeClasses}
onAddFilter={(filter) => {
handleAddFilterInGroup(filter);

View File

@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2024 Formbricks GmbH
Copyright (c) 2023 Formbricks GmbH
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

View File

@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2024 Formbricks GmbH
Copyright (c) 2023 Formbricks GmbH
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

View File

@@ -0,0 +1,25 @@
import { revalidateTag } from "next/cache";
interface RevalidateProps {
environmentId?: string;
personId?: string;
}
export const actionCache = {
tag: {
byEnvironmentId(environmentId: string): string {
return `environments-${environmentId}-actions`;
},
byPersonId(personId: string): string {
return `environments-${personId}-actions`;
},
},
revalidate({ environmentId, personId }: RevalidateProps): void {
if (environmentId) {
revalidateTag(this.tag.byEnvironmentId(environmentId));
}
if (personId) {
revalidateTag(this.tag.byPersonId(personId));
}
},
};

View File

@@ -0,0 +1,442 @@
import "server-only";
import { Prisma } from "@prisma/client";
import { differenceInDays } from "date-fns";
import { cache as reactCache } from "react";
import { prisma } from "@formbricks/database";
import { TAction, TActionInput, ZActionInput } from "@formbricks/types/actions";
import { ZOptionalNumber } from "@formbricks/types/common";
import { ZId } from "@formbricks/types/common";
import { DatabaseError, OperationNotAllowedError } from "@formbricks/types/errors";
import { actionClassCache } from "../actionClass/cache";
import { getActionClassByEnvironmentIdAndName } from "../actionClass/service";
import { cache } from "../cache";
import { ITEMS_PER_PAGE } from "../constants";
import { activePersonCache } from "../person/cache";
import { getIsPersonMonthlyActive } from "../person/service";
import { validateInputs } from "../utils/validate";
import { actionCache } from "./cache";
import { getStartDateOfLastMonth, getStartDateOfLastQuarter, getStartDateOfLastWeek } from "./utils";
export const getActionsByPersonId = reactCache(
async (personId: string, page?: number): Promise<TAction[]> =>
cache(
async () => {
validateInputs([personId, ZId], [page, ZOptionalNumber]);
try {
const actionsPrisma = await prisma.action.findMany({
where: {
person: {
id: personId,
},
},
orderBy: {
createdAt: "desc",
},
take: page ? ITEMS_PER_PAGE : undefined,
skip: page ? ITEMS_PER_PAGE * (page - 1) : undefined,
include: {
actionClass: true,
},
});
return actionsPrisma.map((action) => ({
id: action.id,
createdAt: action.createdAt,
personId: action.personId,
properties: action.properties,
actionClass: action.actionClass,
}));
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
throw new DatabaseError("Database operation failed");
}
throw error;
}
},
[`getActionsByPersonId-${personId}-${page}`],
{
tags: [actionCache.tag.byPersonId(personId)],
}
)()
);
export const getActionsByEnvironmentId = reactCache(
async (environmentId: string, page?: number): Promise<TAction[]> =>
cache(
async () => {
validateInputs([environmentId, ZId], [page, ZOptionalNumber]);
try {
const actionsPrisma = await prisma.action.findMany({
where: {
actionClass: {
environmentId: environmentId,
},
},
orderBy: {
createdAt: "desc",
},
take: page ? ITEMS_PER_PAGE : undefined,
skip: page ? ITEMS_PER_PAGE * (page - 1) : undefined,
include: {
actionClass: true,
},
});
const actions: TAction[] = [];
// transforming response to type TAction[]
actionsPrisma.forEach((action) => {
actions.push({
id: action.id,
createdAt: action.createdAt,
// sessionId: action.sessionId,
personId: action.personId,
properties: action.properties,
actionClass: action.actionClass,
});
});
return actions;
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
throw new DatabaseError("Database operation failed");
}
throw error;
}
},
[`getActionsByEnvironmentId-${environmentId}-${page}`],
{
tags: [actionCache.tag.byEnvironmentId(environmentId)],
}
)()
);
export const createAction = async (data: TActionInput): Promise<TAction> => {
validateInputs([data, ZActionInput]);
try {
const { environmentId, name, userId } = data;
let actionClass = await getActionClassByEnvironmentIdAndName(environmentId, name);
if (!actionClass) {
throw new OperationNotAllowedError(
`${name} action unknown. Please add this action in Formbricks first in order to use it in your code.`
);
}
const action = await prisma.action.create({
data: {
person: {
connect: {
environmentId_userId: {
environmentId,
userId,
},
},
},
actionClass: {
connect: {
id: actionClass.id,
},
},
},
});
const isPersonMonthlyActive = await getIsPersonMonthlyActive(action.personId);
if (!isPersonMonthlyActive) {
activePersonCache.revalidate({ id: action.personId });
}
actionCache.revalidate({
environmentId,
personId: action.personId,
});
return {
id: action.id,
createdAt: action.createdAt,
personId: action.personId,
properties: action.properties,
actionClass,
};
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
throw new DatabaseError("Database operation failed");
}
throw error;
}
};
export const getActionCountInLastHour = reactCache(
async (actionClassId: string): Promise<number> =>
cache(
async () => {
validateInputs([actionClassId, ZId]);
try {
const numEventsLastHour = await prisma.action.count({
where: {
actionClassId: actionClassId,
createdAt: {
gte: new Date(Date.now() - 60 * 60 * 1000),
},
},
});
return numEventsLastHour;
} catch (error) {
throw error;
}
},
[`getActionCountInLastHour-${actionClassId}`],
{
tags: [actionClassCache.tag.byId(actionClassId)],
}
)()
);
export const getActionCountInLast24Hours = reactCache(
async (actionClassId: string): Promise<number> =>
cache(
async () => {
validateInputs([actionClassId, ZId]);
try {
const numEventsLast24Hours = await prisma.action.count({
where: {
actionClassId: actionClassId,
createdAt: {
gte: new Date(Date.now() - 24 * 60 * 60 * 1000),
},
},
});
return numEventsLast24Hours;
} catch (error) {
throw error;
}
},
[`getActionCountInLast24Hours-${actionClassId}`],
{
tags: [actionClassCache.tag.byId(actionClassId)],
}
)()
);
export const getActionCountInLast7Days = reactCache(
async (actionClassId: string): Promise<number> =>
cache(
async () => {
validateInputs([actionClassId, ZId]);
try {
const numEventsLast7Days = await prisma.action.count({
where: {
actionClassId: actionClassId,
createdAt: {
gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
},
},
});
return numEventsLast7Days;
} catch (error) {
throw error;
}
},
[`getActionCountInLast7Days-${actionClassId}`],
{
tags: [actionClassCache.tag.byId(actionClassId)],
}
)()
);
export const getActionCountInLastQuarter = reactCache(
async (actionClassId: string, personId: string): Promise<number> =>
cache(
async () => {
validateInputs([actionClassId, ZId], [personId, ZId]);
try {
const numEventsLastQuarter = await prisma.action.count({
where: {
personId,
actionClass: {
id: actionClassId,
},
createdAt: {
gte: getStartDateOfLastQuarter(),
},
},
});
return numEventsLastQuarter;
} catch (error) {
throw error;
}
},
[`getActionCountInLastQuarter-${actionClassId}-${personId}`],
{
tags: [actionClassCache.tag.byId(actionClassId)],
}
)()
);
export const getActionCountInLastMonth = reactCache(
async (actionClassId: string, personId: string): Promise<number> =>
cache(
async () => {
validateInputs([actionClassId, ZId], [personId, ZId]);
try {
const numEventsLastMonth = await prisma.action.count({
where: {
personId,
actionClass: {
id: actionClassId,
},
createdAt: {
gte: getStartDateOfLastMonth(),
},
},
});
return numEventsLastMonth;
} catch (error) {
throw error;
}
},
[`getActionCountInLastMonth-${actionClassId}-${personId}`],
{
tags: [actionClassCache.tag.byId(actionClassId)],
}
)()
);
export const getActionCountInLastWeek = reactCache(
async (actionClassId: string, personId: string): Promise<number> =>
cache(
async () => {
validateInputs([actionClassId, ZId], [personId, ZId]);
try {
const numEventsLastWeek = await prisma.action.count({
where: {
personId,
actionClass: {
id: actionClassId,
},
createdAt: {
gte: getStartDateOfLastWeek(),
},
},
});
return numEventsLastWeek;
} catch (error) {
throw error;
}
},
[`getActionCountInLastWeek-${actionClassId}-${personId}`],
{
tags: [actionClassCache.tag.byId(actionClassId)],
}
)()
);
export const getTotalOccurrencesForAction = reactCache(
async (actionClassId: string, personId: string): Promise<number> =>
cache(
async () => {
validateInputs([actionClassId, ZId], [personId, ZId]);
try {
const count = await prisma.action.count({
where: {
personId,
actionClass: {
id: actionClassId,
},
},
});
return count;
} catch (error) {
throw error;
}
},
[`getTotalOccurrencesForAction-${actionClassId}-${personId}`],
{
tags: [actionClassCache.tag.byId(actionClassId)],
}
)()
);
export const getLastOccurrenceDaysAgo = reactCache(
async (actionClassId: string, personId: string): Promise<number | null> =>
cache(
async () => {
validateInputs([actionClassId, ZId], [personId, ZId]);
try {
const lastEvent = await prisma.action.findFirst({
where: {
personId,
actionClass: {
id: actionClassId,
},
},
orderBy: {
createdAt: "desc",
},
select: {
createdAt: true,
},
});
if (!lastEvent) return null;
return differenceInDays(new Date(), lastEvent.createdAt);
} catch (error) {
throw error;
}
},
[`getLastOccurrenceDaysAgo-${actionClassId}-${personId}`],
{
tags: [actionClassCache.tag.byId(actionClassId)],
}
)()
);
export const getFirstOccurrenceDaysAgo = reactCache(
async (actionClassId: string, personId: string): Promise<number | null> =>
cache(
async () => {
validateInputs([actionClassId, ZId], [personId, ZId]);
try {
const firstEvent = await prisma.action.findFirst({
where: {
personId,
actionClass: {
id: actionClassId,
},
},
orderBy: {
createdAt: "asc",
},
select: {
createdAt: true,
},
});
if (!firstEvent) return null;
return differenceInDays(new Date(), firstEvent.createdAt);
} catch (error) {
throw error;
}
},
[`getFirstOccurrenceDaysAgo-${actionClassId}-${personId}`],
{
tags: [actionClassCache.tag.byId(actionClassId)],
}
)()
);

View File

@@ -0,0 +1,13 @@
import { startOfMonth, startOfQuarter, startOfWeek, subMonths, subQuarters, subWeeks } from "date-fns";
export const getStartDateOfLastQuarter = () => {
return startOfQuarter(subQuarters(new Date(), 1));
};
export const getStartDateOfLastMonth = () => {
return startOfMonth(subMonths(new Date(), 1));
};
export const getStartDateOfLastWeek = () => {
return startOfWeek(subWeeks(new Date(), 1));
};

View File

@@ -9,7 +9,7 @@ import { TPerson, TPersonWithAttributes } from "@formbricks/types/people";
import { cache } from "../cache";
import { ITEMS_PER_PAGE } from "../constants";
import { validateInputs } from "../utils/validate";
import { personCache } from "./cache";
import { activePersonCache, personCache } from "./cache";
export const selectPerson = {
id: true,
@@ -284,3 +284,39 @@ export const getPersonByUserId = reactCache(
}
)()
);
export const getIsPersonMonthlyActive = reactCache(
(personId: string): Promise<boolean> =>
cache(
async () => {
try {
const latestAction = await prisma.action.findFirst({
where: {
personId,
},
orderBy: {
createdAt: "desc",
},
select: {
createdAt: true,
},
});
if (!latestAction || new Date(latestAction.createdAt).getMonth() !== new Date().getMonth()) {
return false;
}
return true;
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
throw new DatabaseError(error.message);
}
throw error;
}
},
[`getIsPersonMonthlyActive-${personId}`],
{
tags: [activePersonCache.tag.byId(personId)],
revalidate: 60 * 60 * 24, // 24 hours
}
)()
);

View File

@@ -10,11 +10,13 @@ import {
ValidationError,
} from "@formbricks/types/errors";
import {
TActionMetric,
TAllOperators,
TBaseFilters,
TEvaluateSegmentUserAttributeData,
TEvaluateSegmentUserData,
TSegment,
TSegmentActionFilter,
TSegmentAttributeFilter,
TSegmentConnector,
TSegmentCreateInput,
@@ -26,6 +28,14 @@ import {
ZSegmentFilters,
ZSegmentUpdateInput,
} from "@formbricks/types/segment";
import {
getActionCountInLastMonth,
getActionCountInLastQuarter,
getActionCountInLastWeek,
getFirstOccurrenceDaysAgo,
getLastOccurrenceDaysAgo,
getTotalOccurrencesForAction,
} from "../action/service";
import { cache } from "../cache";
import { structuredClone } from "../pollyfills/structuredClone";
import { surveyCache } from "../survey/cache";
@@ -456,6 +466,68 @@ const evaluatePersonFilter = (userId: string, filter: TSegmentPersonFilter): boo
return false;
};
const getResolvedActionValue = async (actionClassId: string, personId: string, metric: TActionMetric) => {
if (metric === "lastQuarterCount") {
const lastQuarterCount = await getActionCountInLastQuarter(actionClassId, personId);
return lastQuarterCount;
}
if (metric === "lastMonthCount") {
const lastMonthCount = await getActionCountInLastMonth(actionClassId, personId);
return lastMonthCount;
}
if (metric === "lastWeekCount") {
const lastWeekCount = await getActionCountInLastWeek(actionClassId, personId);
return lastWeekCount;
}
if (metric === "lastOccurranceDaysAgo") {
const lastOccurranceDaysAgo = await getLastOccurrenceDaysAgo(actionClassId, personId);
return lastOccurranceDaysAgo;
}
if (metric === "firstOccurranceDaysAgo") {
const firstOccurranceDaysAgo = await getFirstOccurrenceDaysAgo(actionClassId, personId);
return firstOccurranceDaysAgo;
}
if (metric === "occuranceCount") {
const occuranceCount = await getTotalOccurrencesForAction(actionClassId, personId);
return occuranceCount;
}
};
const evaluateActionFilter = async (
actionClassIds: string[],
filter: TSegmentActionFilter,
personId: string
): Promise<boolean> => {
const { value, qualifier, root } = filter;
const { actionClassId } = root;
const { metric } = qualifier;
// there could be a case when the actionIds do not have the actionClassId
// in such a case, we return false
const actionClassIdIndex = actionClassIds.findIndex((actionId) => actionId === actionClassId);
if (actionClassIdIndex === -1) {
return false;
}
try {
// we have the action metric and we'll need to find out the values for those metrics from the db
const actionValue = await getResolvedActionValue(actionClassId, personId, metric);
const actionResult =
actionValue !== undefined && compareValues(actionValue ?? 0, value, qualifier.operator);
return actionResult;
} catch (error) {
throw error;
}
};
const evaluateSegmentFilter = async (
userData: TEvaluateSegmentUserData,
filter: TSegmentSegmentFilter
@@ -570,6 +642,19 @@ export const evaluateSegment = async (
});
}
if (type === "action") {
result = await evaluateActionFilter(
userData.actionIds,
resource as TSegmentActionFilter,
userData.personId
);
resultPairs.push({
result,
connector: filterItem.connector,
});
}
if (type === "segment") {
result = await evaluateSegmentFilter(userData, resource as TSegmentSegmentFilter);
resultPairs.push({
@@ -631,3 +716,34 @@ export const evaluateSegment = async (
throw error;
}
};
// This function is used to check if the environment has a segment that uses actions
export const getHasEnvironmentActionSegment = reactCache(
(environmentId: string): Promise<boolean> =>
cache(
async () => {
validateInputs([environmentId, ZId]);
const segments = await getSegments(environmentId);
if (!segments || !segments.length) {
return false;
}
let hasEnvironmentActionSegment = false;
for (let segment of segments) {
const hasActionFilter = JSON.stringify(segment.filters).includes(`"type":"action"`);
if (hasActionFilter) {
hasEnvironmentActionSegment = true;
break;
}
}
return hasEnvironmentActionSegment;
},
[`getHasActionSegment-${environmentId}`],
{
tags: [segmentCache.tag.byEnvironmentId(environmentId)],
}
)()
);

View File

@@ -1,5 +1,7 @@
import {
TActionMetric,
TBaseFilters,
TBaseOperator,
TEvaluateSegmentUserAttributeData,
TEvaluateSegmentUserData,
TSegment,
@@ -27,7 +29,6 @@ export const mockFilter3Resource1Id = "evvoaniy0hn7srea7x0yn4vv";
// filter data:
export const mockActionClassId = "zg7lojfwnk9ipajgeumfz96t";
export const mockEmailValue = "example@example.com";
export const mockEmailFailedValue = "";
export const mockUserId = "random user id";
export const mockDeviceTypeValue = "phone";
@@ -37,24 +38,11 @@ export const mockEvaluateSegmentUserAttributes: TEvaluateSegmentUserAttributeDat
email: mockEmailValue,
userId: mockUserId,
};
export const mockEvaluateFailedSegmentUserAttributes: TEvaluateSegmentUserAttributeData = {
email: mockEmailFailedValue,
userId: mockUserId,
};
export const mockEvaluateSegmentUserData: TEvaluateSegmentUserData = {
personId: mockPersonId,
environmentId: mockEnvironmentId,
attributes: mockEvaluateSegmentUserAttributes,
deviceType: "phone",
userId: mockUserId,
};
export const mockEvaluateFailedSegmentUserData: TEvaluateSegmentUserData = {
personId: mockPersonId,
environmentId: mockEnvironmentId,
attributes: mockEvaluateFailedSegmentUserAttributes,
actionIds: [mockActionClassId],
deviceType: "phone",
userId: mockUserId,
};
@@ -63,7 +51,11 @@ export const mockSegmentTitle = "Engaged Users with Specific Interests";
export const mockSegmentDescription =
"Segment targeting engaged users interested in specific topics and using mobile";
export const getMockSegmentFilters = (): TBaseFilters => [
export const getMockSegmentFilters = (
actionMetric: TActionMetric,
actionValue: string | number,
actionOperator: TBaseOperator
): TBaseFilters => [
{
id: mockFilterGroupId,
connector: null,
@@ -115,6 +107,22 @@ export const getMockSegmentFilters = (): TBaseFilters => [
},
},
},
{
id: mockFilter3Id,
connector: "and",
resource: {
id: mockFilter3Resource1Id,
root: {
type: "action",
actionClassId: mockActionClassId,
},
value: actionValue,
qualifier: {
metric: actionMetric,
operator: actionOperator,
},
},
},
];
export const mockSegment: TSegment = {
@@ -122,7 +130,7 @@ export const mockSegment: TSegment = {
title: mockSegmentTitle,
description: mockSegmentDescription,
isPrivate: false,
filters: getMockSegmentFilters(),
filters: getMockSegmentFilters("lastMonthCount", 5, "equals"),
environmentId: mockEnvironmentId,
createdAt: new Date(),
updatedAt: new Date(),
@@ -133,7 +141,7 @@ export const mockSegmentCreateInput: TSegmentCreateInput = {
title: mockSegmentTitle,
description: mockSegmentDescription,
isPrivate: false,
filters: getMockSegmentFilters(),
filters: getMockSegmentFilters("lastMonthCount", 5, "equals"),
environmentId: mockEnvironmentId,
surveyId: mockSurveyId,
};
@@ -142,7 +150,7 @@ export const mockSegmentUpdateInput: TSegmentUpdateInput = {
title: mockSegmentTitle,
description: mockSegmentDescription,
isPrivate: false,
filters: getMockSegmentFilters(),
filters: getMockSegmentFilters("lastMonthCount", 5, "greaterEqual"),
};
export const mockSegmentPrisma = {
@@ -150,7 +158,7 @@ export const mockSegmentPrisma = {
title: mockSegmentTitle,
description: mockSegmentDescription,
isPrivate: false,
filters: getMockSegmentFilters(),
filters: getMockSegmentFilters("lastMonthCount", 5, "equals"),
environmentId: mockEnvironmentId,
createdAt: new Date(),
updatedAt: new Date(),

View File

@@ -5,7 +5,6 @@ import {
mockDeleteSegmentId,
mockDeleteSegmentPrisma,
mockEnvironmentId,
mockEvaluateFailedSegmentUserData,
mockEvaluateSegmentUserData,
mockSegment,
mockSegmentCreateInput,
@@ -28,27 +27,85 @@ import {
updateSegment,
} from "../service";
const addOrSubractDays = (date: Date, number: number) => {
return new Date(new Date().setDate(date.getDate() - number));
};
beforeEach(() => {
prisma.segment.findUnique.mockResolvedValue(mockSegmentPrisma);
prisma.segment.findMany.mockResolvedValue([mockSegmentPrisma]);
prisma.segment.update.mockResolvedValue({
...mockSegmentPrisma,
filters: getMockSegmentFilters(),
filters: getMockSegmentFilters("lastMonthCount", 5, "greaterEqual"),
});
});
describe("Tests for evaluateSegment service", () => {
describe("Happy Path", () => {
it("Returns true when the user meets the segment criteria", async () => {
// prisma.action.count.mockResolvedValue(4);
const result = await evaluateSegment(mockEvaluateSegmentUserData, getMockSegmentFilters());
prisma.action.count.mockResolvedValue(4);
const result = await evaluateSegment(
mockEvaluateSegmentUserData,
getMockSegmentFilters("lastQuarterCount", 5, "lessThan")
);
expect(result).toBe(true);
});
it("Calculates the action count for the last month", async () => {
prisma.action.count.mockResolvedValue(0);
const result = await evaluateSegment(
mockEvaluateSegmentUserData,
getMockSegmentFilters("lastMonthCount", 5, "lessThan")
);
expect(result).toBe(true);
});
it("Calculates the action count for the last week", async () => {
prisma.action.count.mockResolvedValue(6);
const result = await evaluateSegment(
mockEvaluateSegmentUserData,
getMockSegmentFilters("lastWeekCount", 5, "greaterEqual")
);
expect(result).toBe(true);
});
it("Calculates the total occurences of action", async () => {
prisma.action.count.mockResolvedValue(6);
const result = await evaluateSegment(
mockEvaluateSegmentUserData,
getMockSegmentFilters("occuranceCount", 5, "greaterEqual")
);
expect(result).toBe(true);
});
it("Calculates the last occurence days ago of action", async () => {
prisma.action.findFirst.mockResolvedValue({ createdAt: addOrSubractDays(new Date(), 5) } as any);
const result = await evaluateSegment(
mockEvaluateSegmentUserData,
getMockSegmentFilters("lastOccurranceDaysAgo", 0, "greaterEqual")
);
expect(result).toBe(true);
});
it("Calculates the first occurence days ago of action", async () => {
prisma.action.findFirst.mockResolvedValue({ createdAt: addOrSubractDays(new Date(), 5) } as any);
const result = await evaluateSegment(
mockEvaluateSegmentUserData,
getMockSegmentFilters("firstOccurranceDaysAgo", 6, "lessThan")
);
expect(result).toBe(true);
});
});
describe("Sad Path", () => {
it("Returns false when the user does not meet the segment criteria", async () => {
const result = await evaluateSegment(mockEvaluateFailedSegmentUserData, getMockSegmentFilters());
prisma.action.count.mockResolvedValue(0);
const result = await evaluateSegment(
mockEvaluateSegmentUserData,
getMockSegmentFilters("lastQuarterCount", 5, "greaterThan")
);
expect(result).toBe(false);
});
});
@@ -162,7 +219,7 @@ describe("Tests for updateSegment service", () => {
const result = await updateSegment(mockSegmentId, mockSegmentUpdateInput);
expect(result).toEqual({
...mockSegment,
filters: getMockSegmentFilters(),
filters: getMockSegmentFilters("lastMonthCount", 5, "greaterEqual"),
});
});
});

View File

@@ -1,11 +1,13 @@
import { createId } from "@paralleldrive/cuid2";
import {
TActionMetric,
TAllOperators,
TAttributeOperator,
TBaseFilter,
TBaseFilters,
TDeviceOperator,
TSegment,
TSegmentActionFilter,
TSegmentAttributeFilter,
TSegmentConnector,
TSegmentDeviceFilter,
@@ -90,6 +92,25 @@ export const convertOperatorToTitle = (operator: TAllOperators) => {
}
};
export const convertMetricToText = (metric: TActionMetric) => {
switch (metric) {
case "lastQuarterCount":
return "Last quarter (Count)";
case "lastMonthCount":
return "Last month (Count)";
case "lastWeekCount":
return "Last week (Count)";
case "occuranceCount":
return "Occurance (Count)";
case "lastOccurranceDaysAgo":
return "Last occurrance (Days ago)";
case "firstOccurranceDaysAgo":
return "First occurrance (Days ago)";
default:
return metric;
}
};
export const addFilterBelow = (group: TBaseFilters, resourceId: string, filter: TBaseFilter) => {
for (let i = 0; i < group.length; i++) {
const { resource } = group[i];
@@ -389,6 +410,40 @@ export const updatePersonIdentifierInFilter = (
}
};
export const updateActionClassIdInFilter = (
group: TBaseFilters,
filterId: string,
newActionClassId: string
) => {
for (let i = 0; i < group.length; i++) {
const { resource } = group[i];
if (isResourceFilter(resource)) {
if (resource.id === filterId) {
(resource as TSegmentActionFilter).root.actionClassId = newActionClassId;
break;
}
} else {
updateActionClassIdInFilter(resource, filterId, newActionClassId);
}
}
};
export const updateMetricInFilter = (group: TBaseFilters, filterId: string, newMetric: TActionMetric) => {
for (let i = 0; i < group.length; i++) {
const { resource } = group[i];
if (isResourceFilter(resource)) {
if (resource.id === filterId) {
(resource as TSegmentActionFilter).qualifier.metric = newMetric;
break;
}
} else {
updateMetricInFilter(resource, filterId, newMetric);
}
}
};
export const updateSegmentIdInFilter = (group: TBaseFilters, filterId: string, newSegmentId: string) => {
for (let i = 0; i < group.length; i++) {
const { resource } = group[i];

View File

@@ -18,6 +18,7 @@ import {
ZSurvey,
ZSurveyCreateInput,
} from "@formbricks/types/surveys/types";
import { getActionsByPersonId } from "../action/service";
import { actionClassCache } from "../actionClass/cache";
import { getActionClasses } from "../actionClass/service";
import { attributeCache } from "../attribute/cache";
@@ -1188,6 +1189,11 @@ export const getSyncSurveys = reactCache(
return surveys;
}
const personActions = await getActionsByPersonId(person.id);
const personActionClassIds = Array.from(
new Set(personActions?.map((action) => action.actionClass?.id ?? ""))
);
const attributes = await getAttributes(person.id);
const personUserId = person.userId;
@@ -1203,6 +1209,7 @@ export const getSyncSurveys = reactCache(
const result = await evaluateSegment(
{
attributes: attributes ?? {},
actionIds: personActionClassIds,
deviceType,
environmentId,
personId: person.id,

View File

@@ -2691,18 +2691,7 @@ const NPS = (): TTemplate => {
};
const customerSatisfactionScore = (): TTemplate => {
const reusableQuestionIds = [
createId(),
createId(),
createId(),
createId(),
createId(),
createId(),
createId(),
createId(),
createId(),
createId(),
];
const reusableQuestionIds = [createId(), createId(), createId()];
return {
name: "Customer Satisfaction Score (CSAT)",
role: "customerSuccess",
@@ -2716,12 +2705,39 @@ const customerSatisfactionScore = (): TTemplate => {
{
id: reusableQuestionIds[0],
type: TSurveyQuestionTypeEnum.Rating,
range: 10,
scale: "number",
headline: {
default:
"How likely is it that you would recommend this {{productName}} to a friend or colleague?",
},
logic: [
{
id: createId(),
conditions: {
id: createId(),
connector: "and",
conditions: [
{
id: createId(),
leftOperand: {
value: reusableQuestionIds[0],
type: "question",
},
operator: "isLessThanOrEqual",
rightOperand: {
type: "static",
value: 3,
},
},
],
},
actions: [
{
id: createId(),
objective: "jumpToQuestion",
target: reusableQuestionIds[2],
},
],
},
],
range: 5,
scale: "smiley",
headline: { default: "How satisfied are you with your {{productName}} experience?" },
required: true,
lowerLabel: { default: "Not satisfied" },
upperLabel: { default: "Very satisfied" },
@@ -2729,129 +2745,42 @@ const customerSatisfactionScore = (): TTemplate => {
},
{
id: reusableQuestionIds[1],
type: TSurveyQuestionTypeEnum.MultipleChoiceSingle,
headline: { default: "Overall, how satisfied or dissatisfied are you with our {{productName}}" },
subheader: { default: "Please select one:" },
required: true,
choices: [
{ id: createId(), label: { default: "Very satisfied" } },
{ id: createId(), label: { default: "Somewhat satisfied" } },
{ id: createId(), label: { default: "Neither satisfied nor dissatisfied" } },
{ id: createId(), label: { default: "Somewhat dissatisfied" } },
{ id: createId(), label: { default: "Very dissatisfied" } },
type: TSurveyQuestionTypeEnum.OpenText,
logic: [
{
id: createId(),
conditions: {
id: createId(),
connector: "and",
conditions: [
{
id: createId(),
leftOperand: {
value: reusableQuestionIds[1],
type: "question",
},
operator: "isSubmitted",
},
],
},
actions: [
{
id: createId(),
objective: "jumpToQuestion",
target: surveyDefault.endings[0].id,
},
],
},
],
headline: { default: "Lovely! Is there anything we can do to improve your experience?" },
required: false,
placeholder: { default: "Type your answer here..." },
inputType: "text",
},
{
id: reusableQuestionIds[2],
type: TSurveyQuestionTypeEnum.MultipleChoiceMulti,
headline: {
default: "Which of the following words would you use to describe our {{productName}}?",
},
subheader: { default: "Select all that apply:" },
required: true,
choices: [
{ id: createId(), label: { default: "Reliable" } },
{ id: createId(), label: { default: "High quality" } },
{ id: createId(), label: { default: "Overpriced" } },
{ id: createId(), label: { default: "Impractical" } },
{ id: createId(), label: { default: "Useful" } },
{ id: createId(), label: { default: "Ineffective" } },
{ id: createId(), label: { default: "Unique" } },
{ id: createId(), label: { default: "Poor quality" } },
{ id: createId(), label: { default: "Good value for money" } },
{ id: createId(), label: { default: "Unreliable" } },
],
},
{
id: reusableQuestionIds[3],
type: TSurveyQuestionTypeEnum.MultipleChoiceSingle,
headline: { default: "How well do our {{productName}} meet your needs?" },
subheader: { default: "Select one option:" },
required: true,
choices: [
{ id: createId(), label: { default: "Extremely well" } },
{ id: createId(), label: { default: "Very well" } },
{ id: createId(), label: { default: "Somewhat well" } },
{ id: createId(), label: { default: "Not so well" } },
{ id: createId(), label: { default: "Not at all well" } },
],
},
{
id: reusableQuestionIds[4],
type: TSurveyQuestionTypeEnum.MultipleChoiceSingle,
headline: { default: "How would you rate the quality of the {{productName}}?" },
subheader: { default: "Select one option:" },
required: true,
choices: [
{ id: createId(), label: { default: "Very high quality" } },
{ id: createId(), label: { default: "High quality" } },
{ id: createId(), label: { default: "Low quality" } },
{ id: createId(), label: { default: "Very low quality" } },
{ id: createId(), label: { default: "Neither high nor low" } },
],
},
{
id: reusableQuestionIds[5],
type: TSurveyQuestionTypeEnum.MultipleChoiceSingle,
headline: { default: "How would you rate the value for money of the {{productName}}?" },
subheader: { default: "Please select one:" },
required: true,
choices: [
{ id: createId(), label: { default: "Excellent" } },
{ id: createId(), label: { default: "Above average" } },
{ id: createId(), label: { default: "Average" } },
{ id: createId(), label: { default: "Below average" } },
{ id: createId(), label: { default: "Poor" } },
],
},
{
id: reusableQuestionIds[6],
type: TSurveyQuestionTypeEnum.MultipleChoiceSingle,
headline: { default: "How responsive have we been to your questions about our services?" },
subheader: { default: "Select one option:" },
required: true,
choices: [
{ id: createId(), label: { default: "Extremely responsive" } },
{ id: createId(), label: { default: "Very responsive" } },
{ id: createId(), label: { default: "Somewhat responsive" } },
{ id: createId(), label: { default: "Not so responsive" } },
{ id: createId(), label: { default: "Not at all responsive" } },
{ id: createId(), label: { default: "Not applicable" } },
],
},
{
id: reusableQuestionIds[7],
type: TSurveyQuestionTypeEnum.MultipleChoiceSingle,
headline: { default: "How long have you been a customer of {{productName}}?" },
subheader: { default: "Select one option:" },
required: true,
choices: [
{ id: createId(), label: { default: "This is my first purchase" } },
{ id: createId(), label: { default: "Less than six months" } },
{ id: createId(), label: { default: "Six months to a year" } },
{ id: createId(), label: { default: "1 - 2 years" } },
{ id: createId(), label: { default: "3 or more years" } },
{ id: createId(), label: { default: "I haven't made a purchase yet" } },
],
},
{
id: reusableQuestionIds[8],
type: TSurveyQuestionTypeEnum.MultipleChoiceSingle,
headline: { default: "How likely are you to purchase any of our {{productName}} again ?" },
subheader: { default: "Select one option:" },
required: true,
choices: [
{ id: createId(), label: { default: "Extremely likely" } },
{ id: createId(), label: { default: "Very likely" } },
{ id: createId(), label: { default: "Somewhat likely" } },
{ id: createId(), label: { default: "Not so likely" } },
{ id: createId(), label: { default: "Not at all likely" } },
],
},
{
id: reusableQuestionIds[9],
type: TSurveyQuestionTypeEnum.OpenText,
headline: { default: "Do you have any other comments, questions or concerns?" },
headline: { default: "Ugh, sorry! Is there anything we can do to improve your experience?" },
required: false,
placeholder: { default: "Type your answer here..." },
inputType: "text",
@@ -5256,9 +5185,9 @@ export const getExampleAppSurveyTemplate = (
({
...question,
type: TSurveyQuestionTypeEnum.CTA,
headline: { default: "App successfully connected" },
headline: { default: "App successfully connected 🥳" },
html: {
default: "You're all set up. Create your own survey for your app users.",
default: "You're all set up. Create your own survey for your app users 👇",
},
buttonLabel: { default: "Let's do it!" },
buttonExternal: true,

9
packages/surveys/LICENSE Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2023 Formbricks GmbH
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -6,7 +6,7 @@ export const LoadingSpinner = ({ className }: { className?: string }) => {
data-testid="loading-spinner"
className={cn("fb-flex fb-h-full fb-w-full fb-items-center fb-justify-center", className ?? "")}>
<svg
className="fb-m-2 fb-h-6 fb-w-6 fb-animate-spin fb-text-brand"
className="fb-m-2 fb-h-6 fb-w-6 fb-animate-spin fb-text-slate-700"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24">

View File

@@ -54,11 +54,6 @@ export const Survey = ({
}: SurveyBaseProps) => {
const [localSurvey, setlocalSurvey] = useState<TSurvey>(survey);
// Update localSurvey when the survey prop changes (it changes in case of survey editor)
useEffect(() => {
setlocalSurvey(survey);
}, [survey]);
const autoFocusEnabled = autoFocus !== undefined ? autoFocus : window.self === window.top;
const [questionId, setQuestionId] = useState(() => {

View File

@@ -5,7 +5,6 @@ import { QuestionMedia } from "@/components/general/QuestionMedia";
import { Subheader } from "@/components/general/Subheader";
import { ScrollableContainer } from "@/components/wrappers/ScrollableContainer";
import { getUpdatedTtc, useTtc } from "@/lib/ttc";
import { getShuffledRowIndices } from "@/lib/utils";
import { JSX } from "preact";
import { useCallback, useMemo, useState } from "preact/hooks";
import { getLocalizedValue } from "@formbricks/lib/i18n/utils";
@@ -43,27 +42,6 @@ export const MatrixQuestion = ({
const isMediaAvailable = question.imageUrl || question.videoUrl;
useTtc(question.id, ttc, setTtc, startTime, setStartTime, question.id === currentQuestionId);
const rowShuffleIdx = useMemo(() => {
if (question.shuffleOption) {
return getShuffledRowIndices(question.rows.length, question.shuffleOption);
} else {
return question.rows.map((_, id) => id);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [question.shuffleOption, question.rows.length]);
const questionRows = useMemo(() => {
if (!question.rows) {
return [];
}
if (question.shuffleOption === "none" || question.shuffleOption === undefined) {
return question.rows;
}
return rowShuffleIdx.map((shuffledIdx) => {
return question.rows[shuffledIdx];
});
}, [question.shuffleOption, question.rows, rowShuffleIdx]);
const handleSelect = useCallback(
(column: string, row: string) => {
let responseValue =
@@ -138,7 +116,7 @@ export const MatrixQuestion = ({
</tr>
</thead>
<tbody>
{questionRows.map((row, rowIndex) => (
{question.rows.map((row, rowIndex) => (
// Table rows
<tr className={`${rowIndex % 2 === 0 ? "bg-input-bg" : ""}`}>
<td

View File

@@ -62,12 +62,11 @@ export const OpenTextQuestion = ({
const openTextRef = useCallback(
(currentElement: HTMLInputElement | HTMLTextAreaElement | null) => {
// will focus on current element when the question ID matches the current question
if (question.id && currentElement && autoFocusEnabled && question.id === currentQuestionId) {
if (question.id && currentElement && autoFocusEnabled) {
currentElement.focus();
}
},
[question.id, autoFocusEnabled, currentQuestionId]
[question.id, autoFocusEnabled]
);
return (

View File

@@ -5,7 +5,7 @@ import { QuestionMedia } from "@/components/general/QuestionMedia";
import { Subheader } from "@/components/general/Subheader";
import { ScrollableContainer } from "@/components/wrappers/ScrollableContainer";
import { getUpdatedTtc, useTtc } from "@/lib/ttc";
import { cn, getShuffledChoicesIds } from "@/lib/utils";
import { cn } from "@/lib/utils";
import { useAutoAnimate } from "@formkit/auto-animate/react";
import { useCallback, useMemo, useState } from "preact/hooks";
import { getLocalizedValue } from "@formbricks/lib/i18n/utils";
@@ -48,18 +48,9 @@ export const RankingQuestion = ({
.filter((item): item is TSurveyQuestionChoice => item !== undefined)
);
const [unsortedItems, setUnsortedItems] = useState<TSurveyQuestionChoice[]>(() => {
if (!question.shuffleOption || question.shuffleOption === "none" || sortedItems.length > 1) {
// Return unshuffled items
return question.choices.filter((c) => !value.includes(c.id));
} else {
// Shuffle options
const shuffledChoiceIds = getShuffledChoicesIds(question.choices, question.shuffleOption);
return shuffledChoiceIds
.map((choiceId) => question.choices.find((choice) => choice.id === choiceId))
.filter((choice) => choice !== undefined);
}
});
const [unsortedItems, setUnsortedItems] = useState<TSurveyQuestionChoice[]>(
question.choices.filter((c) => !value.includes(c.id))
);
const [parent] = useAutoAnimate();

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