diff --git a/apps/docs/app/app-surveys/actions/page.mdx b/apps/docs/app/app-surveys/actions/page.mdx index c3e3dd41fc..64cba73f6c 100644 --- a/apps/docs/app/app-surveys/actions/page.mdx +++ b/apps/docs/app/app-surveys/actions/page.mdx @@ -4,25 +4,20 @@ import I1 from "./images/I1.webp"; import I2 from "./images/I2.webp"; export const metadata = { - title: "Using Actions in Formbricks | Fine-tuning User Moments", + title: "Using Actions in Formbricks", 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 & Targeting +# Actions -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. - - - Ensure that you’ve **initialized Formbricks with a userId** to fully utilize this feature along with other - app survey capabilities. - +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. ## **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 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 user’s recent interactions within the app. 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 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. ## **Why Are Actions Useful?** @@ -30,8 +25,7 @@ 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 user’s 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 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. +- **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. ## **Setting Up No-Code Actions** @@ -127,5 +121,3 @@ return ; - -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. diff --git a/apps/docs/app/app-surveys/advanced-targeting/page.mdx b/apps/docs/app/app-surveys/advanced-targeting/page.mdx index 890adf9b16..70e998b048 100644 --- a/apps/docs/app/app-surveys/advanced-targeting/page.mdx +++ b/apps/docs/app/app-surveys/advanced-targeting/page.mdx @@ -1,39 +1,18 @@ -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 In-app Surveys | Formbricks", + title: "Advanced Targeting for 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, user events, and metadata. 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, metadata, and other segments. This helps you get more relevant feedback and make data-driven decisions.", }; #### App Surveys # Advanced Targeting - - 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. - - 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 -## How to setup Advanced Targeting - - - Advanced Targeting is available on the Pro plan! - +Advanced Targeting is only available on the Pro plan! 1. On the Formbricks dashboard, click on **People** tab from the top navigation bar. @@ -41,7 +20,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 actions, user attributes, other segments, devices, and more. +4. Now click on the **Add Filter** button to add a filter. You can filter based on 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**. @@ -50,32 +29,3 @@ 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. - - - -2. Post-experience surveying for a ride hailing app where users who have taken more than 1 ride are shown a survey. - - - -3. Sneak Peak: How we at Formbricks automate inviting power users to chat with us - - diff --git a/apps/docs/app/best-practices/pmf-survey/page.mdx b/apps/docs/app/best-practices/pmf-survey/page.mdx index 202fac1af5..cd995814d3 100644 --- a/apps/docs/app/best-practices/pmf-survey/page.mdx +++ b/apps/docs/app/best-practices/pmf-survey/page.mdx @@ -37,8 +37,9 @@ 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 - ## Formbricks Widget running? - We assume that you have already installed the Formbricks Widget in your web app. It’s 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. It’s required to display messages and surveys in your app. If not, please follow the [Quick Start Guide + (15mins).](/app-surveys/quickstart) ### 1. Create new PMF survey @@ -69,25 +70,12 @@ _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 (coming soon) - - - ## Filter by attribute coming soon We're working on pre-segmenting users by attributes. We will update this - manual in the next days. - +### 3. Pre-segment your audience To run this survey properly, you should pre-segment your user base. As touched upon earlier: if you ask every user you’ll 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. It’s 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: diff --git a/apps/docs/app/developer-docs/rest-api/page.mdx b/apps/docs/app/developer-docs/rest-api/page.mdx index 7783a07063..4e2bc134cb 100644 --- a/apps/docs/app/developer-docs/rest-api/page.mdx +++ b/apps/docs/app/developer-docs/rest-api/page.mdx @@ -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, 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", + "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", }; #### API @@ -23,7 +23,6 @@ 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 diff --git a/apps/docs/app/website-surveys/actions-and-targeting/images/StepOne.webp b/apps/docs/app/website-surveys/actions/images/StepOne.webp similarity index 100% rename from apps/docs/app/website-surveys/actions-and-targeting/images/StepOne.webp rename to apps/docs/app/website-surveys/actions/images/StepOne.webp diff --git a/apps/docs/app/website-surveys/actions-and-targeting/images/StepTwo.webp b/apps/docs/app/website-surveys/actions/images/StepTwo.webp similarity index 100% rename from apps/docs/app/website-surveys/actions-and-targeting/images/StepTwo.webp rename to apps/docs/app/website-surveys/actions/images/StepTwo.webp diff --git a/apps/docs/app/website-surveys/actions-and-targeting/page.mdx b/apps/docs/app/website-surveys/actions/page.mdx similarity index 90% rename from apps/docs/app/website-surveys/actions-and-targeting/page.mdx rename to apps/docs/app/website-surveys/actions/page.mdx index 476c55ebbb..f543700250 100644 --- a/apps/docs/app/website-surveys/actions-and-targeting/page.mdx +++ b/apps/docs/app/website-surveys/actions/page.mdx @@ -11,11 +11,9 @@ export const metadata = { #### Website Surveys -# Actions & Targeting +# Actions -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. +Actions are triggers based on interactions with your website, allowing you to capture feedback precisely when it's most relevant. These actions operate **independently** as website surveys do not involve user identification. If you have @@ -46,7 +44,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” @@ -55,7 +53,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: diff --git a/apps/docs/lib/navigation.ts b/apps/docs/lib/navigation.ts index 9e691fc41c..f48c99c173 100644 --- a/apps/docs/lib/navigation.ts +++ b/apps/docs/lib/navigation.ts @@ -57,7 +57,7 @@ export const navigation: Array = [ { title: "Features", children: [ - { title: "Actions & Targeting", href: "/website-surveys/actions-and-targeting" }, + { title: "Actions", href: "/website-surveys/actions" }, { 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 diff --git a/apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/SettingsView.tsx b/apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/SettingsView.tsx index 583d4adc2a..f03937bf2d 100644 --- a/apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/SettingsView.tsx +++ b/apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/SettingsView.tsx @@ -73,7 +73,6 @@ export const SettingsView = ({ setLocalSurvey={setLocalSurvey} environmentId={environment.id} attributeClasses={attributeClasses} - actionClasses={actionClasses} segments={segments} initialSegment={segments.find((segment) => segment.id === localSurvey.segment?.id)} /> diff --git a/apps/web/app/(app)/environments/[environmentId]/(people)/segments/components/EditSegmentModal.tsx b/apps/web/app/(app)/environments/[environmentId]/(people)/segments/components/EditSegmentModal.tsx index 2666af862b..03f036a16e 100644 --- a/apps/web/app/(app)/environments/[environmentId]/(people)/segments/components/EditSegmentModal.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/(people)/segments/components/EditSegmentModal.tsx @@ -2,7 +2,6 @@ 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"; @@ -16,7 +15,6 @@ interface EditSegmentModalProps { currentSegment: TSegmentWithSurveyNames; segments: TSegment[]; attributeClasses: TAttributeClass[]; - actionClasses: TActionClass[]; isAdvancedTargetingAllowed: boolean; isFormbricksCloud: boolean; } @@ -26,7 +24,6 @@ export const EditSegmentModal = ({ open, setOpen, currentSegment, - actionClasses, attributeClasses, segments, isAdvancedTargetingAllowed, @@ -36,7 +33,6 @@ export const EditSegmentModal = ({ if (isAdvancedTargetingAllowed) { return ( { @@ -32,7 +29,6 @@ export const SegmentTable = ({ diff --git a/apps/web/app/(app)/environments/[environmentId]/(people)/segments/components/SegmentTableDataRow.tsx b/apps/web/app/(app)/environments/[environmentId]/(people)/segments/components/SegmentTableDataRow.tsx index 3b6eff9828..ecf22e6f92 100644 --- a/apps/web/app/(app)/environments/[environmentId]/(people)/segments/components/SegmentTableDataRow.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/(people)/segments/components/SegmentTableDataRow.tsx @@ -3,7 +3,6 @@ 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"; @@ -12,14 +11,12 @@ type TSegmentTableDataRowProps = { currentSegment: TSegmentWithSurveyNames; segments: TSegment[]; attributeClasses: TAttributeClass[]; - actionClasses: TActionClass[]; isAdvancedTargetingAllowed: boolean; isFormbricksCloud: boolean; }; export const SegmentTableDataRow = ({ currentSegment, - actionClasses, attributeClasses, segments, isAdvancedTargetingAllowed, @@ -65,7 +62,6 @@ export const SegmentTableDataRow = ({ open={isEditSegmentModalOpen} setOpen={setIsEditSegmentModalOpen} currentSegment={currentSegment} - actionClasses={actionClasses} attributeClasses={attributeClasses} segments={segments} isAdvancedTargetingAllowed={isAdvancedTargetingAllowed} diff --git a/apps/web/app/(app)/environments/[environmentId]/(people)/segments/components/SegmentTableDataRowContainer.tsx b/apps/web/app/(app)/environments/[environmentId]/(people)/segments/components/SegmentTableDataRowContainer.tsx index a3a98f42ac..229c64b039 100644 --- a/apps/web/app/(app)/environments/[environmentId]/(people)/segments/components/SegmentTableDataRowContainer.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/(people)/segments/components/SegmentTableDataRowContainer.tsx @@ -1,6 +1,5 @@ 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"; @@ -9,14 +8,12 @@ type TSegmentTableDataRowProps = { currentSegment: TSegment; segments: TSegment[]; attributeClasses: TAttributeClass[]; - actionClasses: TActionClass[]; isAdvancedTargetingAllowed: boolean; }; export const SegmentTableDataRowContainer = async ({ currentSegment, segments, - actionClasses, attributeClasses, isAdvancedTargetingAllowed, }: TSegmentTableDataRowProps) => { @@ -38,7 +35,6 @@ export const SegmentTableDataRowContainer = async ({ inactiveSurveys, }} segments={segments} - actionClasses={actionClasses} attributeClasses={attributeClasses} isAdvancedTargetingAllowed={isAdvancedTargetingAllowed} isFormbricksCloud={IS_FORMBRICKS_CLOUD} diff --git a/apps/web/app/(app)/environments/[environmentId]/(people)/segments/page.tsx b/apps/web/app/(app)/environments/[environmentId]/(people)/segments/page.tsx index 2a1803728a..8da0ff8904 100644 --- a/apps/web/app/(app)/environments/[environmentId]/(people)/segments/page.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/(people)/segments/page.tsx @@ -3,7 +3,6 @@ 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"; @@ -13,11 +12,10 @@ import { PageContentWrapper } from "@formbricks/ui/components/PageContentWrapper import { PageHeader } from "@formbricks/ui/components/PageHeader"; const Page = async ({ params }) => { - const [environment, segments, attributeClasses, actionClasses, organization] = await Promise.all([ + const [environment, segments, attributeClasses, organization] = await Promise.all([ getEnvironment(params.environmentId), getSegments(params.environmentId), getAttributeClasses(params.environmentId), - getActionClasses(params.environmentId), getOrganizationByEnvironmentId(params.environmentId), ]); @@ -41,7 +39,6 @@ const Page = async ({ params }) => { isAdvancedTargetingAllowed ? ( @@ -60,7 +57,6 @@ const Page = async ({ params }) => { diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SuccessMessage.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SuccessMessage.tsx index e5e9fc7b9d..5c1c4f2d99 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SuccessMessage.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SuccessMessage.tsx @@ -29,6 +29,7 @@ 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", diff --git a/apps/web/app/api/v1/client/[environmentId]/app/people/[userId]/lib/personState.ts b/apps/web/app/api/v1/client/[environmentId]/app/people/[userId]/lib/personState.ts index 937e103959..ae3531a6ac 100644 --- a/apps/web/app/api/v1/client/[environmentId]/app/people/[userId]/lib/personState.ts +++ b/apps/web/app/api/v1/client/[environmentId]/app/people/[userId]/lib/personState.ts @@ -9,17 +9,13 @@ 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 { - getMonthlyActiveOrganizationPeopleCount, - getOrganizationByEnvironmentId, -} from "@formbricks/lib/organization/service"; +import { getOrganizationByEnvironmentId } from "@formbricks/lib/organization/service"; import { personCache } from "@formbricks/lib/person/cache"; -import { getIsPersonMonthlyActive, getPersonByUserId } from "@formbricks/lib/person/service"; -import { sendPlanLimitsReachedEventToPosthogWeekly } from "@formbricks/lib/posthogServer"; +import { getPersonByUserId } from "@formbricks/lib/person/service"; import { responseCache } from "@formbricks/lib/response/cache"; import { getResponsesByUserId } from "@formbricks/lib/response/service"; import { segmentCache } from "@formbricks/lib/segment/cache"; -import { OperationNotAllowedError, ResourceNotFoundError } from "@formbricks/types/errors"; +import { ResourceNotFoundError } from "@formbricks/types/errors"; import { TJsPersonState } from "@formbricks/types/js"; /** @@ -30,7 +26,6 @@ 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, @@ -56,60 +51,21 @@ 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 (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, + if (!person) { + person = await prisma.person.create({ + data: { + environment: { + connect: { + id: environmentId, }, }, - }); - } catch (err) { - console.error(`Error sending plan limits reached event to Posthog: ${err}`); - } + userId, + }, + }); - 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; - } + revalidatePerson = true; } const personResponses = await getResponsesByUserId(environmentId, userId); diff --git a/apps/web/app/api/v1/client/[environmentId]/app/people/[userId]/lib/segments.ts b/apps/web/app/api/v1/client/[environmentId]/app/people/[userId]/lib/segments.ts index e07381db0f..35c06d00cc 100644 --- a/apps/web/app/api/v1/client/[environmentId]/app/people/[userId]/lib/segments.ts +++ b/apps/web/app/api/v1/client/[environmentId]/app/people/[userId]/lib/segments.ts @@ -32,7 +32,6 @@ export const getPersonSegmentIds = ( const isIncluded = await evaluateSegment( { attributes, - actionIds: [], deviceType, environmentId, personId: person.id, diff --git a/apps/web/app/api/v1/client/[environmentId]/app/sync/[userId]/route.ts b/apps/web/app/api/v1/client/[environmentId]/app/sync/[userId]/route.ts index c5296c8451..9926b7ce86 100644 --- a/apps/web/app/api/v1/client/[environmentId]/app/sync/[userId]/route.ts +++ b/apps/web/app/api/v1/client/[environmentId]/app/sync/[userId]/route.ts @@ -7,11 +7,10 @@ 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, getIsPersonMonthlyActive, getPersonByUserId } from "@formbricks/lib/person/service"; +import { createPerson, getPersonByUserId } from "@formbricks/lib/person/service"; import { capturePosthogEnvironmentEvent, sendPlanLimitsReachedEventToPosthogWeekly, @@ -84,81 +83,31 @@ export const GET = async ( throw new Error("Organization does not exist"); } - // check if MAU limit is reached - let isMauLimitReached = false; - let isMonthlyResponsesLimitReached = false; - + // check if response limit is reached + let isAppSurveyResponseLimitReached = false; if (IS_FORMBRICKS_CLOUD) { - const currentMau = await getMonthlyActiveOrganizationPeopleCount(organization.id); - const monthlyResponseLimit = organization.billing.limits.monthly.responses; - const monthlyMiuLimit = organization.billing.limits.monthly.miu; - - isMauLimitReached = monthlyMiuLimit !== null && currentMau >= monthlyMiuLimit; - const currentResponseCount = await getMonthlyOrganizationResponseCount(organization.id); - isMonthlyResponsesLimitReached = + const monthlyResponseLimit = organization.billing.limits.monthly.responses; + + isAppSurveyResponseLimitReached = 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 (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}`); - } + if (!person) { + person = await createPerson(environmentId, userId); } const [surveys, actionClasses] = await Promise.all([ @@ -186,7 +135,7 @@ export const GET = async ( // creating state object let state: TJsAppStateSync = { - surveys: !isMonthlyResponsesLimitReached + surveys: !isAppSurveyResponseLimitReached ? transformedSurveys.map((survey) => replaceAttributeRecall(survey, attributes)) : [], actionClasses, diff --git a/apps/web/app/s/[surveyId]/components/LegalFooter.tsx b/apps/web/app/s/[surveyId]/components/LegalFooter.tsx index f45e6929c8..425e3c22c8 100644 --- a/apps/web/app/s/[surveyId]/components/LegalFooter.tsx +++ b/apps/web/app/s/[surveyId]/components/LegalFooter.tsx @@ -16,8 +16,8 @@ export const LegalFooter = ({ if (!IMPRINT_URL && !PRIVACY_URL && !IS_FORMBRICKS_CLOUD) return null; return ( -
-
+
+
{IMPRINT_URL && ( Imprint diff --git a/packages/database/data-migrations/20240904091113_removed_actions_table/data-migration.ts b/packages/database/data-migrations/20240904091113_removed_actions_table/data-migration.ts new file mode 100644 index 0000000000..d042ae32e4 --- /dev/null +++ b/packages/database/data-migrations/20240904091113_removed_actions_table/data-migration.ts @@ -0,0 +1,88 @@ +/* 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 { + 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(); diff --git a/packages/database/migrations/20240904091113_removed_actions_table/migration.sql b/packages/database/migrations/20240904091113_removed_actions_table/migration.sql new file mode 100644 index 0000000000..1c63e1c7d6 --- /dev/null +++ b/packages/database/migrations/20240904091113_removed_actions_table/migration.sql @@ -0,0 +1,14 @@ +/* + 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"; diff --git a/packages/database/package.json b/packages/database/package.json index 74e36a3e35..75e628477c 100644 --- a/packages/database/package.json +++ b/packages/database/package.json @@ -50,7 +50,8 @@ "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: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" }, "dependencies": { "@prisma/client": "^5.18.0", diff --git a/packages/database/schema.prisma b/packages/database/schema.prisma index 8f51e66ca2..cbce32d6ca 100644 --- a/packages/database/schema.prisma +++ b/packages/database/schema.prisma @@ -102,7 +102,6 @@ model Person { responses Response[] attributes Attribute[] displays Display[] - actions Action[] @@unique([environmentId, userId]) @@index([environmentId]) @@ -359,30 +358,12 @@ 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 diff --git a/packages/ee/advanced-targeting/components/add-filter-modal.tsx b/packages/ee/advanced-targeting/components/add-filter-modal.tsx index dc4c7e595a..2162232e89 100644 --- a/packages/ee/advanced-targeting/components/add-filter-modal.tsx +++ b/packages/ee/advanced-targeting/components/add-filter-modal.tsx @@ -1,10 +1,9 @@ "use client"; import { createId } from "@paralleldrive/cuid2"; -import { FingerprintIcon, MonitorSmartphoneIcon, MousePointerClick, TagIcon, Users2Icon } from "lucide-react"; +import { FingerprintIcon, MonitorSmartphoneIcon, 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, @@ -20,12 +19,11 @@ interface TAddFilterModalProps { open: boolean; setOpen: (open: boolean) => void; onAddFilter: (filter: TBaseFilter) => void; - actionClasses: TActionClass[]; attributeClasses: TAttributeClass[]; segments: TSegment[]; } -type TFilterType = "action" | "attribute" | "segment" | "device" | "person"; +type TFilterType = "attribute" | "segment" | "device" | "person"; const handleAddFilter = ({ type, @@ -33,41 +31,15 @@ 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; @@ -232,7 +204,6 @@ export function AddFilterModal({ onAddFilter, open, setOpen, - actionClasses, attributeClasses, segments, }: TAddFilterModalProps) { @@ -258,14 +229,6 @@ 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 []; @@ -305,18 +268,11 @@ export function AddFilterModal({ { attributes: attributeClassesFiltered, personAttributes: personAttributesFiltered, - actions: actionClassesFiltered, segments: segmentsFiltered, devices: deviceTypesFiltered, }, ], - [ - actionClassesFiltered, - attributeClassesFiltered, - deviceTypesFiltered, - personAttributesFiltered, - segmentsFiltered, - ] + [attributeClassesFiltered, deviceTypesFiltered, personAttributesFiltered, segmentsFiltered] ); const getAllTabContent = () => { @@ -414,35 +370,6 @@ export function AddFilterModal({ ); }; - const getActionsTabContent = () => { - return ( - <> - {actionClassesFiltered.length === 0 && ( -
-

There are no actions yet!

-
- )} - {actionClassesFiltered.map((actionClass) => { - return ( -
{ - handleAddFilter({ - type: "action", - onAddFilter, - setOpen, - actionClassId: actionClass.id, - }); - }}> - -

{actionClass.name}

-
- ); - })} - - ); - }; - const getAttributesTabContent = () => { return ( >; environmentId: string; - actionClasses: TActionClass[]; attributeClasses: TAttributeClass[]; segments: TSegment[]; initialSegment?: TSegment; @@ -47,7 +45,6 @@ export function AdvancedTargetingCard({ localSurvey, setLocalSurvey, environmentId, - actionClasses, attributeClasses, segments, initialSegment, @@ -213,7 +210,6 @@ export function AdvancedTargetingCard({ {Boolean(segment?.filters.length) && (
{ handleAddFilterInGroup(filter); @@ -302,7 +297,6 @@ export function AdvancedTargetingCard({ {segmentEditorViewOnly && segment ? (
{ handleAddFilterInGroup(filter); diff --git a/packages/ee/advanced-targeting/components/segment-editor.tsx b/packages/ee/advanced-targeting/components/segment-editor.tsx index ac0bf83f54..435fbc1a36 100644 --- a/packages/ee/advanced-targeting/components/segment-editor.tsx +++ b/packages/ee/advanced-targeting/components/segment-editor.tsx @@ -11,7 +11,6 @@ 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"; @@ -29,7 +28,6 @@ interface TSegmentEditorProps { environmentId: string; segment: TSegment; segments: TSegment[]; - actionClasses: TActionClass[]; attributeClasses: TAttributeClass[]; setSegment: React.Dispatch>; viewOnly?: boolean; @@ -40,7 +38,6 @@ export function SegmentEditor({ environmentId, setSegment, segment, - actionClasses, attributeClasses, segments, viewOnly = false, @@ -122,7 +119,6 @@ export function SegmentEditor({ if (isResourceFilter(resource)) { return ( { if (addFilterModalOpenedFromBelow) { diff --git a/packages/ee/advanced-targeting/components/segment-filter.tsx b/packages/ee/advanced-targeting/components/segment-filter.tsx index da7c0f5e41..f80e9596e6 100644 --- a/packages/ee/advanced-targeting/components/segment-filter.tsx +++ b/packages/ee/advanced-targeting/components/segment-filter.tsx @@ -2,7 +2,6 @@ import { FingerprintIcon, MonitorSmartphoneIcon, MoreVertical, - MousePointerClick, TagIcon, Trash2, Users2Icon, @@ -12,31 +11,24 @@ 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, @@ -47,10 +39,8 @@ import type { TSegmentSegmentFilter, } from "@formbricks/types/segment"; import { - ACTION_METRICS, ARITHMETIC_OPERATORS, ATTRIBUTE_OPERATORS, - BASE_OPERATORS, DEVICE_OPERATORS, PERSON_OPERATORS, } from "@formbricks/types/segment"; @@ -77,7 +67,6 @@ interface TSegmentFilterProps { environmentId: string; segment: TSegment; segments: TSegment[]; - actionClasses: TActionClass[]; attributeClasses: TAttributeClass[]; setSegment: (segment: TSegment) => void; handleAddFilterBelow: (resourceId: string, filter: TBaseFilter) => void; @@ -566,188 +555,6 @@ 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) => { - 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 ( -
- - - - -
- { - if (viewOnly) return; - checkValueAndUpdate(e); - }} - value={resource.value} - /> - - {valueError ? ( -

{valueError}

- ) : null} -
- -
- ); -} - type TSegmentSegmentFilterProps = TSegmentFilterProps & { onAddFilterBelow: () => void; resource: TSegmentSegmentFilter; @@ -972,7 +779,6 @@ export function SegmentFilter({ environmentId, segment, segments, - actionClasses, attributeClasses, setSegment, handleAddFilterBelow, @@ -998,7 +804,6 @@ export function SegmentFilter({ function RenderFilterModal() { return ( { handleAddFilterBelow(resource.id, filter); @@ -1011,36 +816,10 @@ export function SegmentFilter({ } switch (resource.root.type) { - case "action": - return ( - <> - - - - - ); - case "attribute": return ( <> { handleAddFilterInGroup(filter); diff --git a/packages/lib/action/cache.ts b/packages/lib/action/cache.ts deleted file mode 100644 index 64859901c0..0000000000 --- a/packages/lib/action/cache.ts +++ /dev/null @@ -1,25 +0,0 @@ -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)); - } - }, -}; diff --git a/packages/lib/action/service.ts b/packages/lib/action/service.ts deleted file mode 100644 index ef594b3468..0000000000 --- a/packages/lib/action/service.ts +++ /dev/null @@ -1,442 +0,0 @@ -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 => - 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 => - 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 => { - 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 => - 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 => - 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 => - 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 => - 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 => - 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 => - 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 => - 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 => - 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 => - 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)], - } - )() -); diff --git a/packages/lib/action/utils.ts b/packages/lib/action/utils.ts deleted file mode 100644 index f3b7b95ba5..0000000000 --- a/packages/lib/action/utils.ts +++ /dev/null @@ -1,13 +0,0 @@ -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)); -}; diff --git a/packages/lib/person/service.ts b/packages/lib/person/service.ts index fa2648e12b..1650166420 100644 --- a/packages/lib/person/service.ts +++ b/packages/lib/person/service.ts @@ -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 { activePersonCache, personCache } from "./cache"; +import { personCache } from "./cache"; export const selectPerson = { id: true, @@ -284,39 +284,3 @@ export const getPersonByUserId = reactCache( } )() ); - -export const getIsPersonMonthlyActive = reactCache( - (personId: string): Promise => - 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 - } - )() -); diff --git a/packages/lib/segment/service.ts b/packages/lib/segment/service.ts index 0be52fc655..e078be387b 100644 --- a/packages/lib/segment/service.ts +++ b/packages/lib/segment/service.ts @@ -10,13 +10,11 @@ import { ValidationError, } from "@formbricks/types/errors"; import { - TActionMetric, TAllOperators, TBaseFilters, TEvaluateSegmentUserAttributeData, TEvaluateSegmentUserData, TSegment, - TSegmentActionFilter, TSegmentAttributeFilter, TSegmentConnector, TSegmentCreateInput, @@ -28,14 +26,6 @@ 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"; @@ -466,68 +456,6 @@ 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 => { - 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 @@ -642,19 +570,6 @@ 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({ @@ -716,34 +631,3 @@ 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 => - 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)], - } - )() -); diff --git a/packages/lib/segment/tests/__mocks__/segment.mock.ts b/packages/lib/segment/tests/__mocks__/segment.mock.ts index 3c58e7e67c..58208cb7f4 100644 --- a/packages/lib/segment/tests/__mocks__/segment.mock.ts +++ b/packages/lib/segment/tests/__mocks__/segment.mock.ts @@ -1,7 +1,5 @@ import { - TActionMetric, TBaseFilters, - TBaseOperator, TEvaluateSegmentUserAttributeData, TEvaluateSegmentUserData, TSegment, @@ -29,6 +27,7 @@ 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"; @@ -38,11 +37,24 @@ 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, - actionIds: [mockActionClassId], + deviceType: "phone", + userId: mockUserId, +}; + +export const mockEvaluateFailedSegmentUserData: TEvaluateSegmentUserData = { + personId: mockPersonId, + environmentId: mockEnvironmentId, + attributes: mockEvaluateFailedSegmentUserAttributes, deviceType: "phone", userId: mockUserId, }; @@ -51,11 +63,7 @@ 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 = ( - actionMetric: TActionMetric, - actionValue: string | number, - actionOperator: TBaseOperator -): TBaseFilters => [ +export const getMockSegmentFilters = (): TBaseFilters => [ { id: mockFilterGroupId, connector: null, @@ -107,22 +115,6 @@ export const getMockSegmentFilters = ( }, }, }, - { - id: mockFilter3Id, - connector: "and", - resource: { - id: mockFilter3Resource1Id, - root: { - type: "action", - actionClassId: mockActionClassId, - }, - value: actionValue, - qualifier: { - metric: actionMetric, - operator: actionOperator, - }, - }, - }, ]; export const mockSegment: TSegment = { @@ -130,7 +122,7 @@ export const mockSegment: TSegment = { title: mockSegmentTitle, description: mockSegmentDescription, isPrivate: false, - filters: getMockSegmentFilters("lastMonthCount", 5, "equals"), + filters: getMockSegmentFilters(), environmentId: mockEnvironmentId, createdAt: new Date(), updatedAt: new Date(), @@ -141,7 +133,7 @@ export const mockSegmentCreateInput: TSegmentCreateInput = { title: mockSegmentTitle, description: mockSegmentDescription, isPrivate: false, - filters: getMockSegmentFilters("lastMonthCount", 5, "equals"), + filters: getMockSegmentFilters(), environmentId: mockEnvironmentId, surveyId: mockSurveyId, }; @@ -150,7 +142,7 @@ export const mockSegmentUpdateInput: TSegmentUpdateInput = { title: mockSegmentTitle, description: mockSegmentDescription, isPrivate: false, - filters: getMockSegmentFilters("lastMonthCount", 5, "greaterEqual"), + filters: getMockSegmentFilters(), }; export const mockSegmentPrisma = { @@ -158,7 +150,7 @@ export const mockSegmentPrisma = { title: mockSegmentTitle, description: mockSegmentDescription, isPrivate: false, - filters: getMockSegmentFilters("lastMonthCount", 5, "equals"), + filters: getMockSegmentFilters(), environmentId: mockEnvironmentId, createdAt: new Date(), updatedAt: new Date(), diff --git a/packages/lib/segment/tests/segment.test.ts b/packages/lib/segment/tests/segment.test.ts index 68014433fb..e6c952ccf9 100644 --- a/packages/lib/segment/tests/segment.test.ts +++ b/packages/lib/segment/tests/segment.test.ts @@ -5,6 +5,7 @@ import { mockDeleteSegmentId, mockDeleteSegmentPrisma, mockEnvironmentId, + mockEvaluateFailedSegmentUserData, mockEvaluateSegmentUserData, mockSegment, mockSegmentCreateInput, @@ -27,85 +28,27 @@ 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("lastMonthCount", 5, "greaterEqual"), + filters: getMockSegmentFilters(), }); }); 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("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") - ); + // prisma.action.count.mockResolvedValue(4); + const result = await evaluateSegment(mockEvaluateSegmentUserData, getMockSegmentFilters()); expect(result).toBe(true); }); }); describe("Sad Path", () => { it("Returns false when the user does not meet the segment criteria", async () => { - prisma.action.count.mockResolvedValue(0); - const result = await evaluateSegment( - mockEvaluateSegmentUserData, - getMockSegmentFilters("lastQuarterCount", 5, "greaterThan") - ); + const result = await evaluateSegment(mockEvaluateFailedSegmentUserData, getMockSegmentFilters()); expect(result).toBe(false); }); }); @@ -219,7 +162,7 @@ describe("Tests for updateSegment service", () => { const result = await updateSegment(mockSegmentId, mockSegmentUpdateInput); expect(result).toEqual({ ...mockSegment, - filters: getMockSegmentFilters("lastMonthCount", 5, "greaterEqual"), + filters: getMockSegmentFilters(), }); }); }); diff --git a/packages/lib/segment/utils.ts b/packages/lib/segment/utils.ts index 2f3fc5875c..5a118a22d9 100644 --- a/packages/lib/segment/utils.ts +++ b/packages/lib/segment/utils.ts @@ -1,13 +1,11 @@ import { createId } from "@paralleldrive/cuid2"; import { - TActionMetric, TAllOperators, TAttributeOperator, TBaseFilter, TBaseFilters, TDeviceOperator, TSegment, - TSegmentActionFilter, TSegmentAttributeFilter, TSegmentConnector, TSegmentDeviceFilter, @@ -92,25 +90,6 @@ 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]; @@ -410,40 +389,6 @@ 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]; diff --git a/packages/lib/survey/service.ts b/packages/lib/survey/service.ts index ae5d1706e0..096521f645 100644 --- a/packages/lib/survey/service.ts +++ b/packages/lib/survey/service.ts @@ -18,7 +18,6 @@ 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"; @@ -1189,11 +1188,6 @@ 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; @@ -1209,7 +1203,6 @@ export const getSyncSurveys = reactCache( const result = await evaluateSegment( { attributes: attributes ?? {}, - actionIds: personActionClassIds, deviceType, environmentId, personId: person.id, diff --git a/packages/types/actions.ts b/packages/types/actions.ts deleted file mode 100644 index 7418abd1e1..0000000000 --- a/packages/types/actions.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { z } from "zod"; -import { ZActionClass } from "./action-classes"; -import { ZId } from "./common"; - -export const ZAction = z.object({ - id: ZId, - createdAt: z.date(), - personId: ZId, - properties: z.record(z.string()), - actionClass: ZActionClass.nullable(), -}); - -export type TAction = z.infer; - -export const ZActionInput = z.object({ - environmentId: ZId, - userId: ZId, - name: z.string(), -}); - -export type TActionInput = z.infer; diff --git a/packages/types/segment.ts b/packages/types/segment.ts index bfe430d201..e66e1e307d 100644 --- a/packages/types/segment.ts +++ b/packages/types/segment.ts @@ -31,17 +31,6 @@ export const ATTRIBUTE_OPERATORS = [ // but we might want to add more operators in the future, so we keep it separated export const PERSON_OPERATORS = ATTRIBUTE_OPERATORS; -// A metric is always only associated with an action filter -// Metrics are used to evaluate the value of an action filter, from the database -export const ACTION_METRICS = [ - "lastQuarterCount", - "lastMonthCount", - "lastWeekCount", - "occuranceCount", - "lastOccurranceDaysAgo", - "firstOccurranceDaysAgo", -] as const; - // operators for segment filters export const SEGMENT_OPERATORS = ["userIsIn", "userIsNotIn"] as const; @@ -65,18 +54,14 @@ export type TDeviceOperator = z.infer; export type TAllOperators = (typeof ALL_OPERATORS)[number]; -export const ZActionMetric = z.enum(ACTION_METRICS); -export type TActionMetric = z.infer; - export const ZSegmentFilterValue = z.union([z.string(), z.number()]); export type TSegmentFilterValue = z.infer; // the type of the root of a filter -export const ZSegmentFilterRootType = z.enum(["attribute", "action", "segment", "device", "person"]); +export const ZSegmentFilterRootType = z.enum(["attribute", "segment", "device", "person"]); // Root of the filter, this defines the type of the filter and the metadata associated with it // For example, if the root is "attribute", the attributeClassName is required -// if the root is "action", the actionClassId is required. export const ZSegmentFilterRoot = z.discriminatedUnion("type", [ z.object({ type: z.literal(ZSegmentFilterRootType.Enum.attribute), @@ -86,10 +71,6 @@ export const ZSegmentFilterRoot = z.discriminatedUnion("type", [ type: z.literal(ZSegmentFilterRootType.Enum.person), userId: z.string(), }), - z.object({ - type: z.literal(ZSegmentFilterRootType.Enum.action), - actionClassId: z.string(), - }), z.object({ type: z.literal(ZSegmentFilterRootType.Enum.segment), segmentId: z.string(), @@ -101,8 +82,6 @@ export const ZSegmentFilterRoot = z.discriminatedUnion("type", [ ]); // Each filter has a qualifier, which usually contains the operator for evaluating the filter. -// Only in the case of action filters, the metric is also included in the qualifier - // Attribute filter -> root will always have type "attribute" export const ZSegmentAttributeFilter = z.object({ id: z.string().cuid2(), @@ -131,41 +110,6 @@ export const ZSegmentPersonFilter = z.object({ }); export type TSegmentPersonFilter = z.infer; -// Action filter -> root will always have type "action" -// Action filters also have the metric along with the operator in the qualifier of the filter -export const ZSegmentActionFilter = z - .object({ - id: z.string().cuid2(), - root: z.object({ - type: z.literal("action"), - actionClassId: z.string(), - }), - value: ZSegmentFilterValue, - qualifier: z.object({ - metric: z.enum(ACTION_METRICS), - operator: ZBaseOperator, - }), - }) - .refine( - (actionFilter) => { - const { value } = actionFilter; - - // if the value is not type of number, it's invalid - - const isValueNumber = typeof value === "number"; - - if (!isValueNumber) { - return false; - } - - return true; - }, - { - message: "Value must be a number for action filters", - } - ); -export type TSegmentActionFilter = z.infer; - // Segment filter -> root will always have type "segment" export const ZSegmentSegmentFilter = z.object({ id: z.string().cuid2(), @@ -197,28 +141,8 @@ export type TSegmentDeviceFilter = z.infer; // A segment filter is a union of all the different filter types export const ZSegmentFilter = z - .union([ - ZSegmentActionFilter, - ZSegmentAttributeFilter, - ZSegmentPersonFilter, - ZSegmentSegmentFilter, - ZSegmentDeviceFilter, - ]) + .union([ZSegmentAttributeFilter, ZSegmentPersonFilter, ZSegmentSegmentFilter, ZSegmentDeviceFilter]) // we need to refine the filter to make sure that the filter is valid - .refine( - (filter) => { - if (filter.root.type === "action") { - if (!("metric" in filter.qualifier)) { - return false; - } - } - - return true; - }, - { - message: "Metric operator must be specified for action filters", - } - ) .refine( (filter) => { // if the operator is an arithmentic operator, the value must be a number @@ -371,6 +295,5 @@ export interface TEvaluateSegmentUserData { userId: string; environmentId: string; attributes: TEvaluateSegmentUserAttributeData; - actionIds: string[]; deviceType: "phone" | "desktop"; }