diff --git a/.env.docker b/.env.docker index d0c378e4d3..ba19223174 100644 --- a/.env.docker +++ b/.env.docker @@ -7,7 +7,7 @@ # BASICS # ############ -NEXT_PUBLIC_WEBAPP_URL=http://localhost:3000 +WEBAPP_URL=http://localhost:3000 ############## # DATABASE # @@ -63,25 +63,25 @@ NEXTAUTH_URL=http://localhost:3000 ##################### # Email Verification. If you enable Email Verification you have to setup SMTP-Settings, too. -NEXT_PUBLIC_EMAIL_VERIFICATION_DISABLED=1 +EMAIL_VERIFICATION_DISABLED=1 # Password Reset. If you enable Password Reset functionality you have to setup SMTP-Settings, too. -NEXT_PUBLIC_PASSWORD_RESET_DISABLED=1 +PASSWORD_RESET_DISABLED=1 # Signup. Disable the ability for new users to create an account. -# NEXT_PUBLIC_SIGNUP_DISABLED=1 +# SIGNUP_DISABLED=1 # Team Invite. Disable the ability for invited users to create an account. -# NEXT_PUBLIC_INVITE_DISABLED=1 +# INVITE_DISABLED=1 ########## # Other # ########## # Display privacy policy, imprint and terms of service links in the footer of signup & public pages. -NEXT_PUBLIC_PRIVACY_URL= -NEXT_PUBLIC_TERMS_URL= -NEXT_PUBLIC_IMPRINT_URL= +PRIVACY_URL= +TERMS_URL= +IMPRINT_URL= # Disable Sentry warning SENTRY_IGNORE_API_RESOLUTION_ERROR=1 @@ -90,14 +90,18 @@ SENTRY_IGNORE_API_RESOLUTION_ERROR=1 NEXT_PUBLIC_SENTRY_DSN= # Configure Github Login -NEXT_PUBLIC_GITHUB_AUTH_ENABLED=0 +GITHUB_AUTH_ENABLED=0 GITHUB_ID= GITHUB_SECRET= # Configure Google Login -NEXT_PUBLIC_GOOGLE_AUTH_ENABLED=0 +GOOGLE_AUTH_ENABLED=0 GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= # Cron Secret CRON_SECRET= + +# Encryption key +# You can use: `openssl rand -base64 16` to generate one +FORMBRICKS_ENCRYPTION_KEY= \ No newline at end of file diff --git a/.env.example b/.env.example index 7b3c52feec..1a4c51ccf9 100644 --- a/.env.example +++ b/.env.example @@ -8,7 +8,7 @@ # BASICS # ############ -NEXT_PUBLIC_WEBAPP_URL=http://localhost:3000 +WEBAPP_URL=http://localhost:3000 ############## # DATABASE # @@ -20,6 +20,7 @@ DATABASE_URL='postgresql://postgres:postgres@localhost:5432/formbricks?schema=pu # Cold boots will be faster and you'll be able to scale your DB independently of your app. # @see https://www.prisma.io/docs/data-platform/data-proxy/use-data-proxy # PRISMA_GENERATE_DATAPROXY=true +# i dont think we use it so ask Matti and remove it PRISMA_GENERATE_DATAPROXY= ############### @@ -34,9 +35,6 @@ NEXTAUTH_SECRET=RANDOM_STRING # You do not need the NEXTAUTH_URL environment variable in Vercel. NEXTAUTH_URL=http://localhost:3000 -# If you encounter NEXT_AUTH URL problems this should always be localhost:3000 (or whatever port your app is running on) -# NEXTAUTH_URL_INTERNAL=http://localhost:3000 - ################ # MAIL SETUP # ################ @@ -64,33 +62,33 @@ SMTP_PASSWORD=smtpPassword ##################### # Email Verification. If you enable Email Verification you have to setup SMTP-Settings, too. -# NEXT_PUBLIC_EMAIL_VERIFICATION_DISABLED=1 +# EMAIL_VERIFICATION_DISABLED=1 # Password Reset. If you enable Password Reset functionality you have to setup SMTP-Settings, too. -# NEXT_PUBLIC_PASSWORD_RESET_DISABLED=1 +# PASSWORD_RESET_DISABLED=1 # Signup. Disable the ability for new users to create an account. -# NEXT_PUBLIC_SIGNUP_DISABLED=1 +# SIGNUP_DISABLED=1 # Team Invite. Disable the ability for invited users to create an account. -# NEXT_PUBLIC_INVITE_DISABLED=1 +# INVITE_DISABLED=1 ########## # Other # ########## # Display privacy policy, imprint and terms of service links in the footer of signup & public pages. -NEXT_PUBLIC_PRIVACY_URL= -NEXT_PUBLIC_TERMS_URL= -NEXT_PUBLIC_IMPRINT_URL= +PRIVACY_URL= +TERMS_URL= +IMPRINT_URL= # Configure Github Login -NEXT_PUBLIC_GITHUB_AUTH_ENABLED=0 +GITHUB_AUTH_ENABLED=0 GITHUB_ID= GITHUB_SECRET= # Configure Google Login -NEXT_PUBLIC_GOOGLE_AUTH_ENABLED=0 +GOOGLE_AUTH_ENABLED=0 GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= @@ -106,4 +104,8 @@ NEXT_PUBLIC_FORMBRICKS_ONBOARDING_SURVEY_ID= # Cron Secret CRON_SECRET= -*/ \ No newline at end of file +*/ + +# Encryption key +# You can use: `openssl rand -base64 16` to generate one +FORMBRICKS_ENCRYPTION_KEY= \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 338cbcbe7a..c5b00f7561 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -4,42 +4,45 @@ title: "[FEATURE]" labels: enhancement assignees: [] body: -- type: textarea - id: problem-description - attributes: - label: Is your feature request related to a problem? Please describe. - description: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - validations: - required: true -- type: textarea - id: solution-description - attributes: - label: Describe the solution you'd like - description: A clear and concise description of what you want to happen. - validations: - required: true -- type: textarea - id: alternate-solution-description - attributes: - label: Describe alternatives you've considered - description: A clear and concise description of any alternative solutions or features you've considered. - validations: - required: false -- type: textarea - id: additional-context - attributes: - label: Additional context - description: Add any other context or screenshots about the feature request here. - validations: - required: false -- type: markdown - id: formbricks-info - attributes: - value: | - ### How we code at Formbricks 🤓 + - type: textarea + id: problem-description + attributes: + label: Is your feature request related to a problem? Please describe. + description: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + validations: + required: true + - type: textarea + id: solution-description + attributes: + label: Describe the solution you'd like + description: A clear and concise description of what you want to happen. + validations: + required: true + - type: textarea + id: alternate-solution-description + attributes: + label: Describe alternatives you've considered + description: A clear and concise description of any alternative solutions or features you've considered. + validations: + required: false + - type: textarea + id: additional-context + attributes: + label: Additional context + description: Add any other context or screenshots about the feature request here. + validations: + required: false + - type: markdown + id: formbricks-info + attributes: + value: | + ### How we code at Formbricks 🤓 - - Everything is type-safe - - All UI components are in the package `formbricks/ui` - - Run `pnpm dev` to find a demo app to test in-app surveys at `localhost:3002` - - We use **chatGPT** to help refactor code. Use our [Formbricks ✨ megaprompt ✨](https://github.com/formbricks/formbricks/blob/main/megaprompt.md) to create the right - context before you write your prompt. + - Follow Best Practices lined out in our [Contributor Docs](https://formbricks.com/docs/contributing/how-we-code) + - First time: Please read our [introductory blog post](https://formbricks.com/blog/join-the-formtribe) + - All UI components are in the package `formbricks/ui` + - Run `pnpm go` to find a demo app to test in-app surveys at `localhost:3002` + - Everything is type-safe + - We use **chatGPT** to help refactor code. Use our [Formbricks ✨ megaprompt ✨](https://github.com/formbricks/formbricks/blob/main/megaprompt.md) to create the right + context before you write your prompt. + - Anything unclear? [Ask in Discord](https://formbricks.com/discord) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index bcc25bd390..fa0d33dbca 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -31,9 +31,10 @@ Fixes # (issue) -- [ ] Added a screen recording or screenshots to this PR +### Required + - [ ] Filled out the "How to test" section in this PR -- [ ] Read the [contributing guide](https://github.com/formbricks/formbricks/blob/main/CONTRIBUTING.md) +- [ ] Read [How we Code at Formbricks](<[https://github.com/formbricks/formbricks/blob/main/CONTRIBUTING.md](https://formbricks.com/docs/contributing/how-we-code)>) - [ ] Self-reviewed my own code - [ ] Commented on my code in hard-to-understand bits - [ ] Ran `pnpm build` @@ -41,4 +42,8 @@ Fixes # (issue) - [ ] Removed all `console.logs` - [ ] Merged the latest changes from main onto my branch with `git pull origin main` - [ ] My changes don't cause any responsiveness issues + +### Appreciated + +- [ ] If a UI change was made: Added a screen recording or screenshots to this PR - [ ] Updated the Formbricks Docs if changes were necessary diff --git a/.gitpod.yml b/.gitpod.yml index 54f05d33a1..3c5941863b 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -32,7 +32,7 @@ tasks: command: | gp sync-await init && cp .env.example .env && - sed -i -r "s#^(NEXT_PUBLIC_WEBAPP_URL=).*#\1 $(gp url 3000)#" .env && + sed -i -r "s#^(WEBAPP_URL=).*#\1 $(gp url 3000)#" .env && sed -i -r "s#^(NEXTAUTH_URL=).*#\1 $(gp url 3000)#" .env && turbo --filter "@formbricks/web" go diff --git a/apps/formbricks-com/app/docs/contributing/gitpod/page.mdx b/apps/formbricks-com/app/docs/contributing/gitpod/page.mdx new file mode 100644 index 0000000000..1128322297 --- /dev/null +++ b/apps/formbricks-com/app/docs/contributing/gitpod/page.mdx @@ -0,0 +1,15 @@ +import Image from "next/image"; + +export const meta = { + title: "Gitpod Setup", + description: + "With one click, you can setup the Formbricks developer environment in your browser using Gitpod", +}; + +### One Click Setup + +1. Click the button below to open this project in Gitpod. + +2. This will open a fully configured workspace in your browser with all the necessary dependencies already installed. + +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/formbricks/formbricks) diff --git a/apps/formbricks-com/app/docs/contributing/how-we-code/cors-handling-in-api.webp b/apps/formbricks-com/app/docs/contributing/how-we-code/cors-handling-in-api.webp new file mode 100644 index 0000000000..10ced089d6 Binary files /dev/null and b/apps/formbricks-com/app/docs/contributing/how-we-code/cors-handling-in-api.webp differ diff --git a/apps/formbricks-com/app/docs/contributing/how-we-code/page.mdx b/apps/formbricks-com/app/docs/contributing/how-we-code/page.mdx new file mode 100644 index 0000000000..4ea09e78c6 --- /dev/null +++ b/apps/formbricks-com/app/docs/contributing/how-we-code/page.mdx @@ -0,0 +1,128 @@ +import Image from "next/image"; +import CorsHandling from "./cors-handling-in-api.webp"; + +export const meta = { + title: "Formbricks Code Contribution Guide: Best Practices and Standards", + description: + "Effortlessly Navigate Your Contribution Journey with Formbricks' Coding Guidelines and PR Review Process", +}; + +#### Contributing + +# How we Code at Formbricks + +Thank you for choosing to contribute to Formbricks. Before you start, please familiarize yourself with our coding standards and best practices, as these are key criteria for pull request reviews. Your contributions are greatly valued, and if you have any questions about these guidelines, please don't hesitate to ask. + +**Table of content** + +- Use Typescript types throughout the application +- Always prioritise Server components +- Fetch data only in server components +- Use Server-Action for mutations +- Use service abstraction instead of direct database calls +- Handle authentication and CORS in management APIs +- Always Document API changes +- Constants should be in the packages folder +- Types should be in the packages folder +- How we handle Pull Requests +- Read environment variables from `.env.mjs` + +--- + +## Use Typescript types throughout the application + +The entire codebase is written in TypeScript, and it is crucial that every new piece of code is thoroughly and accurately typed. Instead of resorting to using the `any` type for variables, please ensure that you explicitly specify the appropriate type. + +## Always prioritise Server components + +When it comes to prioritizing the development of our components, our main focus is on building them as server components. This ensures that they are optimized for server-side rendering and can handle any necessary interactivity seamlessly. However, in cases where a component requires client-side interactivity, we are able to adapt it into a client component. If you would like to learn more about the advantages and benefits of server components, we highly recommend reading the comprehensive documentation provided by Next.js, which can be accessed [here](https://nextjs.org/docs/app/building-your-application/rendering/server-components). + +## Fetch data only in server components + +In order to ensure that both data fetching and rendering take place on the server, it is expected that actions to fetch data from the server will be performed within server components. This approach is prioritized as discussed in the previous point, which provides further details on the benefits and importance of server components. + +**Note**: Data fetching is done in the `page.tsx` of the route or the corresponding server component that needs this data. + +## Use Server-Action for mutations + +Server actions are used to perform server actions in client components. For example, a button click (client-side) that should change something in the database. Server actions should be placed in an `actions.ts` file within the specific route to maintain code organization and facilitate efficient development. + +## Use service abstraction instead of direct database calls + +We utilize [prisma](https://www.prisma.io/) as our Object-Relational Mapping (ORM) tool to interact with the database. This implies that when you need to fetch or modify data in the database, you will be utilizing prisma. All prisma calls should be written in the services folder `packages/lib/services`, and before creating a new service, please ensure that one does not already exist. + +## Handle authentication and CORS in management APIs + +We have two APIs: Management API and Client API. + +The public endpoints of the Client API are used by the link survey and `formbricks-js` to send responses and displays to formbricks. Client APIs can be found in `apps/web/app/api/v1/client` + +The Management API offers the same functionality as the management frontend and can be used to create surveys, view responses or change account settings. The endpoints require an api key that the user can obtain in the management frontend. Management APIs can be found in `apps/web/app/api/v1/management`. + +Please keep the following in mind: + +- When dealing with Management APIs always make sure to require authentication via API keys and a sufficient authorization check. +- Make sure to handle CORS requests in any new Client API endpoint you create as these are called from the browser in link surveys or `formbricks-js`. Example below: + +Cors handling within an API + +## Always Document API changes + +It is imperative that any and all modifications or updates made to the client API are thoroughly and comprehensively documented. This documentation should provide clear and detailed information about the nature of the changes, their impact on existing functionality, and any new features or improvements introduced. This practice not only ensures transparency and accountability but also aids developers, both internal and external, in understanding and effectively utilizing the API, ultimately fostering a more robust and user-friendly development ecosystem. + +## Constants should be in the packages folder + +You should store constants in `packages/lib/constants` + +## Types should be in the packages folder + +You should store type in `packages/types/v1` + +## Read environment variables from `.env.mjs` + +Environment variables (`process.env`) shouldn’t be accessed directly but be added in the `.env.mjs` and should be accessed from here. This practice helps us ensure that the variables are typesafe. + +## How we handle Pull Requests + +We have a number of requirements for PRs to ensure they are as easy to review as possible and to ensure that they are up to standard with the code. + +### Code change + +When submitting a pull request, it is important to avoid combining multiple changes or issues into a single PR. By keeping each PR focused on a specific change or issue, it becomes easier and faster to review. Additionally, separating changes into individual PRs makes it easier to test each change independently. This allows for more efficient and thorough testing, ensuring that each change is properly validated before merging. + +### Title & Content + +We require pull request titles to follow the [Conventional Commits specification](https://www.conventionalcommits.org/en/v1.0.0/). You should provide a short and concise title. Don’t put something generic (e.g. bug fixes), and instead mention more specifically what your PR achieves, for instance “fix: dropdown not expanding on survey page”. + +For the PR description, you should go into much greater detail about what your PR adds or fixes. Firstly, the description should include a link to any relevant issues or discussions surrounding the feature or bug that your PR addresses. + +### Feature PRs + +Give a functional overview of how your feature works, including how the user can use the feature. Then, share any technical details in an overview of how the PR works (e.g. “Once the user enters their password, the password is hashed using BCrypt and stored in the Users database field”). + +### Bug Fix PRs + +Give an overview of how your PR fixes the bug both as a high-level overview and a technical explanation of what caused the issue and how your PR resolves this. + +Add a short video or screenshots of what your PR achieves. Loom is a great way of sharing short videos however you can upload your videos directly to the PR description. + +### Code Quality & Styling + +All submitted code must match our **[code styling](https://www.notion.so/Code-Styling-65ddc5dd2deb4b28a9876f1f7cc89ca9?pvs=21)** standards. We will reject pull requests that differ significantly from our standardised code styles. + +All code is automatically checked by Github actions, and will notify you if there are any issues with the code that you submit. We require that code passes these quality checks before merging. + +### PR review process + +At the moment Matti is responsible for approving and merging pull requests, so please make sure to request his review when opening the PR and make the changes he requests in order to merge the PR. + +### Making a Pull Request + +- Be sure to **[check the "Allow edits from maintainers" option](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork)** while creating your PR. +- If your PR refers to or fixes an issue, be sure to add **`refs #XXX`** or **`fixes #XXX`** to the PR description. Replacing **`XXX`** with the respective issue number. See more about **[Linking a pull request to an issue](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue)** . +- Be sure to fill the PR Template accordingly. diff --git a/apps/formbricks-com/app/docs/contributing/introduction/page.mdx b/apps/formbricks-com/app/docs/contributing/introduction/page.mdx index 28ce951945..e852110835 100644 --- a/apps/formbricks-com/app/docs/contributing/introduction/page.mdx +++ b/apps/formbricks-com/app/docs/contributing/introduction/page.mdx @@ -1,6 +1,7 @@ export const meta = { title: "Formbricks Open Source Contribution Guide: How to Enhance yourself and Contribute to Formbricks", - description: "Join the Formbricks community and learn how to effectively contribute. From raising issues and feature requests to creating PRs, discover the best practices and communicate with our responsive team on Discord", + description: + "Join the Formbricks community and learn how to effectively contribute. From raising issues and feature requests to creating PRs, discover the best practices and communicate with our responsive team on Discord", }; #### Contributing @@ -36,3 +37,11 @@ We are currently working on having a clear [Roadmap](https://github.com/formbric But you can also pick a feature that is not already on the roadmap if you think it creates a positive impact for Formbricks. If you are at all unsure, just raise it as an enhancement issue first and tell us that you like to work on it, and we'll very quickly respond. + +## Contributor License Agreement (CLA) + +To be able to keep working on Formbricks over the coming years, we need to collect a CLA from all relevant contributors. + +Please note that we can only get your contribution merged when we have a CLA signed by you. + +To access the CLA form, please click [here](https://formbricks.com/clmyhzfrymr4ko00hycsg1tvx) diff --git a/apps/formbricks-com/app/docs/introduction/what-is-formbricks/page.mdx b/apps/formbricks-com/app/docs/introduction/what-is-formbricks/page.mdx index 4c41036d58..ea333e00fd 100644 --- a/apps/formbricks-com/app/docs/introduction/what-is-formbricks/page.mdx +++ b/apps/formbricks-com/app/docs/introduction/what-is-formbricks/page.mdx @@ -1,4 +1,5 @@ import { GettingStarted } from "@/components/docs/GettingStarted"; +import BestPractices from "@/components/docs/BestPractices"; import { HeroPattern } from "@/components/docs/HeroPattern"; import { Button } from "@/components/docs/Button"; diff --git a/apps/formbricks-com/app/docs/self-hosting/from-source/page.mdx b/apps/formbricks-com/app/docs/self-hosting/from-source/page.mdx index 89e3cbe2f0..f6209619e7 100644 --- a/apps/formbricks-com/app/docs/self-hosting/from-source/page.mdx +++ b/apps/formbricks-com/app/docs/self-hosting/from-source/page.mdx @@ -29,7 +29,7 @@ Ensure `docker` & `docker compose` are installed on your server/system. Both are -2. **Modify the `.env.docker` file as required by your setup.**
This file comes with a basic setup and Formbricks works without making any changes to the file. To enable email sending functionality you need to configure the SMTP settings. If you configured your email credentials, you can also comment the following lines to enable email verification (`# NEXT_PUBLIC_EMAIL_VERIFICATION_DISABLED=1`) and password reset (`# NEXT_PUBLIC_PASSWORD_RESET_DISABLED=1`) +2. **Modify the `.env.docker` file as required by your setup.**
This file comes with a basic setup and Formbricks works without making any changes to the file. To enable email sending functionality you need to configure the SMTP settings. If you configured your email credentials, you can also comment the following lines to enable email verification (`# EMAIL_VERIFICATION_DISABLED=1`) and password reset (`# PASSWORD_RESET_DISABLED=1`) ## Editing a NEXT_PUBLIC_* variable? @@ -50,67 +50,64 @@ Ensure `docker` & `docker compose` are installed on your server/system. Both are You can now access the app on [http://localhost:3000](http://localhost:3000). You will be automatically redirected to the login. To use your local installation of Formbricks, create a new account. -### Important Run-time Variables +## Important Run-time Variables These variables must also be provided at runtime. -| Variable | Description | Required | Default | -| ------------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ----------------------------------------------------------------------- | --- | -| WEBAPP_URL | Base URL of the site. | required | `http://localhost:3000` | -| DATABASE_URL | Database URL with credentials. | required | `postgresql://postgres:postgres@postgres:5432/formbricks?schema=public` | -| PRISMA_GENERATE_DATAPROXY | Enables a dedicated connection pool for Prisma using Prisma Data Proxy. Uncomment to enable. | optional | | -| NEXTAUTH_SECRET | Secret for NextAuth, used for session signing and encryption. | required | (Generated by the user) | -| NEXTAUTH_URL | Location of the auth server. By default, this is the Formbricks docker instance itself. | required | `http://localhost:3000` | -| MAIL_FROM | Email address to send emails from. | optional (required if email services are to be enabled) | | -| SMTP_HOST | Host URL of your SMTP server. | optional (required if email services are to be enabled) | | -| SMTP_PORT | Host Port of your SMTP server. | optional (required if email services are to be enabled) | | -| SMTP_USER | Username for your SMTP Server. | optional (required if email services are to be enabled) | | -| SMTP_PASSWORD | Password for your SMTP Server. | optional (required if email services are to be enabled) | | -| SMTP_SECURE_ENABLED | SMTP secure connection. For using TLS, set to `1` else to `0`. | optional (required if email services are to be enabled) | | -| GITHUB_ID | Client ID for GitHub. | optional (required if GitHub auth is enabled) | | -| GITHUB_SECRET | Secret for GitHub. | optional (required if GitHub auth is enabled) | | -| GOOGLE_CLIENT_ID | Client ID for Google. | optional (required if Google auth is enabled) | | -| GOOGLE_CLIENT_SECRET | Secret for Google. | optional (required if Google auth is enabled) | | -| CRON_SECRET | API Secret for running cron jobs. | optional | | -| STRIPE_SECRET_KEY | Secret key for Stripe integration. | optional | | -| STRIPE_WEBHOOK_SECRET | Webhook secret for Stripe integration. | optional | | -| TELEMETRY_DISABLED | Disables telemetry if set to `1`. | optional | | -| INSTANCE_ID | Instance ID for Formbricks Cloud to be sent to Telemetry. | optional | | -| INTERNAL_SECRET | Internal Secret (Currently we do not use this anywhere). | optional | | -| RENDER_EXTERNAL_URL | External URL for rendering (used instead of WEBAPP_URL). | optional | | -| HEROKU_APP_NAME | Heroku app name (used instead of WEBAPP_URL). | optional | | -| RAILWAY_STATIC_URL | Railway static URL (used instead of WEBAPP_URL). | optional | | | +| Variable | Description | Required | Default | +| --------------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ----------------------------------------------------------------------- | +| WEBAPP_URL | Base URL of the site. | required | `http://localhost:3000` | +| SURVEY_BASE_URL | Base URL of the link surveys. | required | `http://localhost:3000/s/` | +| DATABASE_URL | Database URL with credentials. | required | `postgresql://postgres:postgres@postgres:5432/formbricks?schema=public` | +| PRISMA_GENERATE_DATAPROXY | Enables a dedicated connection pool for Prisma using Prisma Data Proxy. Uncomment to enable. | optional | | +| NEXTAUTH_SECRET | Secret for NextAuth, used for session signing and encryption. | required | (Generated by the user) | +| NEXTAUTH_URL | Location of the auth server. By default, this is the Formbricks docker instance itself. | required | `http://localhost:3000` | +| PRIVACY_URL | URL for privacy policy. | optional | | +| TERMS_URL | URL for terms of service. | optional | | +| IMPRINT_URL | URL for imprint. | optional | | +| SIGNUP_DISABLED | Disables the ability for new users to create an account if set to `1`. | optional | | +| PASSWORD_RESET_DISABLED | Disables password reset functionality if set to `1`. | optional | | +| EMAIL_VERIFICATION_DISABLED | Disables email verification if set to `1`. | optional | | +| INVITE_DISABLED | Disables the ability for invited users to create an account if set to `1`. | optional | | +| MAIL_FROM | Email address to send emails from. | optional (required if email services are to be enabled) | | +| SMTP_HOST | Host URL of your SMTP server. | optional (required if email services are to be enabled) | | +| SMTP_PORT | Host Port of your SMTP server. | optional (required if email services are to be enabled) | | +| SMTP_USER | Username for your SMTP Server. | optional (required if email services are to be enabled) | | +| SMTP_PASSWORD | Password for your SMTP Server. | optional (required if email services are to be enabled) | | +| SMTP_SECURE_ENABLED | SMTP secure connection. For using TLS, set to `1` else to `0`. | optional (required if email services are to be enabled) | | +| GITHUB_AUTH_ENABLED | Enables GitHub login if set to `1`. | optional | | +| GOOGLE_AUTH_ENABLED | Enables Google login if set to `1`. | optional | | +| GITHUB_ID | Client ID for GitHub. | optional (required if GitHub auth is enabled) | | +| GITHUB_SECRET | Secret for GitHub. | optional (required if GitHub auth is enabled) | | +| GOOGLE_CLIENT_ID | Client ID for Google. | optional (required if Google auth is enabled) | | +| GOOGLE_CLIENT_SECRET | Secret for Google. | optional (required if Google auth is enabled) | | +| CRON_SECRET | API Secret for running cron jobs. | optional | | +| STRIPE_SECRET_KEY | Secret key for Stripe integration. | optional | | +| STRIPE_WEBHOOK_SECRET | Webhook secret for Stripe integration. | optional | | +| TELEMETRY_DISABLED | Disables telemetry if set to `1`. | optional | | +| INSTANCE_ID | Instance ID for Formbricks Cloud to be sent to Telemetry. | optional | | +| INTERNAL_SECRET | Internal Secret (Currently we overwrite the value with a random value). | optional | | +| IS_FORMBRICKS_CLOUD | Uses Formbricks Cloud if set to `1` | optional | | +| DEFAULT_BRAND_COLOR | Default brand color for your app (Can be overwritten from the UI as well). | optional | `#64748b` | -### Build-time Variables +## Build-time Variables These variables must be provided at the time of the docker build and can be provided by updating the `.env` file. -| Variable | Description | Required | Default | -| -------------------------------------------------- | -------------------------------------------------------------------------- | -------- | ----------------------- | -| NEXT_PUBLIC_WEBAPP_URL | Base URL injected into static files. | required | `http://localhost:3000` | -| NEXT_PUBLIC_EMAIL_VERIFICATION_DISABLED | Disables email verification if set to `1`. | optional | | -| NEXT_PUBLIC_PASSWORD_RESET_DISABLED | Disables password reset functionality if set to `1`. | optional | | -| NEXT_PUBLIC_SIGNUP_DISABLED | Disables the ability for new users to create an account if set to `1`. | optional | | -| NEXT_PUBLIC_INVITE_DISABLED | Disables the ability for invited users to create an account if set to `1`. | optional | | -| NEXT_PUBLIC_PRIVACY_URL | URL for privacy policy. | optional | | -| NEXT_PUBLIC_TERMS_URL | URL for terms of service. | optional | | -| NEXT_PUBLIC_IMPRINT_URL | URL for imprint. | optional | | -| NEXT_PUBLIC_GITHUB_AUTH_ENABLED | Enables GitHub login if set to `1`. | optional | | -| NEXT_PUBLIC_GOOGLE_AUTH_ENABLED | Enables Google login if set to `1`. | optional | | -| NEXT_PUBLIC_FORMBRICKS_API_HOST | Host for the Formbricks API. | optional | | -| NEXT_PUBLIC_FORMBRICKS_ENVIRONMENT_ID | If you already have a preset environment ID of the environment. | optional | | -| NEXT_PUBLIC_FORMBRICKS_ONBOARDING_SURVEY_ID | If you already have an onboarding survey ID to show new users. | optional | | -| NEXT_PUBLIC_IS_FORMBRICKS_CLOUD | Uses Formbricks Cloud if set to `1` | optional | | -| NEXT_PUBLIC_POSTHOG_API_KEY | API key for PostHog analytics. | optional | | -| NEXT_PUBLIC_POSTHOG_API_HOST | Host for PostHog analytics. | optional | | -| NEXT_PUBLIC_SENTRY_DSN | DSN for Sentry error tracking. | optional | | -| NEXT_PUBLIC_DOCSEARCH_APP_ID | ID of the DocSearch application. | optional | | -| NEXT_PUBLIC_DOCSEARCH_API_KEY | API key of the DocSearch application. | optional | | -| NEXT_PUBLIC_DOCSEARCH_INDEX_NAME | Name of the DocSearch index. | optional | | -| NEXT_PUBLIC_FORMBRICKS_COM_ENVIRONMENT_ID | Environment ID for Formbricks (if you already have one) | optional | | -| NEXT_PUBLIC_FORMBRICKS_COM_DOCS_FEEDBACK_SURVEY_ID | Survey ID for the feedback survey on the docs site. | optional | | -| NEXT_PUBLIC_FORMBRICKS_COM_API_HOST | Host for the Formbricks API. | optional | | -| NEXT_PUBLIC_VERCEL_URL | Vercel URL (used instead of WEBAPP_URL). | optional | +| Variable | Description | Required | Default | +| -------------------------------------------------- | --------------------------------------------------------------- | -------- | ------- | +| NEXT_PUBLIC_FORMBRICKS_API_HOST | Host for the Formbricks API. | optional | | +| NEXT_PUBLIC_FORMBRICKS_ENVIRONMENT_ID | If you already have a preset environment ID of the environment. | optional | | +| NEXT_PUBLIC_FORMBRICKS_ONBOARDING_SURVEY_ID | If you already have an onboarding survey ID to show new users. | optional | | +| NEXT_PUBLIC_POSTHOG_API_KEY | API key for PostHog analytics. | optional | | +| NEXT_PUBLIC_POSTHOG_API_HOST | Host for PostHog analytics. | optional | | +| NEXT_PUBLIC_SENTRY_DSN | DSN for Sentry error tracking. | optional | | +| NEXT_PUBLIC_DOCSEARCH_APP_ID | ID of the DocSearch application. | optional | | +| NEXT_PUBLIC_DOCSEARCH_API_KEY | API key of the DocSearch application. | optional | | +| NEXT_PUBLIC_DOCSEARCH_INDEX_NAME | Name of the DocSearch index. | optional | | +| NEXT_PUBLIC_FORMBRICKS_COM_ENVIRONMENT_ID | Environment ID for Formbricks (if you already have one) | optional | | +| NEXT_PUBLIC_FORMBRICKS_COM_DOCS_FEEDBACK_SURVEY_ID | Survey ID for the feedback survey on the docs site. | optional | | +| NEXT_PUBLIC_FORMBRICKS_COM_API_HOST | Host for the Formbricks API. | optional | | ## Debugging diff --git a/apps/formbricks-com/app/docs/self-hosting/migrating-to-1.1/page.mdx b/apps/formbricks-com/app/docs/self-hosting/migrating-to-1.1/page.mdx new file mode 100644 index 0000000000..7d3ab4f1b2 --- /dev/null +++ b/apps/formbricks-com/app/docs/self-hosting/migrating-to-1.1/page.mdx @@ -0,0 +1,138 @@ +export const meta = { + title: "Migrating Formbricks to v1.1", + description: + "Formbricks v1.1 comes with an amazing set of features including the ability to define most environment variables at runtime itself! No need to build the image again! This guide will help you migrate your existing Formbricks instance to v1.1", +}; + +#### Self-Hosting + +# Migrating to v1.1 + +Formbricks v1.1 includes a lot of new features and improvements. However, it also comes with a few breaking changes specifically with the environment variables. This guide will help you migrate your existing Formbricks instance to v1.1 without losing any data. + +## Changes in .env + +### Renamed Environment Variables +This was introduced because we got a lot of requests from our users for the ability to define some common environment variables at runtime itself i.e. without having to rebuild the image for the changes to take effect. +This is now possible with v1.1. However, due to Next.JS best practices, we had to deprecate the prefix **NEXT_PUBLIC_** in the following environment variables: + +| till v1.0 | v1.1 | +| ------------------------------------------- | --------------------------- | +| **NEXT_PUBLIC_**EMAIL_VERIFICATION_DISABLED | EMAIL_VERIFICATION_DISABLED | +| **NEXT_PUBLIC_**PASSWORD_RESET_DISABLED | PASSWORD_RESET_DISABLED | +| **NEXT_PUBLIC_**SIGNUP_DISABLED | SIGNUP_DISABLED | +| **NEXT_PUBLIC_**INVITE_DISABLED | INVITE_DISABLED | +| **NEXT_PUBLIC_**PRIVACY_URL | PRIVACY_URL | +| **NEXT_PUBLIC_**TERMS_URL | TERMS_URL | +| **NEXT_PUBLIC_**IMPRINT_URL | IMPRINT_URL | +| **NEXT_PUBLIC_**GITHUB_AUTH_ENABLED | GITHUB_AUTH_ENABLED | +| **NEXT_PUBLIC_**GOOGLE_AUTH_ENABLED | GOOGLE_AUTH_ENABLED | +| **NEXT_PUBLIC_**WEBAPP_URL | WEBAPP_URL | +| **NEXT_PUBLIC_**IS_FORMBRICKS_CLOUD | IS_FORMBRICKS_CLOUD | +| **NEXT_PUBLIC_**SURVEY_BASE_URL | SURVEY_BASE_URL | + + +Please note that their values and the logic remains exactly the same. Only the prefix has been deprecated. The other environment variables remain the same as well. + + +### Deprecated Environment Variables + +- **NEXT_PUBLIC_VERCEL_URL**: Was used as Vercel URL (used instead of WEBAPP_URL), but from v1.1, you can just set the WEBAPP_URL environment variable to your Vercel URL. +- **RAILWAY_STATIC_URL**: Was used as Railway Static URL (used instead of WEBAPP_URL), but from v1.1, you can just set the WEBAPP_URL environment variable. +- **RENDER_EXTERNAL_URL**: Was used as an external URL to Render (used instead of WEBAPP_URL), but from v1.1, you can just set the WEBAPP_URL environment variable. +- **HEROKU_APP_NAME**: Was used to build the App name on a Heroku hosted webapp, but from v1.1, you can just set the WEBAPP_URL environment variable. +- **NEXT_PUBLIC_WEBAPP_URL**: Was used for the same purpose as WEBAPP_URL, but from v1.1, you can just set the WEBAPP_URL environment variable. +- **PRISMA_GENERATE_DATAPROXY**: Was used to tell Prisma that it should generate the runtime for Dataproxy usage. But its officially deprecated now. + +## Helper Shell Script +For a seamless migration, below is a shell script for your self-hosted instance that will automatically update your environment variables to be compliant with the new naming conventions. + +### Building From Source +The below script will: +1. Create a backup of your existing .env file as `.env.old` +2. Update the .env file to be compliant with the new naming conventions + + +```shell {{ title: '.env file' }} +for var in NEXT_PUBLIC_EMAIL_VERIFICATION_DISABLED NEXT_PUBLIC_PASSWORD_RESET_DISABLED NEXT_PUBLIC_SIGNUP_DISABLED NEXT_PUBLIC_INVITE_DISABLED NEXT_PUBLIC_PRIVACY_URL NEXT_PUBLIC_TERMS_URL NEXT_PUBLIC_IMPRINT_URL NEXT_PUBLIC_GITHUB_AUTH_ENABLED NEXT_PUBLIC_GOOGLE_AUTH_ENABLED NEXT_PUBLIC_WEBAPP_URL NEXT_PUBLIC_IS_FORMBRICKS_CLOUD NEXT_PUBLIC_SURVEY_BASE_URL; do sed -i.old "s/^$var=/$(echo $var | sed 's/NEXT_PUBLIC_//')=/" .env; done; echo "Formbricks environment variables have been migrated as per v1.1! You are good to go." +``` + + + +### Docker & Single Script Setup + +Now that these variables can be defined at runtime, you can append them inside your `x-environment` in the `docker-compose.yml` itself. +For a more detailed guide on these environment variables, please refer to the [Important Runtime Variables](/docs/self-hosting/from-source#important-run-time-variables) section. + + +```yaml {{ title: 'docker-compose.yml' }} +version: "3.3" +x-environment: &environment + environment: + # The url of your Formbricks instance used in the admin panel + WEBAPP_URL: + + # PostgreSQL DB for Formbricks to connect to + DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/formbricks?schema=public" + + # Uncomment to enable a dedicated connection pool for Prisma using Prisma Data Proxy + # Cold boots will be faster and you'll be able to scale your DB independently of your app. + # @see https://www.prisma.io/docs/data-platform/data-proxy/use-data-proxy + # PRISMA_GENERATE_DATAPROXY=true + PRISMA_GENERATE_DATAPROXY: + + # NextJS Auth + # @see: https://next-auth.js.org/configuration/options#nextauth_secret + # You can use: `openssl rand -base64 32` to generate one + NEXTAUTH_SECRET: + + # Set this to your public-facing URL, e.g., https://example.com + # You do not need the NEXTAUTH_URL environment variable in Vercel. + NEXTAUTH_URL: http://localhost:3000 + + # PostgreSQL password + POSTGRES_PASSWORD: postgres + + # Email Configuration + MAIL_FROM: + SMTP_HOST: + SMTP_PORT: + SMTP_SECURE_ENABLED: + SMTP_USER: + SMTP_PASSWORD: + + # Uncomment the below and set it to 1 to disable Email Verification for new signups + # EMAIL_VERIFICATION_DISABLED: + + # Uncomment the below and set it to 1 to disable Password Reset + # PASSWORD_RESET_DISABLED: + + # Uncomment the below and set it to 1 to disable Signups + # SIGNUP_DISABLED: + + # Uncomment the below and set it to 1 to disable Invites + # INVITE_DISABLED: + + # Uncomment the below and set a value to have your own Privacy Page URL on the signup & login page + # PRIVACY_URL: + + # Uncomment the below and set a value to have your own Terms Page URL on the auth and the surveys page + # TERMS_URL: + + # Uncomment the below and set a value to have your own Imprint Page URL on the auth and the surveys page + # IMPRINT_URL: + + # Uncomment the below and set to 1 if you want to enable GitHub OAuth + # GITHUB_AUTH_ENABLED: + # GITHUB_ID: + # GITHUB_SECRET: + + # Uncomment the below and set to 1 if you want to enable Google OAuth + # GOOGLE_AUTH_ENABLED: + # GOOGLE_CLIENT_ID: + # GOOGLE_CLIENT_SECRET: + +``` + + +Did we miss something? Are you still facing issues migrating your app? [Join our Discord!](https://formbricks.com/discord) We'd be happy to help! \ No newline at end of file diff --git a/apps/formbricks-com/components/docs/BestPractices.tsx b/apps/formbricks-com/components/docs/BestPractices.tsx index c01a2a24ab..b48d3036e1 100644 --- a/apps/formbricks-com/components/docs/BestPractices.tsx +++ b/apps/formbricks-com/components/docs/BestPractices.tsx @@ -151,7 +151,7 @@ function BestPractice({ resource }: { resource: BestPractice }) { ); } -export function BestPractices() { +export default function BestPractices() { return (
diff --git a/apps/formbricks-com/components/docs/Navigation.tsx b/apps/formbricks-com/components/docs/Navigation.tsx index 7d8c2b28f4..28ffa757ca 100644 --- a/apps/formbricks-com/components/docs/Navigation.tsx +++ b/apps/formbricks-com/components/docs/Navigation.tsx @@ -1,16 +1,16 @@ "use client"; -import { useRef } from "react"; -import Link from "next/link"; -import { usePathname } from "next/navigation"; import clsx from "clsx"; import { AnimatePresence, motion, useIsPresent } from "framer-motion"; +import Link from "next/link"; +import { usePathname } from "next/navigation"; +import { useRef } from "react"; +import { remToPx } from "@/lib/remToPx"; import { Button } from "./Button"; import { useIsInsideMobileNavigation } from "./MobileNavigation"; import { useSectionStore } from "./SectionProvider"; import { Tag } from "./Tag"; -import { remToPx } from "@/lib/remToPx"; interface NavGroup { title: string; @@ -246,13 +246,16 @@ export const navigation: Array = [ { title: "Production", href: "/docs/self-hosting/production" }, { title: "Docker", href: "/docs/self-hosting/docker" }, { title: "From Source", href: "/docs/self-hosting/from-source" }, + { title: "Migration to v1.1", href: "/docs/self-hosting/migrating-to-1.1" }, ], }, { title: "Contributing", links: [ { title: "Introduction", href: "/docs/contributing/introduction" }, + { title: "How we code at Formbricks", href: "/docs/contributing/how-we-code" }, { title: "Setup Dev Environment", href: "/docs/contributing/setup" }, + { title: "Gitpod", href: "/docs/contributing/gitpod" }, { title: "Demo App", href: "/docs/contributing/demo" }, { title: "Troubleshooting", href: "/docs/contributing/troubleshooting" }, { title: "FaQ", href: "/docs/faq" }, diff --git a/apps/formbricks-com/components/home/GitHubSponsorship.tsx b/apps/formbricks-com/components/home/GitHubSponsorship.tsx index a089c5b7dd..4e331ec086 100644 --- a/apps/formbricks-com/components/home/GitHubSponsorship.tsx +++ b/apps/formbricks-com/components/home/GitHubSponsorship.tsx @@ -1,5 +1,4 @@ -import GitHubMarkWhite from "@/images/github-mark-white.svg"; -import GitHubMarkDark from "@/images/github-mark.svg"; +import HackIconGold from "@/images/formtribe/hack-icon-gold.svg"; import Image from "next/image"; import Link from "next/link"; @@ -10,7 +9,7 @@ export const GitHubSponsorship: React.FC = () => { @media (min-width: 426px); `}
- GitHub Sponsors Formbricks badge { alt="GitHub Sponsors Formbricks badge" width={100} height={100} - className="mr-12 hidden dark:block md:mr-4 " + className="mr-12 hidden dark:block md:mr-4" + /> */} + Hacktober Icon Gold

- Proudly Open-Source 🤍 + The FormTribe goes Hacktoberfest 🥨

- We're proud to to be supported by GitHubs Open-Source Program!{" "} + Write code, win a Mac! We're running a Hacktoberfest community Hackathon: - - Read more. + + Find out more.

diff --git a/apps/formbricks-com/components/home/Hero.tsx b/apps/formbricks-com/components/home/Hero.tsx index 2b06350668..89552ac8a2 100644 --- a/apps/formbricks-com/components/home/Hero.tsx +++ b/apps/formbricks-com/components/home/Hero.tsx @@ -20,10 +20,10 @@ export const Hero: React.FC = ({}) => {
- We're Open-Source | Star us on GitHub{" "} + className="border-brand-dark animate-bounce rounded-full border px-4 py-1.5 text-sm text-slate-500 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800"> + The FormTribe Hackathon is on 🔥

diff --git a/apps/formbricks-com/components/shared/Header.tsx b/apps/formbricks-com/components/shared/Header.tsx index 76b57ee726..65ef9c71c9 100644 --- a/apps/formbricks-com/components/shared/Header.tsx +++ b/apps/formbricks-com/components/shared/Header.tsx @@ -250,7 +250,7 @@ export default function Header() { */} Pricing diff --git a/apps/formbricks-com/components/shared/OpenSourceInfo.tsx b/apps/formbricks-com/components/shared/OpenSourceInfo.tsx new file mode 100644 index 0000000000..99b810b92e --- /dev/null +++ b/apps/formbricks-com/components/shared/OpenSourceInfo.tsx @@ -0,0 +1,33 @@ +import { Button } from "@formbricks/ui"; + +export const OpenSourceInfo = () => { + return ( +
+
+
+

+ Open Source +

+ +

+ Formbricks is an open source project. You can self-host it for free. We provide multiple easy + deployment options as per your customisation needs. We have documented the process of self-hosting + Formbricks on your own server using Docker, Bash Scripting, and Building from Source. +

+
+ + +
+
+
+
+ ); +}; diff --git a/apps/formbricks-com/components/shared/PricingCalculator.tsx b/apps/formbricks-com/components/shared/PricingCalculator.tsx new file mode 100644 index 0000000000..03972ac30f --- /dev/null +++ b/apps/formbricks-com/components/shared/PricingCalculator.tsx @@ -0,0 +1,115 @@ +import { Slider } from "@/components/shared/Slider"; +import { useState } from "react"; + +const ProductItem = ({ label, usersCount, price, onSliderChange }) => ( +
+
+
+ {label} +
+
+ {Math.round(usersCount).toLocaleString()} MTU +
+
+ ${price.toFixed(2)} +
+
+
+ +
+ {[3, 4, 5, 6].map((mark) => ( + + {mark === 3 ? "1K" : mark === 4 ? "10K" : mark === 5 ? "100K" : "1M"} + + ))} +
+
+
+); + +const Headers = () => ( +
+

Product

+

+ Subtotal +

+
+); + +const MonthlyEstimate = ({ price }) => ( +
+ + Monthly estimate: + +
+ + ${price.toFixed(2)} + + + {" "} + / month + +
+
+); + +export const PricingCalculator = () => { + const [inProductSlider, setInProductSlider] = useState(Math.log10(1000)); + const [linkSlider, setLinkSlider] = useState(Math.log10(1000)); + + const transformToLog = (value) => Math.pow(10, value); + + const calculatePrice = (users) => { + if (users <= 5000) { + return 0; + } else { + return users * 0.005; + } + }; + + const usersCountForInProductSlider = transformToLog(inProductSlider); + const productSurveysPrice = calculatePrice(usersCountForInProductSlider); + + return ( +
+

+ Pricing Calculator +

+ +
+
+ + +
+ + setInProductSlider(value[0])} + /> + +
+ + setLinkSlider(value[0])} + /> + +
+ + +
+
+
+ ); +}; diff --git a/apps/formbricks-com/components/shared/PricingGetStarted.tsx b/apps/formbricks-com/components/shared/PricingGetStarted.tsx new file mode 100644 index 0000000000..a93df8b2a0 --- /dev/null +++ b/apps/formbricks-com/components/shared/PricingGetStarted.tsx @@ -0,0 +1,47 @@ +import { Button } from "@formbricks/ui"; + +export const GetStartedWithPricing = ({ showDetailed }: { showDetailed: boolean }) => { + return ( + <> +
+
+
+

Free

+ + {showDetailed && ( +

+ General free usage on every product. Best for early stage startups and hobbyists +

+ )} + + +
+
+

Paid

+ {showDetailed && ( +

+ Formbricks with the next-generation features, Pay only for the tracked users. +

+ )} + + +
+
+
+ + ); +}; diff --git a/apps/formbricks-com/components/shared/PricingTable.tsx b/apps/formbricks-com/components/shared/PricingTable.tsx new file mode 100644 index 0000000000..f997336626 --- /dev/null +++ b/apps/formbricks-com/components/shared/PricingTable.tsx @@ -0,0 +1,103 @@ +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@formbricks/ui"; +import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; + +export const PricingTable = ({ leadRow, pricing, endRow }) => { + return ( +
+
+
+
+ {leadRow.title} +
+
+ {leadRow.free} +
+ +
+ {leadRow.paid} +
+
+
+ +
+ {pricing.map((feature) => ( +
+
+ {feature.name} + {feature.addOnText && ( + + Addon + + )} +
+
+ {feature.addOnText ? ( + + + + {feature.free} + + +

+ {feature.addOnText} +

+
+
+
+ ) : feature.free ? ( +
+ +
+ ) : ( +
+ +
+ )} +
+
+ {feature.addOnText ? ( + + + + {feature.paid} + + +

+ {feature.addOnText} +

+
+
+
+ ) : feature.paid ? ( +
+ +
+ ) : ( +
+ +
+ )} +
+
+ ))} +
+ +
+
+
+ {endRow.title} +
+
+ {endRow.free} +
+ +
+ {endRow.paid} +
+
+
+
+ ); +}; diff --git a/apps/formbricks-com/components/shared/Slider.tsx b/apps/formbricks-com/components/shared/Slider.tsx new file mode 100644 index 0000000000..07bce61744 --- /dev/null +++ b/apps/formbricks-com/components/shared/Slider.tsx @@ -0,0 +1,24 @@ +"use client"; + +import * as React from "react"; +import * as SliderPrimitive from "@radix-ui/react-slider"; + +import { cn } from "@formbricks/lib/cn"; + +const Slider = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + + + + +)); +Slider.displayName = SliderPrimitive.Root.displayName; + +export { Slider }; diff --git a/apps/formbricks-com/components/shared/icons/XCircleIcon.jsx b/apps/formbricks-com/components/shared/icons/XCircleIcon.jsx new file mode 100644 index 0000000000..d1573c7733 --- /dev/null +++ b/apps/formbricks-com/components/shared/icons/XCircleIcon.jsx @@ -0,0 +1,13 @@ + + +; diff --git a/apps/formbricks-com/images/formtribe/hack-icon-gold.svg b/apps/formbricks-com/images/formtribe/hack-icon-gold.svg new file mode 100644 index 0000000000..0286b6b8a0 --- /dev/null +++ b/apps/formbricks-com/images/formtribe/hack-icon-gold.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/formbricks-com/package.json b/apps/formbricks-com/package.json index 1101313dfd..338b344d89 100644 --- a/apps/formbricks-com/package.json +++ b/apps/formbricks-com/package.json @@ -24,14 +24,14 @@ "@mapbox/rehype-prism": "^0.8.0", "@mdx-js/loader": "^2.3.0", "@mdx-js/react": "^2.3.0", - "@next/mdx": "13.5.3", + "@next/mdx": "13.4.19", "@paralleldrive/cuid2": "^2.2.2", "@sindresorhus/slugify": "^2.2.1", "@tailwindcss/typography": "^0.5.10", - "@types/node": "20.7.0", - "@types/react-highlight-words": "^0.16.5", + "@types/node": "20.6.0", + "@types/react-highlight-words": "^0.16.4", "acorn": "^8.10.0", - "autoprefixer": "^10.4.16", + "autoprefixer": "^10.4.15", "clsx": "^2.0.0", "fast-glob": "^3.3.1", "flexsearch": "^0.7.31", @@ -39,14 +39,16 @@ "lottie-web": "^5.12.2", "mdast-util-to-string": "^4.0.0", "mdx-annotations": "^0.1.3", - "next": "13.5.3", + "next": "13.4.19", "next-plausible": "^3.11.1", "next-seo": "^6.1.0", "next-sitemap": "^4.2.3", "next-themes": "^0.2.1", "node-fetch": "^3.3.2", - "prism-react-renderer": "^2.1.0", + "prism-react-renderer": "^2.0.6", "prismjs": "^1.29.0", + "@radix-ui/react-slider": "^1.1.2", + "@radix-ui/react-tooltip": "^1.0.6", "react": "18.2.0", "react-dom": "18.2.0", "react-highlight-words": "^0.20.0", @@ -56,7 +58,7 @@ "remark": "^14.0.3", "remark-gfm": "^3.0.1", "remark-mdx": "^2.3.0", - "sharp": "^0.32.6", + "sharp": "^0.32.5", "shiki": "^0.14.4", "simple-functional-loader": "^1.2.1", "tailwindcss": "^3.3.3", diff --git a/apps/formbricks-com/pages/blog/join-the-formtribe/create-a-new-survey-with-formbricks.png b/apps/formbricks-com/pages/blog/join-the-formtribe/create-a-new-survey-with-formbricks.png new file mode 100644 index 0000000000..6803f12105 Binary files /dev/null and b/apps/formbricks-com/pages/blog/join-the-formtribe/create-a-new-survey-with-formbricks.png differ diff --git a/apps/formbricks-com/pages/blog/join-the-formtribe/formbricks-monorepo-folder-structure.png b/apps/formbricks-com/pages/blog/join-the-formtribe/formbricks-monorepo-folder-structure.png new file mode 100644 index 0000000000..5ac0e6b4c5 Binary files /dev/null and b/apps/formbricks-com/pages/blog/join-the-formtribe/formbricks-monorepo-folder-structure.png differ diff --git a/apps/formbricks-com/pages/blog/join-the-formtribe/formbricks-packages-folder.png b/apps/formbricks-com/pages/blog/join-the-formtribe/formbricks-packages-folder.png new file mode 100644 index 0000000000..29e9f5f233 Binary files /dev/null and b/apps/formbricks-com/pages/blog/join-the-formtribe/formbricks-packages-folder.png differ diff --git a/apps/formbricks-com/pages/blog/join-the-formtribe/index.mdx b/apps/formbricks-com/pages/blog/join-the-formtribe/index.mdx new file mode 100644 index 0000000000..8264126c90 --- /dev/null +++ b/apps/formbricks-com/pages/blog/join-the-formtribe/index.mdx @@ -0,0 +1,107 @@ +import Image from "next/image"; +import LayoutMdx from "@/components/shared/LayoutMdx"; +import MonorepoImage from "./formbricks-monorepo-folder-structure.png"; +import HeaderImage from "./create-a-new-survey-with-formbricks.png"; +import GitpodImage from "./setup-formbricks-via-gitpod.png"; +import PackagesFolderImage from "./formbricks-packages-folder.png"; +import AuthorBox from "@/components/shared/AuthorBox"; + +export const meta = { + title: "Join the FormTribe 🔥", + description: "Here is everything you need to know about joining the Formbricks community", + date: "2023-10-01", + publishedTime: "2023-10-01T00:00:00", + authors: ["Johannes"], + section: "Open-Source", + tags: ["Open-Source", "No-Code", "Formbricks", "Geting started", "Welcome guide"], +}; + + + +Title Image + +_Get a quick intro to the Formbricks community, also known as FormTribe, and learn all the deets about making awesome contributions to the project._ + +## Welcome to the Formbricks community! + +We are so excited to have you with us 😊 + +In this post we will be helping you get familiar with the Formbricks codebase and get you up to speed contributing in no time. If you want to learn about Formbricks check out our [docs intro](https://formbricks.com/docs/introduction/what-is-formbricks), for more info about our founding story and why we're building open source checkout out our [blog](https://formbricks.com/blog). + +### Prerequisites + +Our codebase is written fully in Typescript and we love it 😍. To power our the experience management solution, here is the stack behind it all: + +[Next.js](https://nextjs.org/) - React Framework + +[Prisma](https://www.prisma.io/) - ORM + +[Typescript](https://www.typescriptlang.org/) - Language + +[Lucide React](https://lucide.dev/guide/packages/lucide-react) - Icons + +[TalwindCSS](https://tailwindcss.com/) - Styling + +[Zod](https://zod.dev/) - Validation + +[Auth.js](https://authjs.dev/) - Authentication + +### 😎 Installation and Setup + +To get up and running we have 2 options: Gitpod and local. + +#### Get started with Gitpod + +With Gitpod you can run all of Formbricks in the cloud. With one click you can start coding right away in your browser: + +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/formbricks/formbricks) + +Setup Formbricks via Gitpod + +#### Run on a local machine + +If you choose to get setup locally, we also have a well documented guide to hold you through the process, you can find it [here](https://formbricks.com/docs/contributing/setup) + +### 👩🏽‍💻 Codebase Overview + +Our codebase is a [monorepo](https://en.wikipedia.org/wiki/Monorepo) which means we have different projects in one repository. At moment we have 3 different projects: + +1. **demo** `apps/demo` - It's a simple React app that you can run locally and use to trigger actions and set **[Attributes](https://formbricks.com/docs/attributes/why)**. It allows you to test your setup easily. +2. **formbricks-com** `apps/formbricks-com` - The landing page of [Formbricks](https://formbricks.com) +3. **web** `apps/web` - Our [cloud offering](https://app.formbricks.com/) for Formbricks. + +Formbricks monorepo folder structure + +#### TurboRepo and our own packages + +To manage all of these projects in one repository we use [turborepo](https://turbo.build/repo/docs/core-concepts/monorepos). Depending on what part of the codebase you need to contribute in, now you know where to begin 😃 + +We also have a set of packages which we manage: They are located in the `packages` folder. There we keep our styling library, components, database migrations and connection, a couple of configurations and much more. We do this to use any of these packages seamlessly between our mono repos. + +Formbricks packages folder + +### ⚖️ Contribution Guidelines + +You want to get started contributing? Amazing! Checkout our must-read post on [How we Code at Formbricks](https://formbricks.com/docs/contributing/how-we-code). This will give you everything you need to know about successfully contributing to our codebase in no time. + +### 🤗 Our Community + +We really value our community. It might be small but it is close to our hearts. Join our [Discord](https://formbricks.com/discord) to learn from other contributors and meet the Formbricks community. + +### Conclusion + +Contributing to open source projects like Formbricks can be a rewarding experience. By contributing, you have the opportunity to make a meaningful impact on a project used by many and gain valuable experience in the process. + +Whether you are a seasoned developer or just starting out, your contributions are appreciated. We might not always have to onboard everyone but try our best. You can help improve the codebase, fix bugs, add new features, or even contribute to the documentation. Every contribution, no matter how small, can make a difference. + +Not only will you be able to showcase your skills and build your portfolio, but you will also have the chance to collaborate with other talented designers and developers in the Formbricks community. You can learn from their expertise and share your own knowledge. + +### So, why wait? + +Join the Formbricks community today and start contributing to an up and coming open source project. Your contributions can help shape the future of Formbricks and make a positive impact on the lives of tens of thousands of users worldwide. + +We look forward to seeing your contributions and welcoming you to the Formbricks community! + +### [Say Hi 👋](https://formbricks.com/discord) + +export default ({ children }) => {children}; diff --git a/apps/formbricks-com/pages/blog/join-the-formtribe/setup-formbricks-via-gitpod.png b/apps/formbricks-com/pages/blog/join-the-formtribe/setup-formbricks-via-gitpod.png new file mode 100644 index 0000000000..4756254185 Binary files /dev/null and b/apps/formbricks-com/pages/blog/join-the-formtribe/setup-formbricks-via-gitpod.png differ diff --git a/apps/formbricks-com/pages/formtribe/index.tsx b/apps/formbricks-com/pages/formtribe/index.tsx index e6997206e3..9a993efd3f 100644 --- a/apps/formbricks-com/pages/formtribe/index.tsx +++ b/apps/formbricks-com/pages/formtribe/index.tsx @@ -16,65 +16,117 @@ import { useEffect } from "react"; const HowTo = [ { step: "1", - header: "Pick an issue from the list below (or start with a side quest)", + header: "Pick a 'FormTribe 🔥' issue in our repository and comment.", + link: "https://formbricks.com/github", }, { step: "2", - header: "Comment on the issue to signal that you started working on it.", + header: "Be the first to comment and get the issue assigned.", }, { step: "3", - header: "Join our Discord to ask questions and submit side quests.", - link: "https://formbricks.com/discord", + header: "You now have 24h to open a draft PR ⏲️", }, { step: "4", - header: "Code and open a PR with your contribution. ", + header: "If your PR looks promising, we'll work with you to get it merged.", }, { step: "5", - header: "Get your PR merged and collect points.", + header: "For every merged PR you collect points ✨", }, { step: "6", - header: "Tweet about your contribution and tag @formbricks", + header: "Solve side quests to increase your chances on the MacBook 👀", + link: "#prizes", }, { step: "7", - header: "Solve side quests to increase your chances on the MacBook 👀", - link: "#prizes", + header: "Join our Discord to ask questions (and submit side quests).", + link: "https://formbricks.com/discord", }, ]; const SideQuests = [ { - points: "100 Points:", - quest: "You think you're smart removing the blur to see the side quests first?", + points: "Join the Tribe Tweet (100 Points)", + quest: "Tweet a single “🧱” emoji before the 7th of October EOD to join the #FormTribe.", + proof: "Share the link to the tweet in the “side-quest” channel.", }, { - points: "150 Points:", + points: "Spread the Word Tweet (100 Points)", + quest: "Tweet “🧱🚀” on the day of the ProductHunt launch to spread the word.", + proof: "Share the link to the tweet in the “side-quest” channel.", + }, + { + points: "Setup Insights (200 Points)", + quest: "Screen record yourself setting up the Formbricks dev environment.", + proof: "Upload to WeTransfer and send to johannes@formbricks.com", + }, + { + points: "Meme Magic (50 Points + up to 100 Points)", quest: - "You are! Take a screenshot of this and share it in the 'side-quest' channel on Discord to get 100 points.", + "Craft a meme where a brick plays a role. For extra points, tweet it, tag us and score +5 for each like.", + proof: "Share meme or link to the tweet in the “side-quest” channel.", }, { - points: "200 Points:", - quest: "The rest of the side quests will be released on the 1st of October.", + points: "GIF Magic (100 Points)", + quest: + "Create a branded gif related to Formbricks. Upload it to Giphy. For extra points, tweet it, tag us and score +5 for each like.", + proof: "Share link to Giphy in the “side-quest” channel.", }, { - points: "250 Points:", - quest: "Follow us on Twitter and join us on Discord to be the first to know!", + points: "Design a background (250 Points)", + quest: "Illustrate a captivating background for survey enthusiasts (more infos on Notion).", + proof: "Share the design in the “side-quest” channel.", }, { - points: "Pushmaster Prime | +500 Points + Hoodie:", - quest: "Merge the highest amount of Formbricks PRs in October.", + points: "Transform Animation to CSS (350 Points per background)", + quest: "Animate an existing background to CSS versions (more infos on Notion).", + proof: "Share the animated background.", }, { - points: "Guidance Guru | +500 Points + Hoodie:", - quest: "Most active and helpful in the community helping other contributors.", + points: "Enhance Docs (50-250 Points)", + quest: + "Add a new section to our docs where you see gaps. Follow the current style of documentation incl. code snippets and screenshots. Pls no spam.", + proof: "Open a PR with “docs” in the title", }, { - points: "Buzz Builder Guru | +500 Points + Hoodie:", - quest: "Marketing Genie with great and effective ideas to spread the word about FormTribe", + points: "Starry-eyed Supporter (250 Points)", + quest: "Get five friends to star our repository.", + proof: "Share 5 screenshots of the chats where you asked them and they confirmed + their GitHub names", + }, + { + points: "Bug Hunter (50-250 Points)", + quest: "Find and report any functionality bugs.", + proof: "Open a bug issue in our repository.", + }, + { + points: "Brickify someone famous with AI (200 Points + up to 100 Points)", + quest: + "Find someone whose name would be funny as a play on words with “brick”. Then, with the help of AI, create a brick version of this person like Brick Astley, Brickj Minaj, etc. For extra points, tweet it, tag us and score +5 for each like.", + proof: "Share your art or link to the tweet in the “side-quest” channel.", + }, + { + points: "SEO Sage (50-250 Points)", + quest: "Provide detailed SEO recommendations or improvements for our main website.", + proof: "Share your insights.", + }, + { + points: "Community Connector (50 points each, up to 250 points)", + quest: + "Introduce and onboard new members to the community. Have them join Discord and reply to their automated welcome message with your discord handle (in “say-hi” channel).", + proof: "New member joined and commented with your Discord handle", + }, + { + points: "Feedback Fanatic (50 Points)", + quest: "Fill out our feedback survey after the hackathon with suggestions for improvement.", + proof: "Submit the survey.", + }, + { + points: "Side Quest Babo (500 Points)", + quest: "Complete all side quests.", + proof: "All quests marked as completed.", }, ]; @@ -212,6 +264,155 @@ const FAQ = [ }, ]; +const Leaderboard = [ + { + name: "Piyush", + points: "550", + link: "https://github.com/gupta-piyush19", + }, + { + name: "Suman", + points: "200", + }, + { + name: "Subhdeep", + points: "100", + }, + { + name: "Pratik", + points: "250", + }, + { + name: "Karuppiah", + points: "100", + }, + { + name: "Arth", + points: "100", + }, + { + name: "Neztep", + points: "100", + }, + { + name: "Kelvin Parmar", + points: "200", + }, + { + name: "Naitik Kapadia (Arjun)", + points: "200", + }, + { + name: "Yashhhh", + points: "200", + }, + { + name: "vishleshak", + points: "100", + }, + { + name: "Ashu999", + points: "100", + }, + { + name: "Sachin H", + points: "100", + }, + { + name: "Suraj Jadhav", + points: "100", + }, + { + name: "Vishrut", + points: "250", + }, + { + name: "cataxcab", + points: "100", + }, + { + name: "Eldemarkki", + points: "500", + }, + { + name: "Suyash", + points: "100", + }, + { + name: "Rohan Gupta", + points: "100", + }, + { + name: "Nafees Nazik", + points: "100", + }, + { + name: "monk", + points: "100", + }, + { + name: "Pratik Tiwari (Pratik)", + points: "100", + }, + { + name: "Ardash Malviya", + points: "100", + }, + { + name: "Aditya Deshlahre", + points: "550", + link: "https://github.com/adityadeshlahre", + }, + { + name: "Rutam", + points: "350", + }, + { + name: "Sagnik Sahoo", + points: "100", + }, + { + name: "Prasoon Mahawar", + points: "100", + }, + { + name: "Dushmanta", + points: "100", + }, + { + name: "Arjavv", + points: "100", + }, + { + name: "Ashish Khare", + points: "100", + }, + { + name: "Rohit Mondal", + points: "100", + }, + { + name: "noobcoder", + points: "100", + }, + { + name: "Rayyan Alam (Rayy)", + points: "100", + }, + { + name: "Ayush", + points: "100", + }, + { + name: "Zechariah", + points: "100", + }, + { + name: "Rajarshi Misra", + points: "100", + }, +]; + export default function FormTribeHackathon() { // dark mode fix useEffect(() => { @@ -234,7 +435,7 @@ export default function FormTribeHackathon() { Write code, win a Macbook 🔥

- Let's ship Open Source Typeform in Hacktoberfest + Let's ship Open Source Typeform during Hacktoberfest

@@ -400,6 +601,7 @@ export default function FormTribeHackathon() {

  • 🎉 1 x MacBook Air M2
  • 🎉 3 x Limited FormTribe Premium Hoodie
  • 🎉 10 x Limited FormTribe Premium Shirt
  • +
  • 🎉 10 x 250h for Gitpod
  • 🎉 50 x Sets of Formbricks Stickers
  • @@ -462,40 +664,57 @@ export default function FormTribeHackathon() {
    ))}
    - -
    -
    -

    No issues released yet.

    - - Join Discord to get notified first. - -
    +
    +
    + {/* Side Quests */} -
    +

    🏰 Side Quests: Increase your chances

    While code contributions are what gives the most points, everyone gets to bump up their chance of - winning. Here is a list of side quests you can complete:{" "} + winning. Here is a list of side quests you can complete:

    -
    - {SideQuests.map((quest) => ( -
    -
    -
    -

    - {quest.points} {quest.quest} -

    +
    + + {SideQuests.map((quest) => ( +
    + + +
    +
    +

    + {quest.points}: {quest.quest} +

    +
    +
    + +

    +

    Proof: {quest.proof}

    +

    +
    +
    -
    - ))} + ))} +
    +
    + {/* The Leaderboard */} -
    -
    -

    Not live yet.

    - - Sign up to get notified on kick-off. - +
    +
    +
    User
    +
    Points
    + {Leaderboard.sort((a, b) => parseInt(b.points) - parseInt(a.points)).map((player) => ( + +
    +
    +
    {player.name}
    +
    +
    {player.points} Points
    +
    +
    + ))}
    {/* The Timeline */} diff --git a/apps/formbricks-com/pages/index.tsx b/apps/formbricks-com/pages/index.tsx index 7e3ce15bba..5915a86874 100644 --- a/apps/formbricks-com/pages/index.tsx +++ b/apps/formbricks-com/pages/index.tsx @@ -1,13 +1,12 @@ -import Layout from "@/components/shared/Layout"; -import Hero from "@/components/home/Hero"; -import Features from "@/components/home/Features"; -import Highlights from "@/components/home/Highlights"; -import BreakerCTA from "@/components/shared/BreakerCTA"; -import Steps from "@/components/home/Steps"; -import Pricing from "@/components/shared/Pricing"; -import GitHubSponsorship from "@/components/home/GitHubSponsorship"; -import BestPractices from "@/components/shared/BestPractices"; import Faq from "@/components/home/Faq"; +import Features from "@/components/home/Features"; +import GitHubSponsorship from "@/components/home/GitHubSponsorship"; +import Hero from "@/components/home/Hero"; +import Highlights from "@/components/home/Highlights"; +import Steps from "@/components/home/Steps"; +import BestPractices from "@/components/shared/BestPractices"; +import BreakerCTA from "@/components/shared/BreakerCTA"; +import Layout from "@/components/shared/Layout"; const IndexPage = () => ( ( href="https://app.formbricks.com/auth/signup" inverted /> - + ); diff --git a/apps/formbricks-com/pages/pricing.tsx b/apps/formbricks-com/pages/pricing.tsx new file mode 100644 index 0000000000..64429f3389 --- /dev/null +++ b/apps/formbricks-com/pages/pricing.tsx @@ -0,0 +1,144 @@ +import HeroTitle from "@/components/shared/HeroTitle"; +import Layout from "@/components/shared/Layout"; +import { OpenSourceInfo } from "@/components/shared/OpenSourceInfo"; +import { GetStartedWithPricing } from "@/components/shared/PricingGetStarted"; +import { PricingCalculator } from "../components/shared/PricingCalculator"; +import { PricingTable } from "../components/shared/PricingTable"; + +const inProductSurveys = { + leadRow: { + title: "In-Product Surveys", + free: ( +
    + 5000 tracked users /mo{" "} +
    + ), + paid: "Unlimited", + }, + features: [ + { name: "Unlimited Surveys", free: true, paid: true }, + { name: "Granular Targeting", free: true, paid: true }, + { name: "30+ Templates", free: true, paid: true }, + { name: "API Access", free: true, paid: true }, + { name: "Third-Party Integrations", free: true, paid: true }, + { name: "Unlimited Team Members", free: true, paid: true }, + { name: "Unlimited Responses per Survey", free: true, paid: true }, + { name: "Advanced User Targeting", free: false, paid: true }, + { name: "Multi Language", free: false, paid: true }, + + { + name: "Custom URL for Link Surveys", + free: "10$/mo", + paid: "10$/mo", + addOnText: "Free if you self-host", + }, + { + name: "Remove Formbricks Branding", + free: "10$/mo", + paid: "10$/mo", + addOnText: "Free if you self-host", + }, + ], + endRow: { + title: "In-Product Surveys Pricing", + free: "Free", + paid: ( +
    + Free up to 5000 tracked users/mo, then + $0.005 + / tracked user +
    + ), + }, +}; + +const linkSurveys = { + leadRow: { + title: "Link Surveys", + free: Unlimited, + paid: "Unlimited", + }, + + features: [ + { name: "Unlimited Surveys", free: true, paid: true }, + { name: "Unlimited Responses", free: true, paid: true }, + { name: "Partial Responses", free: true, paid: true }, + { name: "⚙️ URL Shortener", free: true, paid: true }, + { name: "⚙️ Recall Information", free: true, paid: true }, + { name: "⚙️ Hidden Field Questions", free: true, paid: true }, + { name: "⚙️ Time to Complete Metadata", free: true, paid: true }, + { name: "⚙️ File Upload", free: true, paid: true }, + { name: "⚙️ Signature Question", free: true, paid: true }, + { name: "⚙️ Question Grouping", free: true, paid: true }, + { name: "⚙️ Add Media to Questions", free: true, paid: true }, + ], + + endRow: { + title: "Link Surveys Pricing", + free: "Free", + paid: "Free", + }, +}; + +const integrations = { + leadRow: { + title: "Integrations", + free: Unlimited, + paid: "Unlimited", + }, + features: [ + { name: "Webhooks", free: true, paid: true }, + { name: "Zapier", free: true, paid: true }, + { name: "Google Sheets", free: true, paid: true }, + { name: "n8n", free: true, paid: true }, + { name: "Make", free: true, paid: true }, + ], + endRow: { + title: "Integrations Pricing", + free: "Free", + paid: "Free", + }, +}; + +const PricingPage = () => { + return ( + + +
    +
    + + + +
    + + + + +
    + + +
    +
    +
    + ); +}; + +export default PricingPage; diff --git a/apps/web/app/(app)/FormbricksClient.tsx b/apps/web/app/(app)/FormbricksClient.tsx index ebc694e2da..6289105b52 100644 --- a/apps/web/app/(app)/FormbricksClient.tsx +++ b/apps/web/app/(app)/FormbricksClient.tsx @@ -7,7 +7,6 @@ import { useEffect } from "react"; type UsageAttributesUpdaterProps = { numSurveys: number; - totalSubmissions: number; }; export default function FormbricksClient({ session }) { @@ -19,31 +18,23 @@ export default function FormbricksClient({ session }) { }); formbricks.setUserId(session.user.id); formbricks.setEmail(session.user.email); - if (session.user.teams?.length > 0) { - formbricks.setAttribute("Plan", session.user.teams[0].plan); - formbricks.setAttribute("Name", session?.user?.name); - } } }, [session]); return null; } -const updateUsageAttributes = (numSurveys, totalSubmissions) => { +const updateUsageAttributes = (numSurveys) => { if (!formbricksEnabled) return; if (numSurveys >= 3) { formbricks.setAttribute("HasThreeSurveys", "true"); } - - if (totalSubmissions >= 20) { - formbricks.setAttribute("HasTwentySubmissions", "true"); - } }; -export function UsageAttributesUpdater({ numSurveys, totalSubmissions }: UsageAttributesUpdaterProps) { +export function UsageAttributesUpdater({ numSurveys }: UsageAttributesUpdaterProps) { useEffect(() => { - updateUsageAttributes(numSurveys, totalSubmissions); - }, [numSurveys, totalSubmissions]); + updateUsageAttributes(numSurveys); + }, [numSurveys]); return null; } diff --git a/apps/web/app/(app)/PosthogIdentify.tsx b/apps/web/app/(app)/PosthogIdentify.tsx index b022fb4056..dc055535d5 100644 --- a/apps/web/app/(app)/PosthogIdentify.tsx +++ b/apps/web/app/(app)/PosthogIdentify.tsx @@ -12,9 +12,6 @@ export default function PosthogIdentify({ session }: { session: Session }) { useEffect(() => { if (posthogEnabled && session.user && posthog) { posthog.identify(session.user.id); - if (session.user.teams?.length > 0) { - posthog?.group("team", session.user.teams[0].id); - } } }, [session, posthog]); diff --git a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/ActionsAttributesTabs.tsx b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/ActionsAttributesTabs.tsx index 7c21c62163..104a0f59dc 100644 --- a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/ActionsAttributesTabs.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/ActionsAttributesTabs.tsx @@ -22,5 +22,5 @@ export default function ActionsAttributesTabs({ activeId, environmentId }: Actio }, ]; - return ; + return ; } diff --git a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/ActionActivityTab.tsx b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/ActionActivityTab.tsx index c6beed9eaf..54e13b363a 100644 --- a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/ActionActivityTab.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/ActionActivityTab.tsx @@ -1,21 +1,67 @@ +"use client"; + import LoadingSpinner from "@/components/shared/LoadingSpinner"; import { ErrorComponent } from "@formbricks/ui"; import { Label } from "@formbricks/ui"; -import { useEventClass } from "@/lib/eventClasses/eventClasses"; import { convertDateTimeStringShort } from "@formbricks/lib/time"; import { capitalizeFirstLetter } from "@/lib/utils"; import { CodeBracketIcon, CursorArrowRaysIcon, SparklesIcon } from "@heroicons/react/24/solid"; - +import { TActionClass } from "@formbricks/types/v1/actionClasses"; +import { useEffect, useState } from "react"; +import { + getActionCountInLastHourAction, + getActionCountInLast24HoursAction, + getActionCountInLast7DaysAction, + GetActiveInactiveSurveysAction, +} from "./actions"; interface ActivityTabProps { - environmentId: string; - actionClassId: string; + actionClass: TActionClass; } -export default function EventActivityTab({ environmentId, actionClassId }: ActivityTabProps) { - const { eventClass, isLoadingEventClass, isErrorEventClass } = useEventClass(environmentId, actionClassId); +export default function EventActivityTab({ actionClass }: ActivityTabProps) { + // const { eventClass, isLoadingEventClass, isErrorEventClass } = useEventClass(environmentId, actionClass.id); - if (isLoadingEventClass) return ; - if (isErrorEventClass) return ; + const [numEventsLastHour, setNumEventsLastHour] = useState(); + const [numEventsLast24Hours, setNumEventsLast24Hours] = useState(); + const [numEventsLast7Days, setNumEventsLast7Days] = useState(); + const [activeSurveys, setActiveSurveys] = useState(); + const [inactiveSurveys, setInactiveSurveys] = useState(); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + + useEffect(() => { + setLoading(true); + updateState(); + + async function updateState() { + try { + setLoading(true); + const [ + numEventsLastHourData, + numEventsLast24HoursData, + numEventsLast7DaysData, + activeInactiveSurveys, + ] = await Promise.all([ + getActionCountInLastHourAction(actionClass.id), + getActionCountInLast24HoursAction(actionClass.id), + getActionCountInLast7DaysAction(actionClass.id), + GetActiveInactiveSurveysAction(actionClass.id), + ]); + setNumEventsLastHour(numEventsLastHourData); + setNumEventsLast24Hours(numEventsLast24HoursData); + setNumEventsLast7Days(numEventsLast7DaysData); + setActiveSurveys(activeInactiveSurveys.activeSurveys); + setInactiveSurveys(activeInactiveSurveys.inactiveSurveys); + } catch (err) { + setError(err); + } finally { + setLoading(false); + } + } + }, [actionClass.id]); + + if (loading) return ; + if (error) return ; return (
    @@ -24,15 +70,15 @@ export default function EventActivityTab({ environmentId, actionClassId }: Activ
    -

    {eventClass.numEventsLastHour}

    +

    {numEventsLastHour}

    last hour

    -

    {eventClass.numEventsLast24Hours}

    +

    {numEventsLast24Hours}

    last 24 hours

    -

    {eventClass.numEventsLast7Days}

    +

    {numEventsLast7Days}

    last week

    @@ -40,8 +86,8 @@ export default function EventActivityTab({ environmentId, actionClassId }: Activ
    - {eventClass.activeSurveys.length === 0 &&

    -

    } - {eventClass.activeSurveys.map((surveyName) => ( + {activeSurveys?.length === 0 &&

    -

    } + {activeSurveys?.map((surveyName) => (

    {surveyName}

    @@ -49,8 +95,8 @@ export default function EventActivityTab({ environmentId, actionClassId }: Activ
    - {eventClass.inactiveSurveys.length === 0 &&

    -

    } - {eventClass.inactiveSurveys.map((surveyName) => ( + {inactiveSurveys?.length === 0 &&

    -

    } + {inactiveSurveys?.map((surveyName) => (

    {surveyName}

    @@ -61,28 +107,28 @@ export default function EventActivityTab({ environmentId, actionClassId }: Activ

    - {convertDateTimeStringShort(eventClass.createdAt?.toString())} + {convertDateTimeStringShort(actionClass.createdAt?.toString())}

    {" "}

    - {convertDateTimeStringShort(eventClass.updatedAt?.toString())} + {convertDateTimeStringShort(actionClass.updatedAt?.toString())}

    - {eventClass.type === "code" ? ( + {actionClass.type === "code" ? ( - ) : eventClass.type === "noCode" ? ( + ) : actionClass.type === "noCode" ? ( - ) : eventClass.type === "automatic" ? ( + ) : actionClass.type === "automatic" ? ( ) : null}
    -

    {capitalizeFirstLetter(eventClass.type)}

    +

    {capitalizeFirstLetter(actionClass.type)}

    diff --git a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/ActionDetailModal.tsx b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/ActionDetailModal.tsx index 1017545e98..f0362ac33c 100644 --- a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/ActionDetailModal.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/ActionDetailModal.tsx @@ -20,7 +20,7 @@ export default function ActionDetailModal({ const tabs = [ { title: "Activity", - children: , + children: , }, { title: "Settings", diff --git a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/ActionSettingsTab.tsx b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/ActionSettingsTab.tsx index ea4f37db2b..da87f38a60 100644 --- a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/ActionSettingsTab.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/ActionSettingsTab.tsx @@ -9,11 +9,14 @@ import { useState } from "react"; import { useForm } from "react-hook-form"; import { toast } from "react-hot-toast"; import { testURLmatch } from "./testURLmatch"; -import { deleteActionClass, updateActionClass } from "@formbricks/lib/services/actionClass"; import { TActionClassInput, TActionClassNoCodeConfig } from "@formbricks/types/v1/actionClasses"; import { CssSelector } from "@/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/(selectors)/CssSelector"; import { PageUrlSelector } from "@/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/(selectors)/PageUrlSelector"; import { InnerHtmlSelector } from "@/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/(selectors)/InnerHtmlSelector"; +import { + deleteActionClassAction, + updateActionClassAction, +} from "@/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/actions"; interface ActionSettingsTabProps { environmentId: string; @@ -77,10 +80,11 @@ export default function ActionSettingsTab({ environmentId, actionClass, setOpen const filteredNoCodeConfig = filterNoCodeConfig(data.noCodeConfig as NoCodeConfig); const updatedData: TActionClassInput = { ...data, + environmentId, noCodeConfig: filteredNoCodeConfig, type: "noCode", } as TActionClassInput; - await updateActionClass(environmentId, actionClass.id, updatedData); + await updateActionClassAction(environmentId, actionClass.id, updatedData); setOpen(false); router.refresh(); toast.success("Action updated successfully"); @@ -94,7 +98,7 @@ export default function ActionSettingsTab({ environmentId, actionClass, setOpen const handleDeleteAction = async () => { try { setIsDeletingAction(true); - await deleteActionClass(environmentId, actionClass.id); + await deleteActionClassAction(environmentId, actionClass.id); router.refresh(); toast.success("Action deleted successfully"); setOpen(false); diff --git a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/AddNoCodeActionModal.tsx b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/AddNoCodeActionModal.tsx index ff08847f2e..ab39bb7279 100644 --- a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/AddNoCodeActionModal.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/AddNoCodeActionModal.tsx @@ -7,7 +7,6 @@ import { useState } from "react"; import { useForm } from "react-hook-form"; import toast from "react-hot-toast"; import { testURLmatch } from "./testURLmatch"; -import { createActionClass } from "@formbricks/lib/services/actionClass"; import { TActionClassInput, TActionClassNoCodeConfig, @@ -16,6 +15,7 @@ import { import { CssSelector } from "@/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/(selectors)/CssSelector"; import { PageUrlSelector } from "@/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/(selectors)/PageUrlSelector"; import { InnerHtmlSelector } from "@/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/(selectors)/InnerHtmlSelector"; +import { createActionClassAction } from "@/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/actions"; interface AddNoCodeActionModalProps { environmentId: string; @@ -84,7 +84,7 @@ export default function AddNoCodeActionModal({ type: "noCode", } as TActionClassInput; - const newActionClass: TActionClass = await createActionClass(environmentId, updatedData); + const newActionClass: TActionClass = await createActionClassAction(updatedData); if (setActionClassArray) { setActionClassArray((prevActionClassArray: TActionClass[]) => [ ...prevActionClassArray, diff --git a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/actions.ts b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/actions.ts new file mode 100644 index 0000000000..0a82437d09 --- /dev/null +++ b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/actions.ts @@ -0,0 +1,97 @@ +"use server"; + +import { authOptions } from "@/app/api/auth/[...nextauth]/authOptions"; +import { hasUserEnvironmentAccess } from "@formbricks/lib/environment/auth"; +import { createActionClass, deleteActionClass, updateActionClass } from "@formbricks/lib/actionClass/service"; +import { canUserAccessActionClass } from "@formbricks/lib/actionClass/auth"; +import { getServerSession } from "next-auth"; +import { TActionClassInput } from "@formbricks/types/v1/actionClasses"; + +import { + getActionCountInLast24Hours, + getActionCountInLast7Days, + getActionCountInLastHour, +} from "@formbricks/lib/services/actions"; +import { getSurveysByActionClassId } from "@formbricks/lib/survey/service"; +import { AuthorizationError } from "@formbricks/types/v1/errors"; + +export async function deleteActionClassAction(environmentId, actionClassId: string) { + const session = await getServerSession(authOptions); + if (!session) throw new AuthorizationError("Not authorized"); + + const isAuthorized = await canUserAccessActionClass(session.user.id, actionClassId); + if (!isAuthorized) throw new AuthorizationError("Not authorized"); + + await deleteActionClass(environmentId, actionClassId); +} + +export async function updateActionClassAction( + environmentId: string, + actionClassId: string, + updatedAction: Partial +) { + const session = await getServerSession(authOptions); + if (!session) throw new AuthorizationError("Not authorized"); + + const isAuthorized = await canUserAccessActionClass(session.user.id, actionClassId); + if (!isAuthorized) throw new AuthorizationError("Not authorized"); + + return await updateActionClass(environmentId, actionClassId, updatedAction); +} + +export async function createActionClassAction(action: TActionClassInput) { + const session = await getServerSession(authOptions); + if (!session) throw new AuthorizationError("Not authorized"); + + const isAuthorized = await hasUserEnvironmentAccess(session.user.id, action.environmentId); + if (!isAuthorized) throw new AuthorizationError("Not authorized"); + + return await createActionClass(action.environmentId, action); +} + +export const getActionCountInLastHourAction = async (actionClassId: string) => { + const session = await getServerSession(authOptions); + if (!session) throw new AuthorizationError("Not authorized"); + + const isAuthorized = await canUserAccessActionClass(session.user.id, actionClassId); + if (!isAuthorized) throw new AuthorizationError("Not authorized"); + + return await getActionCountInLastHour(actionClassId); +}; + +export const getActionCountInLast24HoursAction = async (actionClassId: string) => { + const session = await getServerSession(authOptions); + if (!session) throw new AuthorizationError("Not authorized"); + + const isAuthorized = await canUserAccessActionClass(session.user.id, actionClassId); + if (!isAuthorized) throw new AuthorizationError("Not authorized"); + + return await getActionCountInLast24Hours(actionClassId); +}; + +export const getActionCountInLast7DaysAction = async (actionClassId: string) => { + const session = await getServerSession(authOptions); + if (!session) throw new AuthorizationError("Not authorized"); + + const isAuthorized = await canUserAccessActionClass(session.user.id, actionClassId); + if (!isAuthorized) throw new AuthorizationError("Not authorized"); + + return await getActionCountInLast7Days(actionClassId); +}; + +export const GetActiveInactiveSurveysAction = async ( + actionClassId: string +): Promise<{ activeSurveys: string[]; inactiveSurveys: string[] }> => { + const session = await getServerSession(authOptions); + if (!session) throw new AuthorizationError("Not authorized"); + + const isAuthorized = await canUserAccessActionClass(session.user.id, actionClassId); + if (!isAuthorized) throw new AuthorizationError("Not authorized"); + + const surveys = await getSurveysByActionClassId(actionClassId); + const response = { + activeSurveys: surveys.filter((s) => s.status === "inProgress").map((survey) => survey.name), + inactiveSurveys: surveys.filter((s) => s.status !== "inProgress").map((survey) => survey.name), + }; + return response; +}; diff --git a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/page.tsx b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/page.tsx index 27dbd8caf6..2e39e09f4a 100644 --- a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/page.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/page.tsx @@ -4,7 +4,7 @@ import ActionClassesTable from "@/app/(app)/environments/[environmentId]/(action import ActionClassDataRow from "@/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/ActionRowData"; import ActionTableHeading from "@/app/(app)/environments/[environmentId]/(actionsAndAttributes)/actions/ActionTableHeading"; import { REVALIDATION_INTERVAL } from "@formbricks/lib/constants"; -import { getActionClasses } from "@formbricks/lib/services/actionClass"; +import { getActionClasses } from "@formbricks/lib/actionClass/service"; import { Metadata } from "next"; export const metadata: Metadata = { diff --git a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/AttributeActivityTab.tsx b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/AttributeActivityTab.tsx index 0b66b3d820..54eb7d067c 100644 --- a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/AttributeActivityTab.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/AttributeActivityTab.tsx @@ -1,31 +1,53 @@ +"use client"; + +import { GetActiveInactiveSurveysAction } from "@/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/actions"; import LoadingSpinner from "@/components/shared/LoadingSpinner"; -import { useAttributeClass } from "@/lib/attributeClasses/attributeClasses"; import { capitalizeFirstLetter } from "@/lib/utils"; import { convertDateTimeStringShort } from "@formbricks/lib/time"; +import { TAttributeClass } from "@formbricks/types/v1/attributeClasses"; import { ErrorComponent, Label } from "@formbricks/ui"; import { TagIcon } from "@heroicons/react/24/solid"; +import { useEffect, useState } from "react"; interface EventActivityTabProps { - attributeClassId: string; - environmentId: string; + attributeClass: TAttributeClass; } -export default function AttributeActivityTab({ environmentId, attributeClassId }: EventActivityTabProps) { - const { attributeClass, isLoadingAttributeClass, isErrorAttributeClass } = useAttributeClass( - environmentId, - attributeClassId - ); +export default function AttributeActivityTab({ attributeClass }: EventActivityTabProps) { + const [activeSurveys, setActiveSurveys] = useState(); + const [inactiveSurveys, setInactiveSurveys] = useState(); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); - if (isLoadingAttributeClass) return ; - if (isErrorAttributeClass) return ; + useEffect(() => { + setLoading(true); + + getSurveys(); + + async function getSurveys() { + try { + setLoading(true); + const activeInactive = await GetActiveInactiveSurveysAction(attributeClass.id); + setActiveSurveys(activeInactive.activeSurveys); + setInactiveSurveys(activeInactive.inactiveSurveys); + } catch (err) { + setError(err); + } finally { + setLoading(false); + } + } + }, [attributeClass.id]); + + if (loading) return ; + if (error) return ; return (
    - {attributeClass.activeSurveys.length === 0 &&

    -

    } - {attributeClass.activeSurveys.map((surveyName) => ( + {activeSurveys?.length === 0 &&

    -

    } + {activeSurveys?.map((surveyName) => (

    {surveyName}

    @@ -33,8 +55,8 @@ export default function AttributeActivityTab({ environmentId, attributeClassId }
    - {attributeClass.inactiveSurveys.length === 0 &&

    -

    } - {attributeClass.inactiveSurveys.map((surveyName) => ( + {inactiveSurveys?.length === 0 &&

    -

    } + {inactiveSurveys?.map((surveyName) => (

    {surveyName}

    diff --git a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/AttributeClassesTable.tsx b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/AttributeClassesTable.tsx index cfce41c9d9..f76eecf980 100644 --- a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/AttributeClassesTable.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/AttributeClassesTable.tsx @@ -8,11 +8,9 @@ import { useMemo } from "react"; import { TAttributeClass } from "@formbricks/types/v1/attributeClasses"; export default function AttributeClassesTable({ - environmentId, attributeClasses, children: [TableHeading, howToAddAttributeButton, attributeRows], }: { - environmentId: string; attributeClasses: TAttributeClass[]; children: [JSX.Element, JSX.Element, JSX.Element[]]; }) { @@ -69,7 +67,6 @@ export default function AttributeClassesTable({ ))}
    void; - attributeClass: AttributeClass; + attributeClass: TAttributeClass; } -export default function AttributeDetailModal({ - environmentId, - open, - setOpen, - attributeClass, -}: AttributeDetailModalProps) { +export default function AttributeDetailModal({ open, setOpen, attributeClass }: AttributeDetailModalProps) { const tabs = [ { title: "Activity", - children: , + children: , }, { title: "Settings", diff --git a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/actions.ts b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/actions.ts new file mode 100644 index 0000000000..54bdcabb3e --- /dev/null +++ b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/actions.ts @@ -0,0 +1,14 @@ +"use server"; + +import { getSurveysByAttributeClassId } from "@formbricks/lib/survey/service"; + +export const GetActiveInactiveSurveysAction = async ( + attributeClassId: string +): Promise<{ activeSurveys: string[]; inactiveSurveys: string[] }> => { + const surveys = await getSurveysByAttributeClassId(attributeClassId); + const response = { + activeSurveys: surveys.filter((s) => s.status === "inProgress").map((survey) => survey.name), + inactiveSurveys: surveys.filter((s) => s.status !== "inProgress").map((survey) => survey.name), + }; + return response; +}; diff --git a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/page.tsx b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/page.tsx index 37cea27263..6a37ff53bf 100644 --- a/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/page.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/(actionsAndAttributes)/attributes/page.tsx @@ -14,9 +14,10 @@ export const metadata: Metadata = { export default async function AttributesPage({ params }) { let attributeClasses = await getAttributeClasses(params.environmentId); + return ( <> - + diff --git a/apps/web/app/(app)/environments/[environmentId]/AddProductModal.tsx b/apps/web/app/(app)/environments/[environmentId]/AddProductModal.tsx index 2548948f04..2a0dab6026 100644 --- a/apps/web/app/(app)/environments/[environmentId]/AddProductModal.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/AddProductModal.tsx @@ -1,7 +1,7 @@ "use client"; +import { createProductAction } from "@/app/(app)/environments/[environmentId]/actions"; import Modal from "@/components/shared/Modal"; -import { createProduct } from "@/lib/products/products"; import { Button, Input, Label } from "@formbricks/ui"; import { PlusCircleIcon } from "@heroicons/react/24/outline"; import { useRouter } from "next/navigation"; @@ -19,9 +19,9 @@ export default function AddProductModal({ environmentId, open, setOpen }: AddPro const [loading, setLoading] = useState(false); const { register, handleSubmit } = useForm(); - const submitProduct = async (data) => { + const submitProduct = async (data: { name: string }) => { setLoading(true); - const newEnv = await createProduct(environmentId, data); + const newEnv = await createProductAction(environmentId, data.name); router.push(`/environments/${newEnv.id}/`); setOpen(false); setLoading(false); diff --git a/apps/web/app/(app)/environments/[environmentId]/EnvironmentsNavbar.tsx b/apps/web/app/(app)/environments/[environmentId]/EnvironmentsNavbar.tsx index 701c29c1de..8e5296e288 100644 --- a/apps/web/app/(app)/environments/[environmentId]/EnvironmentsNavbar.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/EnvironmentsNavbar.tsx @@ -1,7 +1,7 @@ export const revalidate = REVALIDATION_INTERVAL; import Navigation from "@/app/(app)/environments/[environmentId]/Navigation"; -import { REVALIDATION_INTERVAL } from "@formbricks/lib/constants"; +import { IS_FORMBRICKS_CLOUD, REVALIDATION_INTERVAL } from "@formbricks/lib/constants"; import { getEnvironment, getEnvironments } from "@formbricks/lib/services/environment"; import { getProducts } from "@formbricks/lib/services/product"; import { getTeamByEnvironmentId, getTeamsByUserId } from "@formbricks/lib/services/team"; @@ -11,6 +11,7 @@ import type { Session } from "next-auth"; interface EnvironmentsNavbarProps { environmentId: string; session: Session; + isFormbricksCloud: boolean; } export default async function EnvironmentsNavbar({ environmentId, session }: EnvironmentsNavbarProps) { @@ -41,6 +42,7 @@ export default async function EnvironmentsNavbar({ environmentId, session }: Env products={products} environments={environments} session={session} + isFormbricksCloud={IS_FORMBRICKS_CLOUD} /> ); } diff --git a/apps/web/app/(app)/environments/[environmentId]/Navigation.tsx b/apps/web/app/(app)/environments/[environmentId]/Navigation.tsx index c2790c8e35..00a054f784 100644 --- a/apps/web/app/(app)/environments/[environmentId]/Navigation.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/Navigation.tsx @@ -21,7 +21,6 @@ import { formbricksLogout } from "@/lib/formbricks"; import { capitalizeFirstLetter, truncate } from "@/lib/utils"; import formbricks from "@formbricks/js"; import { cn } from "@formbricks/lib/cn"; -import { IS_FORMBRICKS_CLOUD } from "@formbricks/lib/constants"; import { TEnvironment } from "@formbricks/types/v1/environment"; import { TProduct } from "@formbricks/types/v1/product"; import { TTeam } from "@formbricks/types/v1/teams"; @@ -71,6 +70,7 @@ interface NavigationProps { team: TTeam; products: TProduct[]; environments: TEnvironment[]; + isFormbricksCloud: boolean; } export default function Navigation({ @@ -80,6 +80,7 @@ export default function Navigation({ session, products, environments, + isFormbricksCloud, }: NavigationProps) { const router = useRouter(); const pathname = usePathname(); @@ -171,7 +172,7 @@ export default function Navigation({ icon: CreditCardIcon, label: "Billing & Plan", href: `/environments/${environment.id}/settings/billing`, - hidden: !IS_FORMBRICKS_CLOUD, + hidden: !isFormbricksCloud, }, ], }, @@ -453,7 +454,7 @@ export default function Navigation({ ))} - {IS_FORMBRICKS_CLOUD && ( + {isFormbricksCloud && (
    - +
    ); } diff --git a/apps/web/app/(app)/environments/[environmentId]/people/[personId]/(responseSection)/ResponsesFeed.tsx b/apps/web/app/(app)/environments/[environmentId]/people/[personId]/(responseSection)/ResponsesFeed.tsx index 9914eb783d..2e73a97846 100644 --- a/apps/web/app/(app)/environments/[environmentId]/people/[personId]/(responseSection)/ResponsesFeed.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/people/[personId]/(responseSection)/ResponsesFeed.tsx @@ -3,20 +3,22 @@ import EmptySpaceFiller from "@/components/shared/EmptySpaceFiller"; import SurveyStatusIndicator from "@/components/shared/SurveyStatusIndicator"; import { TResponseWithSurvey } from "@formbricks/types/v1/responses"; import Link from "next/link"; +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@formbricks/ui"; +import { TEnvironment } from "@formbricks/types/v1/environment"; export default function ResponseFeed({ responses, sortByDate, - environmentId, + environment, }: { responses: TResponseWithSurvey[]; sortByDate: boolean; - environmentId: string; + environment: TEnvironment; }) { return ( <> {responses.length === 0 ? ( - + ) : (
    {responses @@ -53,15 +55,16 @@ export default function ResponseFeed({
    + href={`/environments/${environment.id}/surveys/${response.survey.id}/summary`}> {response.survey.name}
    +
    {response.survey.questions.map((question) => (
    @@ -74,6 +77,18 @@ export default function ResponseFeed({
    ))}
    +
    + + + +

    {response.singleUseId}

    +
    + +

    Single Use Id

    +
    +
    +
    +
    diff --git a/apps/web/app/(app)/environments/[environmentId]/people/[personId]/page.tsx b/apps/web/app/(app)/environments/[environmentId]/people/[personId]/page.tsx index 02fd8bc4db..9bb2fbf8fd 100644 --- a/apps/web/app/(app)/environments/[environmentId]/people/[personId]/page.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/people/[personId]/page.tsx @@ -5,8 +5,13 @@ import AttributesSection from "@/app/(app)/environments/[environmentId]/people/[ import ResponseSection from "@/app/(app)/environments/[environmentId]/people/[personId]/(responseSection)/ResponseSection"; import HeadingSection from "@/app/(app)/environments/[environmentId]/people/[personId]/HeadingSection"; import { REVALIDATION_INTERVAL } from "@formbricks/lib/constants"; +import { getEnvironment } from "@formbricks/lib/services/environment"; export default async function PersonPage({ params }) { + const environment = await getEnvironment(params.environmentId); + if (!environment) { + throw new Error("Environment not found"); + } return (
    @@ -15,7 +20,7 @@ export default async function PersonPage({ params }) {
    - +
    diff --git a/apps/web/app/(app)/environments/[environmentId]/people/page.tsx b/apps/web/app/(app)/environments/[environmentId]/people/page.tsx index bcd734c513..18e234457d 100644 --- a/apps/web/app/(app)/environments/[environmentId]/people/page.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/people/page.tsx @@ -3,6 +3,7 @@ export const revalidate = REVALIDATION_INTERVAL; import EmptySpaceFiller from "@/components/shared/EmptySpaceFiller"; import { truncateMiddle } from "@/lib/utils"; import { PEOPLE_PER_PAGE, REVALIDATION_INTERVAL } from "@formbricks/lib/constants"; +import { getEnvironment } from "@formbricks/lib/services/environment"; import { getPeople, getPeopleCount } from "@formbricks/lib/services/person"; import { TPerson } from "@formbricks/types/v1/people"; import { Pagination, PersonAvatar } from "@formbricks/ui"; @@ -19,7 +20,13 @@ export default async function PeoplePage({ searchParams: { [key: string]: string | string[] | undefined }; }) { const pageNumber = searchParams.page ? parseInt(searchParams.page as string) : 1; - const totalPeople = await getPeopleCount(params.environmentId); + const [environment, totalPeople] = await Promise.all([ + getEnvironment(params.environmentId), + getPeopleCount(params.environmentId), + ]); + if (!environment) { + throw new Error("Environment not found"); + } const maxPageNumber = Math.ceil(totalPeople / PEOPLE_PER_PAGE); let hidePagination = false; @@ -37,7 +44,7 @@ export default async function PeoplePage({ {people.length === 0 ? ( ) : ( diff --git a/apps/web/app/(app)/environments/[environmentId]/settings/SettingsNavbar.tsx b/apps/web/app/(app)/environments/[environmentId]/settings/SettingsNavbar.tsx index 82fd341905..de2e6975ca 100644 --- a/apps/web/app/(app)/environments/[environmentId]/settings/SettingsNavbar.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/settings/SettingsNavbar.tsx @@ -1,9 +1,8 @@ "use client"; -import { useProduct } from "@/lib/products/products"; -import { useTeam } from "@/lib/teams/teams"; import { truncate } from "@/lib/utils"; -import { IS_FORMBRICKS_CLOUD } from "@formbricks/lib/constants"; +import { TProduct } from "@formbricks/types/v1/product"; +import { TTeam } from "@formbricks/types/v1/teams"; import { Popover, PopoverContent, PopoverTrigger } from "@formbricks/ui"; import { ChevronDownIcon } from "@heroicons/react/20/solid"; import { @@ -25,10 +24,18 @@ import Link from "next/link"; import { usePathname } from "next/navigation"; import { useMemo, useState } from "react"; -export default function SettingsNavbar({ environmentId }: { environmentId: string }) { +export default function SettingsNavbar({ + environmentId, + isFormbricksCloud, + team, + product, +}: { + environmentId: string; + isFormbricksCloud: boolean; + team: TTeam; + product: TProduct; +}) { const pathname = usePathname(); - const { team } = useTeam(environmentId); - const { product } = useProduct(environmentId); const [mobileNavMenuOpen, setMobileNavMenuOpen] = useState(false); interface NavigationLink { @@ -113,7 +120,7 @@ export default function SettingsNavbar({ environmentId }: { environmentId: strin name: "Billing & Plan", href: `/environments/${environmentId}/settings/billing`, icon: CreditCardIcon, - hidden: !IS_FORMBRICKS_CLOUD, + hidden: !isFormbricksCloud, current: pathname?.includes("/billing"), }, ], @@ -152,21 +159,21 @@ export default function SettingsNavbar({ environmentId }: { environmentId: strin href: "https://formbricks.com/gdpr", icon: LinkIcon, target: "_blank", - hidden: !IS_FORMBRICKS_CLOUD, + hidden: !isFormbricksCloud, }, { name: "Privacy", href: "https://formbricks.com/privacy", icon: LinkIcon, target: "_blank", - hidden: !IS_FORMBRICKS_CLOUD, + hidden: !isFormbricksCloud, }, { name: "Terms", href: "https://formbricks.com/terms", icon: LinkIcon, target: "_blank", - hidden: !IS_FORMBRICKS_CLOUD, + hidden: !isFormbricksCloud, }, { name: "License", @@ -178,7 +185,7 @@ export default function SettingsNavbar({ environmentId }: { environmentId: strin ], }, ], - [environmentId, pathname] + [environmentId, isFormbricksCloud, pathname] ); if (!navigation) return null; diff --git a/apps/web/app/(app)/environments/[environmentId]/settings/api-keys/ApiKeyList.tsx b/apps/web/app/(app)/environments/[environmentId]/settings/api-keys/ApiKeyList.tsx index 1ad90e1cd5..0ab082d63c 100644 --- a/apps/web/app/(app)/environments/[environmentId]/settings/api-keys/ApiKeyList.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/settings/api-keys/ApiKeyList.tsx @@ -1,6 +1,6 @@ import EditApiKeys from "./EditApiKeys"; import { getProductByEnvironmentId } from "@formbricks/lib/services/product"; -import { getApiKeys } from "@formbricks/lib/services/apiKey"; +import { getApiKeys } from "@formbricks/lib/apiKey/service"; import { getEnvironments } from "@formbricks/lib/services/environment"; export default async function ApiKeyList({ diff --git a/apps/web/app/(app)/environments/[environmentId]/settings/api-keys/EditApiKeys.tsx b/apps/web/app/(app)/environments/[environmentId]/settings/api-keys/EditApiKeys.tsx index c8fd9f4670..1a4fbd04d7 100644 --- a/apps/web/app/(app)/environments/[environmentId]/settings/api-keys/EditApiKeys.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/settings/api-keys/EditApiKeys.tsx @@ -34,19 +34,29 @@ export default function EditAPIKeys({ }; const handleDeleteKey = async () => { - await deleteApiKeyAction(activeKey.id); - const updatedApiKeys = apiKeysLocal?.filter((apiKey) => apiKey.id !== activeKey.id) || []; - setApiKeysLocal(updatedApiKeys); - setOpenDeleteKeyModal(false); - toast.success("API Key deleted"); + try { + await deleteApiKeyAction(activeKey.id); + const updatedApiKeys = apiKeysLocal?.filter((apiKey) => apiKey.id !== activeKey.id) || []; + setApiKeysLocal(updatedApiKeys); + toast.success("API Key deleted"); + } catch (e) { + toast.error("Unable to delete API Key"); + } finally { + setOpenDeleteKeyModal(false); + } }; const handleAddAPIKey = async (data) => { - const apiKey = await createApiKeyAction(environmentTypeId, { label: data.label }); - const updatedApiKeys = [...apiKeysLocal!, apiKey]; - setApiKeysLocal(updatedApiKeys); - setOpenAddAPIKeyModal(false); - toast.success("API key created"); + try { + const apiKey = await createApiKeyAction(environmentTypeId, { label: data.label }); + const updatedApiKeys = [...apiKeysLocal!, apiKey]; + setApiKeysLocal(updatedApiKeys); + toast.success("API key created"); + } catch (e) { + toast.error("Unable to create API Key"); + } finally { + setOpenAddAPIKeyModal(false); + } }; return ( diff --git a/apps/web/app/(app)/environments/[environmentId]/settings/api-keys/actions.ts b/apps/web/app/(app)/environments/[environmentId]/settings/api-keys/actions.ts index 3220686f37..1db54a5815 100644 --- a/apps/web/app/(app)/environments/[environmentId]/settings/api-keys/actions.ts +++ b/apps/web/app/(app)/environments/[environmentId]/settings/api-keys/actions.ts @@ -1,11 +1,28 @@ "use server"; -import { deleteApiKey, createApiKey } from "@formbricks/lib/services/apiKey"; +import { authOptions } from "@/app/api/auth/[...nextauth]/authOptions"; +import { hasUserEnvironmentAccess } from "@formbricks/lib/environment/auth"; +import { deleteApiKey, createApiKey } from "@formbricks/lib/apiKey/service"; +import { canUserAccessApiKey } from "@formbricks/lib/apiKey/auth"; import { TApiKeyCreateInput } from "@formbricks/types/v1/apiKeys"; +import { getServerSession } from "next-auth"; +import { AuthorizationError } from "@formbricks/types/v1/errors"; export async function deleteApiKeyAction(id: string) { + const session = await getServerSession(authOptions); + if (!session) throw new AuthorizationError("Not authorized"); + + const isAuthorized = await canUserAccessApiKey(session.user.id, id); + if (!isAuthorized) throw new AuthorizationError("Not authorized"); + return await deleteApiKey(id); } export async function createApiKeyAction(environmentId: string, apiKeyData: TApiKeyCreateInput) { + const session = await getServerSession(authOptions); + if (!session) throw new AuthorizationError("Not authorized"); + + const isAuthorized = await hasUserEnvironmentAccess(session.user.id, environmentId); + if (!isAuthorized) throw new AuthorizationError("Not authorized"); + return await createApiKey(environmentId, apiKeyData); } diff --git a/apps/web/app/(app)/environments/[environmentId]/settings/billing/page.tsx b/apps/web/app/(app)/environments/[environmentId]/settings/billing/page.tsx index d2d21c1c9e..d71594bf91 100644 --- a/apps/web/app/(app)/environments/[environmentId]/settings/billing/page.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/settings/billing/page.tsx @@ -1,6 +1,7 @@ export const revalidate = REVALIDATION_INTERVAL; -import { IS_FORMBRICKS_CLOUD, REVALIDATION_INTERVAL } from "@formbricks/lib/constants"; +import { REVALIDATION_INTERVAL } from "@formbricks/lib/constants"; +import { IS_FORMBRICKS_CLOUD } from "@formbricks/lib/constants"; import { authOptions } from "@/app/api/auth/[...nextauth]/authOptions"; import { getTeamByEnvironmentId } from "@formbricks/lib/services/team"; diff --git a/apps/web/app/(app)/environments/[environmentId]/settings/layout.tsx b/apps/web/app/(app)/environments/[environmentId]/settings/layout.tsx index d990621ed0..08561f7430 100644 --- a/apps/web/app/(app)/environments/[environmentId]/settings/layout.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/settings/layout.tsx @@ -1,15 +1,33 @@ import { Metadata } from "next"; import SettingsNavbar from "./SettingsNavbar"; +import { IS_FORMBRICKS_CLOUD } from "@formbricks/lib/constants"; +import { getTeamByEnvironmentId } from "@formbricks/lib/services/team"; +import { getProductByEnvironmentId } from "@formbricks/lib/services/product"; export const metadata: Metadata = { title: "Settings", }; -export default function SettingsLayout({ children, params }) { +export default async function SettingsLayout({ children, params }) { + const [team, product] = await Promise.all([ + getTeamByEnvironmentId(params.environmentId), + getProductByEnvironmentId(params.environmentId), + ]); + if (!team) { + throw new Error("Team not found"); + } + if (!product) { + throw new Error("Product not found"); + } return ( <>
    - +
    {children}
    diff --git a/apps/web/app/(app)/environments/[environmentId]/settings/lookandfeel/EditHighlightBorder.tsx b/apps/web/app/(app)/environments/[environmentId]/settings/lookandfeel/EditHighlightBorder.tsx index 093d950c81..71d68b838c 100644 --- a/apps/web/app/(app)/environments/[environmentId]/settings/lookandfeel/EditHighlightBorder.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/settings/lookandfeel/EditHighlightBorder.tsx @@ -1,7 +1,6 @@ "use client"; import { cn } from "@formbricks/lib/cn"; -import { DEFAULT_BRAND_COLOR } from "@formbricks/lib/constants"; import { TProduct } from "@formbricks/types/v1/product"; import { Button, ColorPicker, Label, Switch } from "@formbricks/ui"; import { useState } from "react"; @@ -10,11 +9,12 @@ import { updateProductAction } from "./actions"; interface EditHighlightBorderProps { product: TProduct; + defaultBrandColor: string; } -export const EditHighlightBorder = ({ product }: EditHighlightBorderProps) => { +export const EditHighlightBorder = ({ product, defaultBrandColor }: EditHighlightBorderProps) => { const [showHighlightBorder, setShowHighlightBorder] = useState(product.highlightBorderColor ? true : false); - const [color, setColor] = useState(product.highlightBorderColor || DEFAULT_BRAND_COLOR); + const [color, setColor] = useState(product.highlightBorderColor || defaultBrandColor); const [updatingBorder, setUpdatingBorder] = useState(false); const handleUpdateHighlightBorder = async () => { @@ -32,7 +32,7 @@ export const EditHighlightBorder = ({ product }: EditHighlightBorderProps) => { const handleSwitch = (checked: boolean) => { if (checked) { if (!color) { - setColor(DEFAULT_BRAND_COLOR); + setColor(defaultBrandColor); setShowHighlightBorder(true); } else { setShowHighlightBorder(true); diff --git a/apps/web/app/(app)/environments/[environmentId]/settings/lookandfeel/page.tsx b/apps/web/app/(app)/environments/[environmentId]/settings/lookandfeel/page.tsx index f1ce4391ef..8c725ae937 100644 --- a/apps/web/app/(app)/environments/[environmentId]/settings/lookandfeel/page.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/settings/lookandfeel/page.tsx @@ -8,6 +8,7 @@ import { EditFormbricksSignature } from "./EditSignature"; import { EditBrandColor } from "./EditBrandColor"; import { EditPlacement } from "./EditPlacement"; import { EditHighlightBorder } from "./EditHighlightBorder"; +import { DEFAULT_BRAND_COLOR } from "@formbricks/lib/constants"; export default async function ProfileSettingsPage({ params }: { params: { environmentId: string } }) { const product = await getProductByEnvironmentId(params.environmentId); @@ -29,7 +30,7 @@ export default async function ProfileSettingsPage({ params }: { params: { enviro noPadding title="Highlight Border" description="Make sure your users notice the survey you display"> - + Create New Team - {env.NEXT_PUBLIC_INVITE_DISABLED !== "1" && isAdminOrOwner && ( + {!isInviteDisabled && isAdminOrOwner && (
    diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponseTimeline.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponseTimeline.tsx index 989b380312..8fec366144 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponseTimeline.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponseTimeline.tsx @@ -6,19 +6,23 @@ import { createId } from "@paralleldrive/cuid2"; import { useMemo } from "react"; import SingleResponse from "./SingleResponse"; import EmptyInAppSurveys from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/components/EmptyInAppSurveys"; +import { TEnvironment } from "@formbricks/types/v1/environment"; +import { TTag } from "@formbricks/types/v1/tags"; interface ResponseTimelineProps { - environmentId: string; + environment: TEnvironment; surveyId: string; responses: TResponse[]; survey: TSurvey; + environmentTags: TTag[]; } export default function ResponseTimeline({ - environmentId, + environment, surveyId, responses, survey, + environmentTags, }: ResponseTimelineProps) { const matchQandA = useMemo(() => { if (survey && responses) { @@ -67,11 +71,13 @@ export default function ResponseTimeline({ return (
    - {survey.type === "web" && responses.length === 0 && } + {survey.type === "web" && responses.length === 0 && ( + + )} {survey.type !== "web" && responses.length === 0 ? ( ) : ( @@ -82,7 +88,8 @@ export default function ResponseTimeline({ key={updatedResponse.id} data={updatedResponse} surveyId={surveyId} - environmentId={environmentId} + environmentId={environment.id} + environmentTags={environmentTags} /> ); })} diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/SingleResponse.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/SingleResponse.tsx index dd52c735b9..402a2ce596 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/SingleResponse.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/SingleResponse.tsx @@ -1,7 +1,6 @@ "use client"; import DeleteDialog from "@/components/shared/DeleteDialog"; -import { deleteSubmission } from "@/lib/responses/responses"; import { truncate } from "@/lib/utils"; import { timeSince } from "@formbricks/lib/time"; import { QuestionType } from "@formbricks/types/questions"; @@ -17,6 +16,8 @@ import toast from "react-hot-toast"; import ResponseNote from "./ResponseNote"; import ResponseTagsWrapper from "./ResponseTagsWrapper"; import { RatingResponse } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/components/RatingResponse"; +import { deleteResponseAction } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/actions"; +import { TTag } from "@formbricks/types/v1/tags"; export interface OpenTextSummaryProps { environmentId: string; @@ -31,6 +32,7 @@ export interface OpenTextSummaryProps { range?: number; }[]; }; + environmentTags: TTag[]; } function findEmail(person) { @@ -59,7 +61,12 @@ function TooltipRenderer(props: TooltipRendererProps) { return <>{children}; } -export default function SingleResponse({ data, environmentId, surveyId }: OpenTextSummaryProps) { +export default function SingleResponse({ + data, + environmentId, + surveyId, + environmentTags, +}: OpenTextSummaryProps) { const router = useRouter(); const email = data.person && findEmail(data.person); const displayIdentifier = email || (data.person && truncate(data.person.id, 16)) || null; @@ -69,9 +76,9 @@ export default function SingleResponse({ data, environmentId, surveyId }: OpenTe const handleDeleteSubmission = async () => { setIsDeleting(true); - const deleteResponse = await deleteSubmission(environmentId, data?.surveyId, data?.id); + const deleteResponseStatus = await deleteResponseAction(data?.id); router.refresh(); - if (deleteResponse?.id?.length > 0) toast.success("Submission deleted successfully."); + if (deleteResponseStatus) toast.success("Submission deleted successfully."); setDeleteDialogOpen(false); setIsDeleting(false); }; @@ -140,6 +147,11 @@ export default function SingleResponse({ data, environmentId, surveyId }: OpenTe )}
    + {data.singleUseId && ( + + {data.singleUseId} + + )} {data.finished && ( Completed @@ -182,10 +194,10 @@ export default function SingleResponse({ data, environmentId, surveyId }: OpenTe ({ tagId: tag.id, tagName: tag.name }))} key={data.tags.map((tag) => tag.id).join("-")} + environmentTags={environmentTags} /> ); diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/CTASummary.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/CTASummary.tsx index 819369a076..84f9a3dde1 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/CTASummary.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/CTASummary.tsx @@ -1,8 +1,10 @@ +import Headline from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/Headline"; import type { QuestionSummary } from "@formbricks/types/responses"; import { TSurveyCTAQuestion } from "@formbricks/types/v1/surveys"; import { ProgressBar } from "@formbricks/ui"; import { InboxStackIcon } from "@heroicons/react/24/solid"; import { useMemo } from "react"; +import { questionTypes } from "@/lib/questions"; interface CTASummaryProps { questionSummary: QuestionSummary; @@ -14,6 +16,8 @@ interface ChoiceResult { } export default function CTASummary({ questionSummary }: CTASummaryProps) { + const questionTypeInfo = questionTypes.find((type) => type.id === questionSummary.question.type); + const ctr: ChoiceResult = useMemo(() => { const clickedAbs = questionSummary.responses.filter((response) => response.value === "clicked").length; const count = questionSummary.responses.length; @@ -27,13 +31,13 @@ export default function CTASummary({ questionSummary }: CTASummaryProps) { return (
    -
    -

    - {questionSummary.question.headline} -

    -
    + +
    -
    Call-to-Action
    +
    + {questionTypeInfo && } + {questionTypeInfo ? questionTypeInfo.label : "Unknown Question Type"} +
    {ctr.count} responses diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/ConsentSummary.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/ConsentSummary.tsx index b5d5a68d7e..7440113486 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/ConsentSummary.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/ConsentSummary.tsx @@ -3,6 +3,8 @@ import { ProgressBar } from "@formbricks/ui"; import { InboxStackIcon } from "@heroicons/react/24/solid"; import { useMemo } from "react"; import { TSurveyConsentQuestion } from "@formbricks/types/v1/surveys"; +import { questionTypes } from "@/lib/questions"; +import Headline from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/Headline"; interface ConsentSummaryProps { questionSummary: QuestionSummary; @@ -17,6 +19,8 @@ interface ChoiceResult { } export default function ConsentSummary({ questionSummary }: ConsentSummaryProps) { + const questionTypeInfo = questionTypes.find((type) => type.id === questionSummary.question.type); + const ctr: ChoiceResult = useMemo(() => { const total = questionSummary.responses.length; const clickedAbs = questionSummary.responses.filter((response) => response.value !== "dismissed").length; @@ -35,13 +39,12 @@ export default function ConsentSummary({ questionSummary }: ConsentSummaryProps) return (
    -
    -

    - {questionSummary.question.headline} -

    -
    +
    -
    Consent
    +
    + {questionTypeInfo && } + {questionTypeInfo ? questionTypeInfo.label : "Unknown Question Type"} +
    {ctr.count} responses diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/Headline.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/Headline.tsx new file mode 100644 index 0000000000..4fde567053 --- /dev/null +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/Headline.tsx @@ -0,0 +1,17 @@ +interface HeadlineProps { + headline: string; + required?: boolean; +} + +export default function Headline({ headline, required = true }: HeadlineProps) { + return ( +
    +

    {headline}

    + {!required && ( + + Optional + + )} +
    + ); +} diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/LinkModalButton.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/LinkModalButton.tsx index 66fbdba48b..2aedcc0361 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/LinkModalButton.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/LinkModalButton.tsx @@ -6,19 +6,23 @@ import { Button } from "@formbricks/ui"; import { ShareIcon } from "@heroicons/react/24/outline"; import { useState } from "react"; import clsx from "clsx"; +import LinkSingleUseSurveyModal from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/LinkSingleUseSurveyModal"; interface LinkSurveyShareButtonProps { survey: TSurvey; className?: string; surveyBaseUrl: string; + singleUseIds?: string[]; } export default function LinkSurveyShareButton({ survey, className, surveyBaseUrl, + singleUseIds, }: LinkSurveyShareButtonProps) { const [showLinkModal, setShowLinkModal] = useState(false); + const isSingleUse = survey.singleUse?.enabled ?? false; return ( <> @@ -31,7 +35,14 @@ export default function LinkSurveyShareButton({ onClick={() => setShowLinkModal(true)}> - {showLinkModal && ( + {showLinkModal && isSingleUse && singleUseIds ? ( + + ) : ( void; + singleUseIds: string[]; +} + +export default function LinkSingleUseSurveyModal({ + survey, + open, + setOpen, + singleUseIds, +}: LinkSingleUseSurveyModalProps) { + const defaultSurveyUrl = `${window.location.protocol}//${window.location.host}/s/${survey.id}`; + const [selectedSingleUseIds, setSelectedSingleIds] = useState([]); + + const linkTextRef = useRef(null); + const router = useRouter(); + + const handleLinkOnClick = (index: number) => { + setSelectedSingleIds([...selectedSingleUseIds, index]); + const surveyUrl = `${defaultSurveyUrl}?suId=${singleUseIds[index]}`; + navigator.clipboard.writeText(surveyUrl); + toast.success("URL copied to clipboard!"); + }; + + return ( + + +
    +
    +
    +

    Your survey is ready!

    +
    +

    + Here are 5 single use links to let people answer your survey: +

    +
    + {singleUseIds.map((singleUseId, index) => { + const isSelected = selectedSingleUseIds.includes(index); + return ( +
    { + if (!isSelected) { + handleLinkOnClick(index); + } + }}> + {truncateMiddle(`${defaultSurveyUrl}?suId=${singleUseId}`, 48)} + {isSelected ? ( + + ) : ( + + )} +
    + ); + })} +
    +
    +
    + + + +
    +
    +
    +
    + ); +} diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/LinkSurveyModal.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/LinkSurveyModal.tsx index 3a2fbc9302..486c5ef291 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/LinkSurveyModal.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/LinkSurveyModal.tsx @@ -19,7 +19,7 @@ export default function LinkSurveyModal({ survey, open, setOpen, surveyBaseUrl } const linkTextRef = useRef(null); const [showEmbed, setShowEmbed] = useState(false); - const surveyUrl = useMemo(() => surveyBaseUrl + survey.id, [survey]); + const surveyUrl = useMemo(() => surveyBaseUrl + survey.id, [survey.id, surveyBaseUrl]); const iframeCode = `
    diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/MultipleChoiceSummary.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/MultipleChoiceSummary.tsx index c0f8277ac5..8c2b9943df 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/MultipleChoiceSummary.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/MultipleChoiceSummary.tsx @@ -9,6 +9,8 @@ import { TSurveyMultipleChoiceMultiQuestion, TSurveyMultipleChoiceSingleQuestion, } from "@formbricks/types/v1/surveys"; +import { questionTypes } from "@/lib/questions"; +import Headline from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/Headline"; interface MultipleChoiceSummaryProps { questionSummary: QuestionSummary; @@ -38,6 +40,8 @@ export default function MultipleChoiceSummary({ }: MultipleChoiceSummaryProps) { const isSingleChoice = questionSummary.question.type === QuestionType.MultipleChoiceSingle; + const questionTypeInfo = questionTypes.find((type) => type.id === questionSummary.question.type); + const results: ChoiceResult[] = useMemo(() => { if (!("choices" in questionSummary.question)) return []; @@ -125,16 +129,12 @@ export default function MultipleChoiceSummary({ return (
    -
    -

    - {questionSummary.question.headline} -

    -
    + +
    -
    - {isSingleChoice - ? "Multiple-Choice Single Select Question" - : "Multiple-Choice Multi Select Question"} +
    + {questionTypeInfo && } + Multiple-Choice {questionTypeInfo ? questionTypeInfo.label : "Unknown Question Type"} Question
    diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/NPSSummary.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/NPSSummary.tsx index c06f4f7cae..37a5e5eaba 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/NPSSummary.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/NPSSummary.tsx @@ -1,8 +1,10 @@ +import Headline from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/Headline"; import type { QuestionSummary } from "@formbricks/types/responses"; import { TSurveyNPSQuestion } from "@formbricks/types/v1/surveys"; import { HalfCircle, ProgressBar } from "@formbricks/ui"; import { InboxStackIcon } from "@heroicons/react/24/solid"; import { useMemo } from "react"; +import { questionTypes } from "@/lib/questions"; interface NPSSummaryProps { questionSummary: QuestionSummary; @@ -28,6 +30,8 @@ export default function NPSSummary({ questionSummary }: NPSSummaryProps) { return result || 0; }; + const questionTypeInfo = questionTypes.find((type) => type.id === questionSummary.question.type); + const result: Result = useMemo(() => { let data = { promoters: 0, @@ -75,13 +79,13 @@ export default function NPSSummary({ questionSummary }: NPSSummaryProps) { return (
    -
    -

    - {questionSummary.question.headline} -

    -
    + +
    -
    Net Promoter Score (NPS)
    +
    + {questionTypeInfo && } + {questionTypeInfo ? questionTypeInfo.label : "Unknown Question Type"} +
    {result.total} responses diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/OpenTextSummary.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/OpenTextSummary.tsx index 1a0427b339..a92e2a1a77 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/OpenTextSummary.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/OpenTextSummary.tsx @@ -1,3 +1,4 @@ +import Headline from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/Headline"; import { truncate } from "@/lib/utils"; import { timeSince } from "@formbricks/lib/time"; import type { QuestionSummary } from "@formbricks/types/responses"; @@ -5,6 +6,7 @@ import { TSurveyOpenTextQuestion } from "@formbricks/types/v1/surveys"; import { PersonAvatar } from "@formbricks/ui"; import { InboxStackIcon } from "@heroicons/react/24/solid"; import Link from "next/link"; +import { questionTypes } from "@/lib/questions"; interface OpenTextSummaryProps { questionSummary: QuestionSummary; @@ -16,16 +18,18 @@ function findEmail(person) { } export default function OpenTextSummary({ questionSummary, environmentId }: OpenTextSummaryProps) { + const questionTypeInfo = questionTypes.find((type) => type.id === questionSummary.question.type); + return (
    -
    -

    - {questionSummary.question.headline} -

    -
    + +
    -
    Open Text Question
    +
    + {questionTypeInfo && } + {questionTypeInfo ? questionTypeInfo.label : "Unknown Question Type"} Question +
    {questionSummary.responses.length} Responses diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/RatingSummary.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/RatingSummary.tsx index b62d82949d..39461a563f 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/RatingSummary.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/RatingSummary.tsx @@ -5,6 +5,8 @@ import { useMemo } from "react"; import { QuestionType } from "@formbricks/types/questions"; import { TSurveyRatingQuestion } from "@formbricks/types/v1/surveys"; import { RatingResponse } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/components/RatingResponse"; +import { questionTypes } from "@/lib/questions"; +import Headline from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/Headline"; interface RatingSummaryProps { questionSummary: QuestionSummary; @@ -17,6 +19,8 @@ interface ChoiceResult { } export default function RatingSummary({ questionSummary }: RatingSummaryProps) { + const questionTypeInfo = questionTypes.find((type) => type.id === questionSummary.question.type); + const results: ChoiceResult[] = useMemo(() => { if (questionSummary.question.type !== QuestionType.Rating) return []; // build a dictionary of choices @@ -77,13 +81,13 @@ export default function RatingSummary({ questionSummary }: RatingSummaryProps) { return (
    -
    -

    - {questionSummary.question.headline} -

    -
    + +
    -
    Rating Question
    +
    + {questionTypeInfo && } + {questionTypeInfo ? questionTypeInfo.label : "Unknown Question Type"} Question +
    {totalResponses} responses diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/StatusDropdown.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/StatusDropdown.tsx deleted file mode 100644 index b970c69ee7..0000000000 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/StatusDropdown.tsx +++ /dev/null @@ -1,32 +0,0 @@ -"use client"; - -import LoadingSpinner from "@/components/shared/LoadingSpinner"; -import SurveyStatusDropdown from "@/components/shared/SurveyStatusDropdown"; -import { useEnvironment } from "@/lib/environments/environments"; -import { TSurvey } from "@formbricks/types/v1/surveys"; -import { ErrorComponent } from "@formbricks/ui"; - -interface StatusDropdownProps { - survey: TSurvey; - environmentId: string; -} - -export default function StatusDropdown({ survey, environmentId }: StatusDropdownProps) { - const { environment, isLoadingEnvironment, isErrorEnvironment } = useEnvironment(environmentId); - - if (isLoadingEnvironment) { - return ; - } - - if (isErrorEnvironment) { - return ; - } - - return ( - <> - {environment.widgetSetupCompleted || survey.type === "link" ? ( - - ) : null} - - ); -} 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 7667e0f2d1..4df9c80059 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 @@ -1,53 +1,66 @@ "use client"; -import { useEnvironment } from "@/lib/environments/environments"; import { TSurvey } from "@formbricks/types/v1/surveys"; import { Confetti } from "@formbricks/ui"; import { useSearchParams } from "next/navigation"; import { useEffect, useState } from "react"; import toast from "react-hot-toast"; import LinkSurveyModal from "./LinkSurveyModal"; +import LinkSingleUseSurveyModal from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/LinkSingleUseSurveyModal"; +import { TEnvironment } from "@formbricks/types/v1/environment"; interface SummaryMetadataProps { - environmentId: string; + environment: TEnvironment; survey: TSurvey; surveyBaseUrl: string; + singleUseIds?: string[]; } -export default function SuccessMessage({ environmentId, survey, surveyBaseUrl }: SummaryMetadataProps) { - const { environment } = useEnvironment(environmentId); +export default function SuccessMessage({ + environment, + survey, + surveyBaseUrl, + singleUseIds, +}: SummaryMetadataProps) { + const isSingleUse = survey.singleUse?.enabled ?? false; const searchParams = useSearchParams(); const [showLinkModal, setShowLinkModal] = useState(false); const [confetti, setConfetti] = useState(false); + useEffect(() => { - if (environment) { - const newSurveyParam = searchParams?.get("success"); - if (newSurveyParam && survey && environment) { - setConfetti(true); - toast.success( - survey.type === "web" && !environment.widgetSetupCompleted - ? "Almost there! Install widget to start receiving responses." - : "Congrats! Your survey is live.", - { - icon: survey.type === "web" && !environment.widgetSetupCompleted ? "🤏" : "🎉", - duration: 5000, - position: "bottom-right", - } - ); - if (survey.type === "link") { - setShowLinkModal(true); + const newSurveyParam = searchParams?.get("success"); + if (newSurveyParam && survey && environment) { + setConfetti(true); + toast.success( + survey.type === "web" && !environment.widgetSetupCompleted + ? "Almost there! Install widget to start receiving responses." + : "Congrats! Your survey is live.", + { + icon: survey.type === "web" && !environment.widgetSetupCompleted ? "🤏" : "🎉", + duration: 5000, + position: "bottom-right", } - // Remove success param from url - const url = new URL(window.location.href); - url.searchParams.delete("success"); - window.history.replaceState({}, "", url.toString()); + ); + if (survey.type === "link") { + setShowLinkModal(true); } + // Remove success param from url + const url = new URL(window.location.href); + url.searchParams.delete("success"); + window.history.replaceState({}, "", url.toString()); } }, [environment, searchParams, survey]); return ( <> - {showLinkModal && ( + {showLinkModal && isSingleUse && singleUseIds ? ( + + ) : ( [] => survey.questions.map((question) => { const questionResponses = responses @@ -48,13 +49,13 @@ export default function SummaryList({ environmentId, survey, responses }: Summar <>
    {survey.type === "web" && responses.length === 0 && ( - + )} {survey.type !== "web" && responses.length === 0 ? ( ) : ( @@ -65,7 +66,7 @@ export default function SummaryList({ environmentId, survey, responses }: Summar } - environmentId={environmentId} + environmentId={environment.id} /> ); } @@ -81,7 +82,7 @@ export default function SummaryList({ environmentId, survey, responses }: Summar TSurveyMultipleChoiceMultiQuestion | TSurveyMultipleChoiceSingleQuestion > } - environmentId={environmentId} + environmentId={environment.id} surveyType={survey.type} /> ); diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SummaryPage.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SummaryPage.tsx index 28454c5d2e..0651c346f5 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SummaryPage.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SummaryPage.tsx @@ -12,16 +12,31 @@ import { TResponse } from "@formbricks/types/v1/responses"; import { TSurveyWithAnalytics } from "@formbricks/types/v1/surveys"; import { useSearchParams } from "next/navigation"; import { useEffect, useMemo } from "react"; +import { TEnvironment } from "@formbricks/types/v1/environment"; +import { TProduct } from "@formbricks/types/v1/product"; +import { TTag } from "@formbricks/types/v1/tags"; interface SummaryPageProps { - environmentId: string; + environment: TEnvironment; survey: TSurveyWithAnalytics; surveyId: string; responses: TResponse[]; surveyBaseUrl: string; + singleUseIds?: string[]; + product: TProduct; + environmentTags: TTag[]; } -const SummaryPage = ({ environmentId, survey, surveyId, responses, surveyBaseUrl }: SummaryPageProps) => { +const SummaryPage = ({ + environment, + survey, + surveyId, + responses, + surveyBaseUrl, + singleUseIds, + product, + environmentTags, +}: SummaryPageProps) => { const { selectedFilter, dateRange, resetState } = useResponseFilter(); const searchParams = useSearchParams(); @@ -30,6 +45,7 @@ const SummaryPage = ({ environmentId, survey, surveyId, responses, surveyBaseUrl resetState(); } }, [searchParams]); + // get the filtered array when the selected filter value changes const filterResponses: TResponse[] = useMemo(() => { return getFilterResponses(responses, selectedFilter, survey, dateRange); @@ -38,20 +54,22 @@ const SummaryPage = ({ environmentId, survey, surveyId, responses, surveyBaseUrl return ( - + - + ); }; diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/page.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/page.tsx index ad7d8c42e3..c5866fb710 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/page.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/page.tsx @@ -5,24 +5,54 @@ import { getAnalysisData } from "@/app/(app)/environments/[environmentId]/survey import SummaryPage from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SummaryPage"; import { authOptions } from "@/app/api/auth/[...nextauth]/authOptions"; import { REVALIDATION_INTERVAL, SURVEY_BASE_URL } from "@formbricks/lib/constants"; +import { getEnvironment } from "@formbricks/lib/services/environment"; +import { getProductByEnvironmentId } from "@formbricks/lib/services/product"; +import { getTagsByEnvironmentId } from "@formbricks/lib/tag/service"; import { getServerSession } from "next-auth"; +import { generateSurveySingleUseId } from "@/lib/singleUseSurveys"; + +const generateSingleUseIds = (isEncrypted: boolean) => { + return Array(5) + .fill(null) + .map(() => { + return generateSurveySingleUseId(isEncrypted); + }); +}; export default async function Page({ params }) { const session = await getServerSession(authOptions); if (!session) { throw new Error("Unauthorized"); } - const { responses, survey } = await getAnalysisData(params.surveyId, params.environmentId); + + const [{ responses, survey }, environment] = await Promise.all([ + getAnalysisData(params.surveyId, params.environmentId), + getEnvironment(params.environmentId), + ]); + const isSingleUseSurvey = survey.singleUse?.enabled ?? false; + const singleUseIds = generateSingleUseIds(survey.singleUse?.isEncrypted ?? false); + if (!environment) { + throw new Error("Environment not found"); + } + + const product = await getProductByEnvironmentId(environment.id); + if (!product) { + throw new Error("Product not found"); + } + const tags = await getTagsByEnvironmentId(params.environmentId); return ( <> ); diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/CustomFilter.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/CustomFilter.tsx old mode 100644 new mode 100755 index ff8be2bc65..d87bcf1dc2 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/CustomFilter.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/CustomFilter.tsx @@ -17,14 +17,14 @@ import { } from "@/lib/surveys/surveys"; import toast from "react-hot-toast"; import { getTodaysDateFormatted } from "@formbricks/lib/time"; -import { convertToCSV } from "@/lib/csvConversion"; +import { fetchFile } from "@/lib/fetchFile"; import useClickOutside from "@formbricks/lib/useClickOutside"; import { TResponse } from "@formbricks/types/v1/responses"; import { TSurvey } from "@formbricks/types/v1/surveys"; import { createId } from "@paralleldrive/cuid2"; import ResponseFilter from "./ResponseFilter"; import { DateRange, useResponseFilter } from "@/app/(app)/environments/[environmentId]/ResponseFilterContext"; -import { useTagsForEnvironment } from "@/lib/tags/tags"; +import { TTag } from "@formbricks/types/v1/tags"; enum DateSelected { FROM = "from", @@ -44,7 +44,7 @@ enum FilterDropDownLabels { } interface CustomFilterProps { - environmentId: string; + environmentTags: TTag[]; survey: TSurvey; responses: TResponse[]; totalResponses: TResponse[]; @@ -61,7 +61,7 @@ const getDifferenceOfDays = (from, to) => { } }; -const CustomFilter = ({ environmentId, responses, survey, totalResponses }: CustomFilterProps) => { +const CustomFilter = ({ environmentTags, responses, survey, totalResponses }: CustomFilterProps) => { const { setSelectedOptions, dateRange, setDateRange } = useResponseFilter(); const [filterRange, setFilterRange] = useState( dateRange.from && dateRange.to @@ -73,7 +73,6 @@ const CustomFilter = ({ environmentId, responses, survey, totalResponses }: Cust const [isFilterDropDownOpen, setIsFilterDropDownOpen] = useState(false); const [isDownloadDropDownOpen, setIsDownloadDropDownOpen] = useState(false); const [hoveredRange, setHoveredRange] = useState(null); - const { data: environmentTags } = useTagsForEnvironment(environmentId); // when the page loads we get total responses and iterate over the responses and questions, tags and attributes to create the filter options useEffect(() => { @@ -132,7 +131,7 @@ const CustomFilter = ({ environmentId, responses, survey, totalResponses }: Cust return []; }; - const csvFileName = useMemo(() => { + const downloadFileName = useMemo(() => { if (survey) { const formattedDateString = getTodaysDateFormatted("_"); return `${survey.name.split(" ").join("_")}_responses_${formattedDateString}`.toLocaleLowerCase(); @@ -142,12 +141,12 @@ const CustomFilter = ({ environmentId, responses, survey, totalResponses }: Cust }, [survey]); const downloadResponses = useCallback( - async (filter: FilterDownload) => { + async (filter: FilterDownload, filetype: "csv" | "xlsx") => { const downloadResponse = filter === FilterDownload.ALL ? totalResponses : responses; const { attributeMap, questionNames } = generateQuestionsAndAttributes(survey, downloadResponse); const matchQandA = getMatchQandA(downloadResponse, survey); - const csvData = matchQandA.map((response) => { - const csvResponse = { + const jsonData = matchQandA.map((response) => { + const fileResponse = { "Response ID": response.id, Timestamp: response.createdAt, Finished: response.finished, @@ -167,26 +166,25 @@ const CustomFilter = ({ environmentId, responses, survey, totalResponses }: Cust transformedAnswer = answer; } } - csvResponse[questionName] = matchingQuestion ? transformedAnswer : ""; + fileResponse[questionName] = matchingQuestion ? transformedAnswer : ""; }); - return csvResponse; + return fileResponse; }); - // Add attribute columns to the CSV - + // Add attribute columns to the file Object.keys(attributeMap).forEach((attributeName) => { const attributeValues = attributeMap[attributeName]; Object.keys(attributeValues).forEach((personId) => { const value = attributeValues[personId]; - const matchingResponse = csvData.find((response) => response["Formbricks User ID"] === personId); + const matchingResponse = jsonData.find((response) => response["Formbricks User ID"] === personId); if (matchingResponse) { matchingResponse[attributeName] = value; } }); }); - // Fields which will be used as column headers in the CSV + // Fields which will be used as column headers in the file const fields = [ "Response ID", "Timestamp", @@ -200,23 +198,40 @@ const CustomFilter = ({ environmentId, responses, survey, totalResponses }: Cust let response; try { - response = await convertToCSV({ - json: csvData, - fields, - fileName: csvFileName, - }); + response = await fetchFile( + { + json: jsonData, + fields, + fileName: downloadFileName, + }, + filetype + ); } catch (err) { - toast.error("Error downloading CSV"); + toast.error(`Error downloading ${filetype === "csv" ? "CSV" : "Excel"}`); return; } - const blob = new Blob([response.csvResponse], { type: "text/csv;charset=utf-8;" }); + let blob: Blob; + if (filetype === "csv") { + blob = new Blob([response.fileResponse], { type: "text/csv;charset=utf-8;" }); + } else if (filetype === "xlsx") { + const binaryString = atob(response["fileResponse"]); + const byteArray = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + byteArray[i] = binaryString.charCodeAt(i); + } + blob = new Blob([byteArray], { + type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + }); + } else { + throw new Error(`Unsupported filetype: ${filetype}`); + } + const downloadUrl = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = downloadUrl; - - link.download = `${csvFileName}.csv`; + link.download = `${downloadFileName}.${filetype}`; document.body.appendChild(link); link.click(); @@ -225,7 +240,7 @@ const CustomFilter = ({ environmentId, responses, survey, totalResponses }: Cust URL.revokeObjectURL(downloadUrl); }, - [csvFileName, responses, totalResponses, survey] + [downloadFileName, responses, totalResponses, survey] ); const handleDateHoveredChange = (date: Date) => { @@ -376,17 +391,31 @@ const CustomFilter = ({ environmentId, responses, survey, totalResponses }: Cust { - downloadResponses(FilterDownload.ALL); + downloadResponses(FilterDownload.ALL, "csv"); }}>

    All responses (CSV)

    { - downloadResponses(FilterDownload.FILTER); + downloadResponses(FilterDownload.ALL, "xlsx"); + }}> +

    All responses (Excel)

    +
    + { + downloadResponses(FilterDownload.FILTER, "csv"); }}>

    Current selection (CSV)

    + { + downloadResponses(FilterDownload.FILTER, "xlsx"); + }}> +

    Current selection (Excel)

    +
    diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/ResponseFilter.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/ResponseFilter.tsx index aaca497890..45c8db087b 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/ResponseFilter.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/ResponseFilter.tsx @@ -1,17 +1,17 @@ "use client"; -import { QuestionType } from "@formbricks/types/questions"; -import QuestionsComboBox, { QuestionOption, OptionsType } from "./QuestionsComboBox"; -import { useState, useEffect } from "react"; -import { Popover, PopoverTrigger, PopoverContent, Button, Checkbox } from "@formbricks/ui"; -import { ChevronDown, ChevronUp, Plus } from "lucide-react"; -import { TrashIcon } from "@heroicons/react/24/solid"; -import QuestionFilterComboBox from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/QuestionFilterComboBox"; import { useResponseFilter } from "@/app/(app)/environments/[environmentId]/ResponseFilterContext"; +import QuestionFilterComboBox from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/QuestionFilterComboBox"; +import { TSurveyQuestionType } from "@formbricks/types/v1/surveys"; +import { Button, Checkbox, Popover, PopoverContent, PopoverTrigger } from "@formbricks/ui"; +import { TrashIcon } from "@heroicons/react/24/solid"; import clsx from "clsx"; +import { ChevronDown, ChevronUp, Plus } from "lucide-react"; +import { useEffect, useState } from "react"; +import QuestionsComboBox, { OptionsType, QuestionOption } from "./QuestionsComboBox"; export type QuestionFilterOptions = { - type: QuestionType | "Attributes" | "Tags"; + type: TSurveyQuestionType | "Attributes" | "Tags"; filterOptions: string[]; filterComboBoxOptions: string[]; id: string; @@ -47,6 +47,14 @@ const ResponseFilter = () => { } }; + // when filter is opened and added a filter without selecting any option clear out that value + const clearItem = () => { + setSelectedFilter({ + filter: [...selectedFilter.filter.filter((s) => s.questionType.hasOwnProperty("label"))], + onlyComplete: selectedFilter.onlyComplete, + }); + }; + // remove the added filter if nothing is selected when filter is closed useEffect(() => { if (!isOpen) { @@ -76,14 +84,6 @@ const ResponseFilter = () => { setSelectedFilter({ ...selectedFilter }); }; - // when filter is opened and added a filter without selecting any option clear out that value - const clearItem = () => { - setSelectedFilter({ - filter: [...selectedFilter.filter.filter((s) => s.questionType.hasOwnProperty("label"))], - onlyComplete: selectedFilter.onlyComplete, - }); - }; - const handleOnChangeFilterComboBoxValue = (o: string | string[], index: number) => { selectedFilter.filter[index] = { ...selectedFilter.filter[index], diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/SummaryHeader.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/SummaryHeader.tsx index c7c3c2d1c8..0416b6b497 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/SummaryHeader.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/SummaryHeader.tsx @@ -1,7 +1,5 @@ "use client"; -import { useEnvironment } from "@/lib/environments/environments"; -import { useProduct } from "@/lib/products/products"; import { TSurvey } from "@formbricks/types/v1/surveys"; import { Button, @@ -15,41 +13,40 @@ import { DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, - ErrorComponent, } from "@formbricks/ui"; import { PencilSquareIcon, EllipsisHorizontalIcon } from "@heroicons/react/24/solid"; import SurveyStatusIndicator from "@/components/shared/SurveyStatusIndicator"; -import { useSurveyMutation } from "@/lib/surveys/mutateSurveys"; import toast from "react-hot-toast"; import { useRouter } from "next/navigation"; import SuccessMessage from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SuccessMessage"; import LinkSurveyShareButton from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/LinkModalButton"; -import LoadingSpinner from "@/components/shared/LoadingSpinner"; import SurveyStatusDropdown from "@/components/shared/SurveyStatusDropdown"; +import { TEnvironment } from "@formbricks/types/v1/environment"; +import { TProduct } from "@formbricks/types/v1/product"; +import { updateSurveyAction } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/edit/actions"; interface SummaryHeaderProps { surveyId: string; - environmentId: string; + environment: TEnvironment; survey: TSurvey; surveyBaseUrl: string; + product: TProduct; + singleUseIds?: string[]; } -const SummaryHeader = ({ surveyId, environmentId, survey, surveyBaseUrl }: SummaryHeaderProps) => { +const SummaryHeader = ({ + surveyId, + environment, + survey, + surveyBaseUrl, + product, + singleUseIds, +}: SummaryHeaderProps) => { const router = useRouter(); - const { product, isLoadingProduct, isErrorProduct } = useProduct(environmentId); - const { environment, isLoadingEnvironment, isErrorEnvironment } = useEnvironment(environmentId); - const { triggerSurveyMutate } = useSurveyMutation(environmentId, surveyId); const isCloseOnDateEnabled = survey.closeOnDate !== null; const closeOnDate = survey.closeOnDate ? new Date(survey.closeOnDate) : null; const isStatusChangeDisabled = (isCloseOnDateEnabled && closeOnDate && closeOnDate < new Date()) ?? false; - if (isLoadingProduct || isLoadingEnvironment) { - return ; - } - - if (isErrorProduct || isErrorEnvironment) { - return ; - } return (
    @@ -57,14 +54,16 @@ const SummaryHeader = ({ surveyId, environmentId, survey, surveyBaseUrl }: Summa {product.name}
    - {survey.type === "link" && } + {survey.type === "link" && ( + + )} {(environment?.widgetSetupCompleted || survey.type === "link") && survey?.status !== "draft" ? ( - + ) : null} @@ -83,6 +82,7 @@ const SummaryHeader = ({ surveyId, environmentId, survey, surveyBaseUrl }: Summa className="flex w-full justify-center p-1" survey={survey} surveyBaseUrl={surveyBaseUrl} + singleUseIds={singleUseIds} /> @@ -94,7 +94,7 @@ const SummaryHeader = ({ surveyId, environmentId, survey, surveyBaseUrl }: Summa disabled={isStatusChangeDisabled} style={isStatusChangeDisabled ? { pointerEvents: "none", opacity: 0.5 } : {}}>
    - + {survey.status === "inProgress" && "In-progress"} {survey.status === "paused" && "Paused"} @@ -107,7 +107,8 @@ const SummaryHeader = ({ surveyId, environmentId, survey, surveyBaseUrl }: Summa { - triggerSurveyMutate({ status: value }) + const castedValue = value as "draft" | "inProgress" | "paused" | "completed"; + updateSurveyAction({ ...survey, status: castedValue }) .then(() => { toast.success( value === "inProgress" @@ -152,14 +153,19 @@ const SummaryHeader = ({ surveyId, environmentId, survey, surveyBaseUrl }: Summa variant="darkCTA" size="sm" className="flex h-full w-full justify-center px-3 lg:px-6" - href={`/environments/${environmentId}/surveys/${surveyId}/edit`}> + href={`/environments/${environment.id}/surveys/${surveyId}/edit`}> Edit
    - +
    ); }; diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/edit/AddQuestionButton.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/edit/AddQuestionButton.tsx index 8911641ef4..1271d3a195 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/edit/AddQuestionButton.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/edit/AddQuestionButton.tsx @@ -1,10 +1,8 @@ "use client"; -import LoadingSpinner from "@/components/shared/LoadingSpinner"; -import { useProduct } from "@/lib/products/products"; import { getQuestionDefaults, questionTypes, universalQuestionPresets } from "@/lib/questions"; import { cn } from "@formbricks/lib/cn"; -import { ErrorComponent } from "@formbricks/ui"; +import { TProduct } from "@formbricks/types/v1/product"; import { PlusIcon } from "@heroicons/react/24/solid"; import { createId } from "@paralleldrive/cuid2"; import * as Collapsible from "@radix-ui/react-collapsible"; @@ -12,17 +10,12 @@ import { useState } from "react"; interface AddQuestionButtonProps { addQuestion: (question: any) => void; - environmentId: string; + product: TProduct; } -export default function AddQuestionButton({ addQuestion, environmentId }: AddQuestionButtonProps) { - const { product, isLoadingProduct, isErrorProduct } = useProduct(environmentId); - +export default function AddQuestionButton({ addQuestion, product }: AddQuestionButtonProps) { const [open, setOpen] = useState(false); - if (isLoadingProduct) return ; - if (isErrorProduct) return ; - return ( void; activeQuestionId: string | null; setActiveQuestionId: (questionId: string | null) => void; - environmentId: string; + product: TProduct; invalidQuestions: String[] | null; setInvalidQuestions: (invalidQuestions: String[] | null) => void; } @@ -28,7 +29,7 @@ export default function QuestionsView({ setActiveQuestionId, localSurvey, setLocalSurvey, - environmentId, + product, invalidQuestions, setInvalidQuestions, }: QuestionsViewProps) { @@ -58,7 +59,7 @@ export default function QuestionsView({ }; // function to validate individual questions - const validateSurvey = (question: Question) => { + const validateSurvey = (question: TSurveyQuestion) => { // prevent this function to execute further if user hasnt still tried to save the survey if (invalidQuestions === null) { return; @@ -212,7 +213,7 @@ export default function QuestionsView({
    - +
    void; + isEncryptionKeySet: boolean; } -export default function ResponseOptionsCard({ localSurvey, setLocalSurvey }: ResponseOptionsCardProps) { +export default function ResponseOptionsCard({ + localSurvey, + setLocalSurvey, + isEncryptionKeySet, +}: ResponseOptionsCardProps) { const [open, setOpen] = useState(false); const autoComplete = localSurvey.autoComplete !== null; const [redirectToggle, setRedirectToggle] = useState(false); @@ -27,6 +42,12 @@ export default function ResponseOptionsCard({ localSurvey, setLocalSurvey }: Res subheading: "This free & open-source survey has been closed", }); + const [singleUseMessage, setSingleUseMessage] = useState({ + heading: "The survey has already been answered.", + subheading: "You can only use this link once.", + }); + + const [singleUseEncryption, setSingleUseEncryption] = useState(isEncryptionKeySet); const [verifyEmailSurveyDetails, setVerifyEmailSurveyDetails] = useState({ name: "", subheading: "", @@ -104,6 +125,53 @@ export default function ResponseOptionsCard({ localSurvey, setLocalSurvey }: Res setLocalSurvey({ ...localSurvey, surveyClosedMessage: message }); }; + const handleSingleUseSurveyToggle = () => { + if (!localSurvey.singleUse?.enabled) { + setLocalSurvey({ + ...localSurvey, + singleUse: { enabled: true, ...singleUseMessage, isEncrypted: singleUseEncryption }, + }); + } else { + setLocalSurvey({ ...localSurvey, singleUse: { enabled: false, isEncrypted: false } }); + } + }; + + const handleSingleUseSurveyMessageChange = ({ + heading, + subheading, + }: { + heading?: string; + subheading?: string; + }) => { + const message = { + heading: heading ?? singleUseMessage.heading, + subheading: subheading ?? singleUseMessage.subheading, + }; + + const localSurveySingleUseEnabled = localSurvey.singleUse?.enabled ?? false; + setSingleUseMessage(message); + setLocalSurvey({ + ...localSurvey, + singleUse: { enabled: localSurveySingleUseEnabled, ...message, isEncrypted: singleUseEncryption }, + }); + }; + + const hangleSingleUseEncryptionToggle = () => { + if (!singleUseEncryption) { + setSingleUseEncryption(true); + setLocalSurvey({ + ...localSurvey, + singleUse: { enabled: true, ...singleUseMessage, isEncrypted: true }, + }); + } else { + setSingleUseEncryption(false); + setLocalSurvey({ + ...localSurvey, + singleUse: { enabled: true, ...singleUseMessage, isEncrypted: false }, + }); + } + }; + const handleVerifyEmailSurveyDetailsChange = ({ name, subheading, @@ -134,6 +202,14 @@ export default function ResponseOptionsCard({ localSurvey, setLocalSurvey }: Res setSurveyClosedMessageToggle(true); } + if (localSurvey.singleUse?.enabled) { + setSingleUseMessage({ + heading: localSurvey.singleUse.heading ?? singleUseMessage.heading, + subheading: localSurvey.singleUse.subheading ?? singleUseMessage.subheading, + }); + setSingleUseEncryption(localSurvey.singleUse.isEncrypted); + } + if (localSurvey.verifyEmail) { setVerifyEmailSurveyDetails({ name: localSurvey.verifyEmail.name!, @@ -146,7 +222,7 @@ export default function ResponseOptionsCard({ localSurvey, setLocalSurvey }: Res setCloseOnDate(localSurvey.closeOnDate); setSurveyCloseOnDateToggle(true); } - }, []); + }, [localSurvey]); const handleCheckMark = () => { if (autoComplete) { @@ -302,6 +378,81 @@ export default function ResponseOptionsCard({ localSurvey, setLocalSurvey }: Res
    + {/* Single User Survey Options */} + +
    +
    +
    + +
    +
      +
    • + Blocks survey if the survey URL has no Single Use Id (suId). +
    • +
    • + Blocks survey if a submission with the Single Use Id (suId) in the URL exists already. +
    • +
    + + handleSingleUseSurveyMessageChange({ heading: e.target.value })} + /> + + + handleSingleUseSurveyMessageChange({ subheading: e.target.value })} + /> + +
    + + + +
    + + +
    +
    + {!isEncryptionKeySet && ( + +

    + FORMBRICKS_ENCRYPTION_KEY needs to be set to enable this feature. +

    +
    + )} +
    +
    +
    +
    +
    +
    + + {/* Verify Email Section */} void; actionClasses: TActionClass[]; attributeClasses: TAttributeClass[]; + isEncryptionKeySet: boolean; } export default function SettingsView({ @@ -22,6 +23,7 @@ export default function SettingsView({ setLocalSurvey, actionClasses, attributeClasses, + isEncryptionKeySet, }: SettingsViewProps) { return (
    @@ -41,7 +43,11 @@ export default function SettingsView({ actionClasses={actionClasses} /> - + ("questions"); const [activeQuestionId, setActiveQuestionId] = useState(null); @@ -46,7 +48,7 @@ export default function SurveyEditor({ // when the survey type changes, we need to reset the active question id to the first question useEffect(() => { - if (localSurvey && localSurvey.questions?.length > 0) { + if (localSurvey?.questions?.length && localSurvey.questions.length > 0) { setActiveQuestionId(localSurvey.questions[0].id); } }, [localSurvey?.type]); @@ -77,7 +79,7 @@ export default function SurveyEditor({ setLocalSurvey={setLocalSurvey} activeQuestionId={activeQuestionId} setActiveQuestionId={setActiveQuestionId} - environmentId={environment.id} + product={product} invalidQuestions={invalidQuestions} setInvalidQuestions={setInvalidQuestions} /> @@ -88,6 +90,7 @@ export default function SurveyEditor({ setLocalSurvey={setLocalSurvey} actionClasses={actionClasses} attributeClasses={attributeClasses} + isEncryptionKeySet={isEncryptionKeySet} /> )}
    diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/edit/SurveyMenuBar.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/edit/SurveyMenuBar.tsx index 822ff1c9fe..b0f9bd0378 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/edit/SurveyMenuBar.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/edit/SurveyMenuBar.tsx @@ -1,10 +1,12 @@ "use client"; -import React from "react"; import AlertDialog from "@/components/shared/AlertDialog"; import DeleteDialog from "@/components/shared/DeleteDialog"; import SurveyStatusDropdown from "@/components/shared/SurveyStatusDropdown"; import type { Survey } from "@formbricks/types/surveys"; +import { TEnvironment } from "@formbricks/types/v1/environment"; +import { TProduct } from "@formbricks/types/v1/product"; +import { TSurvey, TSurveyWithAnalytics } from "@formbricks/types/v1/surveys"; import { Button, Input } from "@formbricks/ui"; import { ArrowLeftIcon, Cog8ToothIcon, ExclamationTriangleIcon } from "@heroicons/react/24/solid"; import { isEqual } from "lodash"; @@ -12,10 +14,7 @@ import { useRouter } from "next/navigation"; import { useEffect, useState } from "react"; import toast from "react-hot-toast"; import { validateQuestion } from "./Validation"; -import { TSurvey, TSurveyWithAnalytics } from "@formbricks/types/v1/surveys"; -import { deleteSurveyAction, surveyMutateAction } from "./actions"; -import { TProduct } from "@formbricks/types/v1/product"; -import { TEnvironment } from "@formbricks/types/v1/environment"; +import { deleteSurveyAction, updateSurveyAction } from "./actions"; interface SurveyMenuBarProps { localSurvey: TSurveyWithAnalytics; @@ -144,7 +143,7 @@ export default function SurveyMenuBar({ } try { - await surveyMutateAction({ ...strippedSurvey }); + await updateSurveyAction({ ...strippedSurvey }); router.refresh(); setIsMutatingSurvey(false); toast.success("Changes saved."); @@ -156,6 +155,7 @@ export default function SurveyMenuBar({ } else { router.push(`/environments/${environment.id}/surveys`); } + router.refresh(); } } catch (e) { console.error(e); @@ -197,16 +197,16 @@ export default function SurveyMenuBar({ {!!localSurvey.analytics.responseRate && (
    -

    - This survey received responses. To keep the data consistent, make changes with caution. +

    + This survey received responses, make changes with caution.

    )}
    @@ -242,7 +242,7 @@ export default function SurveyMenuBar({ if (!validateSurvey(localSurvey)) { return; } - await surveyMutateAction({ ...localSurvey, status: "inProgress" }); + await updateSurveyAction({ ...localSurvey, status: "inProgress" }); router.refresh(); setIsMutatingSurvey(false); router.push(`/environments/${environment.id}/surveys/${localSurvey.id}/summary?success=true`); diff --git a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/edit/WhenToSendCard.tsx b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/edit/WhenToSendCard.tsx index 5b46da1f36..6db7a9c3f7 100644 --- a/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/edit/WhenToSendCard.tsx +++ b/apps/web/app/(app)/environments/[environmentId]/surveys/[surveyId]/edit/WhenToSendCard.tsx @@ -16,7 +16,7 @@ import { } from "@formbricks/ui"; import { CheckCircleIcon, PlusIcon, TrashIcon } from "@heroicons/react/24/solid"; import * as Collapsible from "@radix-ui/react-collapsible"; -import { useEffect, useState } from "react"; +import { useCallback, useEffect, useMemo, useState } from "react"; import { TSurveyWithAnalytics } from "@formbricks/types/v1/surveys"; import { TActionClass } from "@formbricks/types/v1/actionClasses"; @@ -40,30 +40,36 @@ export default function WhenToSendCard({ const autoClose = localSurvey.autoClose !== null; - let newTrigger = { - id: "", // Set the appropriate value for the id - createdAt: new Date(), - updatedAt: new Date(), - name: "", - type: "code" as const, // Set the appropriate value for the type - environmentId: "", - description: null, - noCodeConfig: null, - }; + let newTrigger = useMemo( + () => ({ + id: "", // Set the appropriate value for the id + createdAt: new Date(), + updatedAt: new Date(), + name: "", + type: "code" as const, // Set the appropriate value for the type + environmentId: "", + description: null, + noCodeConfig: null, + }), + [] + ); - const addTriggerEvent = () => { + const addTriggerEvent = useCallback(() => { const updatedSurvey = { ...localSurvey }; updatedSurvey.triggers = [...localSurvey.triggers, newTrigger]; setLocalSurvey(updatedSurvey); - }; + }, [newTrigger, localSurvey, setLocalSurvey]); - const setTriggerEvent = (idx: number, actionClassId: string) => { - const updatedSurvey = { ...localSurvey }; - updatedSurvey.triggers[idx] = actionClassArray!.find((actionClass) => { - return actionClass.id === actionClassId; - })!; - setLocalSurvey(updatedSurvey); - }; + const setTriggerEvent = useCallback( + (idx: number, actionClassId: string) => { + const updatedSurvey = { ...localSurvey }; + updatedSurvey.triggers[idx] = actionClassArray!.find((actionClass) => { + return actionClass.id === actionClassId; + })!; + setLocalSurvey(updatedSurvey); + }, + [actionClassArray, localSurvey, setLocalSurvey] + ); const removeTriggerEvent = (idx: number) => { const updatedSurvey = { ...localSurvey }; @@ -95,11 +101,19 @@ export default function WhenToSendCard({ const updatedSurvey: TSurveyWithAnalytics = { ...localSurvey, delay: value }; setLocalSurvey(updatedSurvey); }; + useEffect(() => { if (activeIndex !== null) { - setTriggerEvent(activeIndex, actionClassArray[actionClassArray.length - 1].id); + const newActionClassId = actionClassArray[actionClassArray.length - 1].id; + const currentActionClassId = localSurvey.triggers[activeIndex]?.id; + + if (newActionClassId !== currentActionClassId) { + setTriggerEvent(activeIndex, newActionClassId); + } + + setActiveIndex(null); } - }, [actionClassArray]); + }, [actionClassArray, activeIndex, setTriggerEvent]); useEffect(() => { if (localSurvey.type === "link") { @@ -112,7 +126,7 @@ export default function WhenToSendCard({ if (localSurvey.triggers.length === 0) { addTriggerEvent(); } - }, []); + }, [addTriggerEvent, localSurvey.triggers.length]); return ( <> @@ -166,45 +180,46 @@ export default function WhenToSendCard({
    - {localSurvey.triggers?.map((triggerEventClass, idx) => ( -
    -
    -

    {idx === 0 ? "When" : "or"}

    - -

    action is performed

    - + {!isAddEventModalOpen && + localSurvey.triggers?.map((triggerEventClass, idx) => ( +
    +
    +

    {idx === 0 ? "When" : "or"}

    + +

    action is performed

    + +
    -
    - ))} + ))}
    - +
    diff --git a/apps/web/app/(auth)/auth/signup/page.tsx b/apps/web/app/(auth)/auth/signup/page.tsx index a5f519967d..76f3b02d47 100644 --- a/apps/web/app/(auth)/auth/signup/page.tsx +++ b/apps/web/app/(auth)/auth/signup/page.tsx @@ -1,15 +1,25 @@ -"use client"; - import Link from "next/link"; -import { useSearchParams } from "next/navigation"; import { SignupForm } from "@/components/auth/SignupForm"; import FormWrapper from "@/components/auth/FormWrapper"; import Testimonial from "@/components/auth/Testimonial"; -import { env } from "@/env.mjs"; +import { + EMAIL_VERIFICATION_DISABLED, + GITHUB_OAUTH_ENABLED, + GOOGLE_OAUTH_ENABLED, + INVITE_DISABLED, + PASSWORD_RESET_DISABLED, + PRIVACY_URL, + SIGNUP_ENABLED, + TERMS_URL, + WEBAPP_URL, +} from "@formbricks/lib/constants"; -export default function SignUpPage() { - const searchParams = useSearchParams(); - const inviteToken = searchParams?.get("inviteToken"); +export default function SignUpPage({ + searchParams, +}: { + searchParams: { [key: string]: string | string[] | undefined }; +}) { + const inviteToken = searchParams["inviteToken"] ?? null; return (
    @@ -18,9 +28,7 @@ export default function SignUpPage() {
    - {( - inviteToken ? env.NEXT_PUBLIC_INVITE_DISABLED === "1" : env.NEXT_PUBLIC_SIGNUP_DISABLED === "1" - ) ? ( + {(inviteToken ? INVITE_DISABLED : !SIGNUP_ENABLED) ? ( <>

    Sign up disabled

    @@ -35,7 +43,15 @@ export default function SignUpPage() { ) : ( - + )}

    diff --git a/apps/web/app/(auth)/invite/page.tsx b/apps/web/app/(auth)/invite/page.tsx index 67a8a4dc81..473168ce96 100644 --- a/apps/web/app/(auth)/invite/page.tsx +++ b/apps/web/app/(auth)/invite/page.tsx @@ -2,7 +2,6 @@ import { sendInviteAcceptedEmail } from "@/lib/email"; import { verifyInviteToken } from "@formbricks/lib/jwt"; import { authOptions } from "@/app/api/auth/[...nextauth]/authOptions"; import { getServerSession } from "next-auth"; -import { env } from "process"; import { prisma } from "@formbricks/database"; import { NotLoggedInContent, @@ -11,6 +10,7 @@ import { UsedContent, RightAccountContent, } from "./InviteContentComponents"; +import { env } from "@/env.mjs"; export default async function JoinTeam({ searchParams }) { const currentUser = await getServerSession(authOptions); diff --git a/apps/web/app/api/auth/[...nextauth]/authOptions.ts b/apps/web/app/api/auth/[...nextauth]/authOptions.ts index 3c61f999d4..5dbdefac8b 100644 --- a/apps/web/app/api/auth/[...nextauth]/authOptions.ts +++ b/apps/web/app/api/auth/[...nextauth]/authOptions.ts @@ -1,8 +1,9 @@ import { env } from "@/env.mjs"; import { verifyPassword } from "@/lib/auth"; -import { verifyToken } from "@formbricks/lib/jwt"; import { prisma } from "@formbricks/database"; -import { INTERNAL_SECRET, WEBAPP_URL } from "@formbricks/lib/constants"; +import { EMAIL_VERIFICATION_DISABLED, INTERNAL_SECRET, WEBAPP_URL } from "@formbricks/lib/constants"; +import { verifyToken } from "@formbricks/lib/jwt"; +import { getProfileByEmail } from "@formbricks/lib/services/profile"; import type { IdentityProvider } from "@prisma/client"; import type { NextAuthOptions } from "next-auth"; import CredentialsProvider from "next-auth/providers/credentials"; @@ -133,42 +134,16 @@ export const authOptions: NextAuthOptions = { ], callbacks: { async jwt({ token }) { - const existingUser = await prisma.user.findFirst({ - where: { email: token.email! }, - select: { - id: true, - createdAt: true, - onboardingCompleted: true, - memberships: { - select: { - teamId: true, - role: true, - team: { - select: { - plan: true, - }, - }, - }, - }, - name: true, - }, - }); + const existingUser = await getProfileByEmail(token?.email!); if (!existingUser) { return token; } - const teams = existingUser.memberships.map((membership) => ({ - id: membership.teamId, - role: membership.role, - plan: membership.team.plan, - })); - const additionalAttributs = { id: existingUser.id, createdAt: existingUser.createdAt, onboardingCompleted: existingUser.onboardingCompleted, - teams, name: existingUser.name, }; @@ -185,14 +160,13 @@ export const authOptions: NextAuthOptions = { // @ts-ignore session.user.onboardingCompleted = token?.onboardingCompleted; // @ts-ignore - session.user.teams = token?.teams; session.user.name = token.name || ""; return session; }, async signIn({ user, account }: any) { if (account.provider === "credentials" || account.provider === "token") { - if (!user.emailVerified && env.NEXT_PUBLIC_EMAIL_VERIFICATION_DISABLED !== "1") { + if (!user.emailVerified && !EMAIL_VERIFICATION_DISABLED) { return `/auth/verification-requested?email=${encodeURIComponent(user.email)}`; } return true; diff --git a/apps/web/app/api/cron/close_surveys/route.ts b/apps/web/app/api/cron/close_surveys/route.ts index 320571e0bf..41b06ddfb3 100644 --- a/apps/web/app/api/cron/close_surveys/route.ts +++ b/apps/web/app/api/cron/close_surveys/route.ts @@ -1,13 +1,13 @@ -import { env } from "@/env.mjs"; import { responses } from "@/lib/api/response"; import { prisma } from "@formbricks/database"; +import { CRON_SECRET } from "@formbricks/lib/constants"; import { headers } from "next/headers"; export async function POST() { const headersList = headers(); const apiKey = headersList.get("x-api-key"); - if (!apiKey || apiKey !== env.CRON_SECRET) { + if (!apiKey || apiKey !== CRON_SECRET) { return responses.notAuthenticatedResponse(); } diff --git a/apps/web/app/api/google-sheet/callback/route.ts b/apps/web/app/api/google-sheet/callback/route.ts index 8644ce18d8..e2c4540adc 100644 --- a/apps/web/app/api/google-sheet/callback/route.ts +++ b/apps/web/app/api/google-sheet/callback/route.ts @@ -1,6 +1,10 @@ -import { env } from "@/env.mjs"; import { prisma } from "@formbricks/database"; -import { WEBAPP_URL } from "@formbricks/lib/constants"; +import { + GOOGLE_SHEETS_CLIENT_ID, + WEBAPP_URL, + GOOGLE_SHEETS_CLIENT_SECRET, + GOOGLE_SHEETS_REDIRECT_URL, +} from "@formbricks/lib/constants"; import { google } from "googleapis"; import { NextRequest, NextResponse } from "next/server"; @@ -18,9 +22,9 @@ export async function GET(req: NextRequest) { return NextResponse.json({ message: "`code` must be a string" }, { status: 400 }); } - const client_id = env.GOOGLE_SHEETS_CLIENT_ID; - const client_secret = env.GOOGLE_SHEETS_CLIENT_SECRET; - const redirect_uri = env.GOOGLE_SHEETS_REDIRECT_URL; + const client_id = GOOGLE_SHEETS_CLIENT_ID; + const client_secret = GOOGLE_SHEETS_CLIENT_SECRET; + const redirect_uri = GOOGLE_SHEETS_REDIRECT_URL; if (!client_id) return NextResponse.json({ Error: "Google client id is missing" }, { status: 400 }); if (!client_secret) return NextResponse.json({ Error: "Google client secret is missing" }, { status: 400 }); if (!redirect_uri) return NextResponse.json({ Error: "Google redirect url is missing" }, { status: 400 }); diff --git a/apps/web/app/api/google-sheet/route.ts b/apps/web/app/api/google-sheet/route.ts index 63bd97d0a2..9e3864a54d 100644 --- a/apps/web/app/api/google-sheet/route.ts +++ b/apps/web/app/api/google-sheet/route.ts @@ -1,5 +1,9 @@ -import { hasUserEnvironmentAccess } from "@/lib/api/apiHelper"; -import { env } from "@/env.mjs"; +import { hasUserEnvironmentAccess } from "@formbricks/lib/environment/auth"; +import { + GOOGLE_SHEETS_CLIENT_ID, + GOOGLE_SHEETS_CLIENT_SECRET, + GOOGLE_SHEETS_REDIRECT_URL, +} from "@formbricks/lib/constants"; import { google } from "googleapis"; import { NextRequest, NextResponse } from "next/server"; import { authOptions } from "@/app/api/auth/[...nextauth]/authOptions"; @@ -15,18 +19,22 @@ export async function GET(req: NextRequest) { const environmentId = req.headers.get("environmentId"); const session = await getServerSession(authOptions); + if (!environmentId) { + return NextResponse.json({ Error: "environmentId is missing" }, { status: 400 }); + } + if (!session) { return NextResponse.json({ Error: "Invalid session" }, { status: 400 }); } - const canUserAccessEnvironment = await hasUserEnvironmentAccess(session?.user, environmentId); + const canUserAccessEnvironment = await hasUserEnvironmentAccess(session?.user.id, environmentId); if (!canUserAccessEnvironment) { return NextResponse.json({ Error: "You dont have access to environment" }, { status: 401 }); } - const client_id = env.GOOGLE_SHEETS_CLIENT_ID; - const client_secret = env.GOOGLE_SHEETS_CLIENT_SECRET; - const redirect_uri = env.GOOGLE_SHEETS_REDIRECT_URL; + const client_id = GOOGLE_SHEETS_CLIENT_ID; + const client_secret = GOOGLE_SHEETS_CLIENT_SECRET; + const redirect_uri = GOOGLE_SHEETS_REDIRECT_URL; if (!client_id) return NextResponse.json({ Error: "Google client id is missing" }, { status: 400 }); if (!client_secret) return NextResponse.json({ Error: "Google client secret is missing" }, { status: 400 }); if (!redirect_uri) return NextResponse.json({ Error: "Google redirect url is missing" }, { status: 400 }); diff --git a/apps/web/app/api/integration/integrations.ts b/apps/web/app/api/integration/integrations.ts index 3ffbc383d7..c28c768867 100644 --- a/apps/web/app/api/integration/integrations.ts +++ b/apps/web/app/api/integration/integrations.ts @@ -1,5 +1,5 @@ import { writeData } from "@formbricks/lib/services/googleSheet"; -import { getSurvey } from "@formbricks/lib/services/survey"; +import { getSurvey } from "@formbricks/lib/survey/service"; import { TGoogleSheetIntegration, TIntegration } from "@formbricks/types/v1/integrations"; import { TPipelineInput } from "@formbricks/types/v1/pipelines"; diff --git a/apps/web/app/api/csv-conversion/route.ts b/apps/web/app/api/internal/csv-conversion/route.ts old mode 100644 new mode 100755 similarity index 69% rename from apps/web/app/api/csv-conversion/route.ts rename to apps/web/app/api/internal/csv-conversion/route.ts index 697c9cc15b..96eeb42546 --- a/apps/web/app/api/csv-conversion/route.ts +++ b/apps/web/app/api/internal/csv-conversion/route.ts @@ -1,7 +1,16 @@ import { NextRequest, NextResponse } from "next/server"; import { AsyncParser } from "@json2csv/node"; +import { getServerSession } from "next-auth"; +import { authOptions } from "@/app/api/auth/[...nextauth]/authOptions"; +import { responses } from "@/lib/api/response"; export async function POST(request: NextRequest) { + const session = await getServerSession(authOptions); + + if (!session) { + return responses.unauthorizedResponse(); + } + const data = await request.json(); let csv: string = ""; @@ -24,7 +33,7 @@ export async function POST(request: NextRequest) { return NextResponse.json( { - csvResponse: csv, + fileResponse: csv, }, { headers, diff --git a/apps/web/app/api/internal/excel-conversion/route.ts b/apps/web/app/api/internal/excel-conversion/route.ts new file mode 100755 index 0000000000..d6a1263e04 --- /dev/null +++ b/apps/web/app/api/internal/excel-conversion/route.ts @@ -0,0 +1,39 @@ +import { authOptions } from "@/app/api/auth/[...nextauth]/authOptions"; +import { responses } from "@/lib/api/response"; +import { getServerSession } from "next-auth"; +import { NextRequest, NextResponse } from "next/server"; +import * as xlsx from "xlsx"; + +export async function POST(request: NextRequest) { + const session = await getServerSession(authOptions); + + if (!session) { + return responses.unauthorizedResponse(); + } + + const data = await request.json(); + + const { json, fields, fileName } = data; + + const wb = xlsx.utils.book_new(); + const ws = xlsx.utils.json_to_sheet(json, { header: fields }); + xlsx.utils.book_append_sheet(wb, ws, "Sheet1"); + + const buffer = xlsx.write(wb, { type: "buffer", bookType: "xlsx" }); + + const binaryString = String.fromCharCode.apply(null, buffer); + const base64String = btoa(binaryString); + + const headers = new Headers(); + headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + headers.set("Content-Disposition", `attachment; filename=${fileName ?? "converted"}.xlsx`); + + return NextResponse.json( + { + fileResponse: base64String, + }, + { + headers, + } + ); +} diff --git a/apps/web/app/api/v1/auth.ts b/apps/web/app/api/v1/auth.ts index 2234d081f7..c8403b90bb 100644 --- a/apps/web/app/api/v1/auth.ts +++ b/apps/web/app/api/v1/auth.ts @@ -1,4 +1,4 @@ -import { getApiKeyFromKey } from "@formbricks/lib/services/apiKey"; +import { getApiKeyFromKey } from "@formbricks/lib/apiKey/service"; import { TAuthenticationApiKey } from "@formbricks/types/v1/auth"; import { DatabaseError, InvalidInputError, ResourceNotFoundError } from "@formbricks/types/v1/errors"; import { responses } from "@/lib/api/response"; diff --git a/apps/web/app/api/v1/client/displays/route.ts b/apps/web/app/api/v1/client/displays/route.ts index e51d6639af..7d46e99a8e 100644 --- a/apps/web/app/api/v1/client/displays/route.ts +++ b/apps/web/app/api/v1/client/displays/route.ts @@ -3,7 +3,7 @@ import { transformErrorToDetails } from "@/lib/api/validator"; import { InvalidInputError } from "@formbricks/types/v1/errors"; import { capturePosthogEvent } from "@formbricks/lib/posthogServer"; import { createDisplay } from "@formbricks/lib/services/displays"; -import { getSurvey } from "@formbricks/lib/services/survey"; +import { getSurvey } from "@formbricks/lib/survey/service"; import { getTeamDetails } from "@formbricks/lib/services/teamDetails"; import { TDisplay, ZDisplayInput } from "@formbricks/types/v1/displays"; import { NextResponse } from "next/server"; diff --git a/apps/web/app/api/v1/client/responses/[responseId]/route.ts b/apps/web/app/api/v1/client/responses/[responseId]/route.ts index fd92d2b780..59edb5b4cb 100644 --- a/apps/web/app/api/v1/client/responses/[responseId]/route.ts +++ b/apps/web/app/api/v1/client/responses/[responseId]/route.ts @@ -2,8 +2,8 @@ import { responses } from "@/lib/api/response"; import { transformErrorToDetails } from "@/lib/api/validator"; import { sendToPipeline } from "@/lib/pipelines"; import { DatabaseError, InvalidInputError, ResourceNotFoundError } from "@formbricks/types/v1/errors"; -import { updateResponse } from "@formbricks/lib/services/response"; -import { getSurvey } from "@formbricks/lib/services/survey"; +import { getSurvey } from "@formbricks/lib/survey/service"; +import { updateResponse } from "@formbricks/lib/response/service"; import { ZResponseUpdateInput } from "@formbricks/types/v1/responses"; import { NextResponse } from "next/server"; diff --git a/apps/web/app/api/v1/client/responses/route.ts b/apps/web/app/api/v1/client/responses/route.ts index a9898b1b92..0def24c540 100644 --- a/apps/web/app/api/v1/client/responses/route.ts +++ b/apps/web/app/api/v1/client/responses/route.ts @@ -3,8 +3,8 @@ import { transformErrorToDetails } from "@/lib/api/validator"; import { sendToPipeline } from "@/lib/pipelines"; import { InvalidInputError } from "@formbricks/types/v1/errors"; import { capturePosthogEvent } from "@formbricks/lib/posthogServer"; -import { createResponse } from "@formbricks/lib/services/response"; -import { getSurvey } from "@formbricks/lib/services/survey"; +import { getSurvey } from "@formbricks/lib/survey/service"; +import { createResponse } from "@formbricks/lib/response/service"; import { getTeamDetails } from "@formbricks/lib/services/teamDetails"; import { TResponse, TResponseInput, ZResponseInput } from "@formbricks/types/v1/responses"; import { NextResponse } from "next/server"; diff --git a/apps/web/app/api/v1/js/surveys.ts b/apps/web/app/api/v1/js/surveys.ts index 8b53d212ce..bd0a77f446 100644 --- a/apps/web/app/api/v1/js/surveys.ts +++ b/apps/web/app/api/v1/js/surveys.ts @@ -1,17 +1,17 @@ import { prisma } from "@formbricks/database"; -import { selectSurvey } from "@formbricks/lib/services/survey"; +import { selectSurvey } from "@formbricks/lib/survey/service"; import { TPerson } from "@formbricks/types/v1/people"; import { TSurvey } from "@formbricks/types/v1/surveys"; import { unstable_cache } from "next/cache"; const getSurveysCacheTags = (environmentId: string, personId: string): string[] => [ - `env-${environmentId}-surveys`, - `env-${environmentId}-product`, + `environments-${environmentId}-surveys`, + `environments-${environmentId}-product`, personId, ]; const getSurveysCacheKey = (environmentId: string, personId: string): string[] => [ - `env-${environmentId}-person-${personId}-syncSurveys`, + `environments-${environmentId}-person-${personId}-syncSurveys`, ]; export const getSurveysCached = (environmentId: string, person: TPerson) => @@ -164,6 +164,7 @@ export const getSurveys = async (environmentId: string, person: TPerson): Promis }) .map((survey) => ({ ...survey, + singleUse: survey.singleUse ? JSON.parse(JSON.stringify(survey.singleUse)) : null, triggers: survey.triggers.map((trigger) => trigger.eventClass), attributeFilters: survey.attributeFilters.map((af) => ({ ...af, diff --git a/apps/web/app/api/v1/js/sync/lib/sync.ts b/apps/web/app/api/v1/js/sync/lib/sync.ts index e1b4385c31..e865231f6e 100644 --- a/apps/web/app/api/v1/js/sync/lib/sync.ts +++ b/apps/web/app/api/v1/js/sync/lib/sync.ts @@ -1,7 +1,7 @@ import { getSurveysCached } from "@/app/api/v1/js/surveys"; import { MAU_LIMIT } from "@formbricks/lib/constants"; -import { getActionClassesCached } from "@formbricks/lib/services/actionClass"; -import { getEnvironmentCached } from "@formbricks/lib/services/environment"; +import { getActionClasses } from "@formbricks/lib/actionClass/service"; +import { getEnvironment } from "@formbricks/lib/services/environment"; import { createPerson, getMonthlyActivePeopleCount, getPersonCached } from "@formbricks/lib/services/person"; import { getProductByEnvironmentIdCached } from "@formbricks/lib/services/product"; import { createSession, extendSession, getSessionCached } from "@formbricks/lib/services/session"; @@ -26,7 +26,7 @@ export const getUpdatedState = async ( let session: TSession | null; // check if environment exists - environment = await getEnvironmentCached(environmentId); + environment = await getEnvironment(environmentId); if (!environment) { throw new Error("Environment does not exist"); @@ -101,7 +101,7 @@ export const getUpdatedState = async ( // get/create rest of the state const [surveys, noCodeActionClasses, product] = await Promise.all([ getSurveysCached(environmentId, person), - getActionClassesCached(environmentId), + getActionClasses(environmentId), getProductByEnvironmentIdCached(environmentId), ]); diff --git a/apps/web/app/api/v1/management/action-classes/[actionClassId]/route.ts b/apps/web/app/api/v1/management/action-classes/[actionClassId]/route.ts index 8702de259a..8c1d26eb11 100644 --- a/apps/web/app/api/v1/management/action-classes/[actionClassId]/route.ts +++ b/apps/web/app/api/v1/management/action-classes/[actionClassId]/route.ts @@ -1,6 +1,6 @@ import { responses } from "@/lib/api/response"; import { NextResponse } from "next/server"; -import { deleteActionClass, getActionClass, updateActionClass } from "@formbricks/lib/services/actionClass"; +import { deleteActionClass, getActionClass, updateActionClass } from "@formbricks/lib/actionClass/service"; import { TActionClass, ZActionClassInput } from "@formbricks/types/v1/actionClasses"; import { authenticateRequest } from "@/app/api/v1/auth"; import { transformErrorToDetails } from "@/lib/api/validator"; diff --git a/apps/web/app/api/v1/management/action-classes/route.ts b/apps/web/app/api/v1/management/action-classes/route.ts index 89d0fe72bf..ac8d492c06 100644 --- a/apps/web/app/api/v1/management/action-classes/route.ts +++ b/apps/web/app/api/v1/management/action-classes/route.ts @@ -3,7 +3,7 @@ import { DatabaseError } from "@formbricks/types/v1/errors"; import { authenticateRequest } from "@/app/api/v1/auth"; import { NextResponse } from "next/server"; import { TActionClass, ZActionClassInput } from "@formbricks/types/v1/actionClasses"; -import { createActionClass, getActionClasses } from "@formbricks/lib/services/actionClass"; +import { createActionClass, getActionClasses } from "@formbricks/lib/actionClass/service"; import { transformErrorToDetails } from "@/lib/api/validator"; export async function GET(request: Request) { diff --git a/apps/web/app/api/v1/management/responses/[responseId]/route.ts b/apps/web/app/api/v1/management/responses/[responseId]/route.ts index ac1325f890..4158e05bc0 100644 --- a/apps/web/app/api/v1/management/responses/[responseId]/route.ts +++ b/apps/web/app/api/v1/management/responses/[responseId]/route.ts @@ -1,10 +1,10 @@ import { responses } from "@/lib/api/response"; import { NextResponse } from "next/server"; import { transformErrorToDetails } from "@/lib/api/validator"; -import { deleteResponse, getResponse, updateResponse } from "@formbricks/lib/services/response"; +import { deleteResponse, getResponse, updateResponse } from "@formbricks/lib/response/service"; import { TResponse, ZResponseUpdateInput } from "@formbricks/types/v1/responses"; -import { hasUserEnvironmentAccess } from "@/lib/api/apiHelper"; -import { getSurvey } from "@formbricks/lib/services/survey"; +import { hasUserEnvironmentAccess } from "@formbricks/lib/environment/auth"; +import { getSurvey } from "@formbricks/lib/survey/service"; import { authenticateRequest } from "@/app/api/v1/auth"; import { handleErrorResponse } from "@/app/api/v1/auth"; @@ -21,7 +21,7 @@ const canUserAccessResponse = async (authentication: any, response: TResponse): if (!survey) return false; if (authentication.type === "session") { - return await hasUserEnvironmentAccess(authentication.session.user, survey.environmentId); + return await hasUserEnvironmentAccess(authentication.session.user.id, survey.environmentId); } else if (authentication.type === "apiKey") { return survey.environmentId === authentication.environmentId; } else { diff --git a/apps/web/app/api/v1/management/responses/route.ts b/apps/web/app/api/v1/management/responses/route.ts index 087cc40809..3fab5f3a3b 100644 --- a/apps/web/app/api/v1/management/responses/route.ts +++ b/apps/web/app/api/v1/management/responses/route.ts @@ -1,5 +1,5 @@ import { responses } from "@/lib/api/response"; -import { getEnvironmentResponses } from "@formbricks/lib/services/response"; +import { getEnvironmentResponses } from "@formbricks/lib/response/service"; import { authenticateRequest } from "@/app/api/v1/auth"; import { DatabaseError } from "@formbricks/types/v1/errors"; diff --git a/apps/web/app/api/v1/management/surveys/[surveyId]/route.ts b/apps/web/app/api/v1/management/surveys/[surveyId]/route.ts index c25e2ec9a1..cc096f9caa 100644 --- a/apps/web/app/api/v1/management/surveys/[surveyId]/route.ts +++ b/apps/web/app/api/v1/management/surveys/[surveyId]/route.ts @@ -1,6 +1,6 @@ import { responses } from "@/lib/api/response"; import { NextResponse } from "next/server"; -import { getSurvey, updateSurvey, deleteSurvey } from "@formbricks/lib/services/survey"; +import { getSurvey, updateSurvey, deleteSurvey } from "@formbricks/lib/survey/service"; import { TSurvey, ZSurveyInput } from "@formbricks/types/v1/surveys"; import { transformErrorToDetails } from "@/lib/api/validator"; import { authenticateRequest } from "@/app/api/v1/auth"; diff --git a/apps/web/app/api/v1/management/surveys/route.ts b/apps/web/app/api/v1/management/surveys/route.ts index 1ced6ec5d9..4a7d3eb939 100644 --- a/apps/web/app/api/v1/management/surveys/route.ts +++ b/apps/web/app/api/v1/management/surveys/route.ts @@ -2,7 +2,7 @@ import { responses } from "@/lib/api/response"; import { authenticateRequest } from "@/app/api/v1/auth"; import { NextResponse } from "next/server"; import { transformErrorToDetails } from "@/lib/api/validator"; -import { createSurvey, getSurveys } from "@formbricks/lib/services/survey"; +import { createSurvey, getSurveys } from "@formbricks/lib/survey/service"; import { ZSurveyInput } from "@formbricks/types/v1/surveys"; import { DatabaseError } from "@formbricks/types/v1/errors"; diff --git a/apps/web/app/api/v1/users/route.ts b/apps/web/app/api/v1/users/route.ts index 148df1729e..b4352157eb 100644 --- a/apps/web/app/api/v1/users/route.ts +++ b/apps/web/app/api/v1/users/route.ts @@ -1,15 +1,17 @@ import { sendInviteAcceptedEmail, sendVerificationEmail } from "@/lib/email"; -import { verifyInviteToken } from "@formbricks/lib/jwt"; -import { populateEnvironment } from "@/lib/populate"; import { prisma } from "@formbricks/database"; +import { EMAIL_VERIFICATION_DISABLED, INVITE_DISABLED, SIGNUP_ENABLED } from "@formbricks/lib/constants"; +import { verifyInviteToken } from "@formbricks/lib/jwt"; +import { deleteInvite } from "@formbricks/lib/services/invite"; +import { createMembership } from "@formbricks/lib/services/membership"; +import { createProduct } from "@formbricks/lib/services/product"; +import { createProfile } from "@formbricks/lib/services/profile"; +import { createTeam } from "@formbricks/lib/services/team"; import { NextResponse } from "next/server"; -import { env } from "@/env.mjs"; -import { Prisma } from "@prisma/client"; -import { INTERNAL_SECRET, WEBAPP_URL } from "@formbricks/lib/constants"; export async function POST(request: Request) { let { inviteToken, ...user } = await request.json(); - if (inviteToken ? env.NEXT_PUBLIC_INVITE_DISABLED === "1" : env.NEXT_PUBLIC_SIGNUP_DISABLED === "1") { + if (inviteToken ? INVITE_DISABLED : !SIGNUP_ENABLED) { return NextResponse.json({ error: "Signup disabled" }, { status: 403 }); } user = { ...user, ...{ email: user.email.toLowerCase() } }; @@ -17,7 +19,6 @@ export async function POST(request: Request) { let inviteId; try { - let data: Prisma.UserCreateArgs; let invite; if (inviteToken) { @@ -35,92 +36,35 @@ export async function POST(request: Request) { return NextResponse.json({ error: "Invalid invite ID" }, { status: 400 }); } - data = { - data: { - ...user, - memberships: { - create: { - accepted: true, - role: invite.role, - team: { - connect: { - id: invite.teamId, - }, - }, - }, - }, - }, - }; - } else { - data = { - data: { - ...user, - memberships: { - create: [ - { - accepted: true, - role: "owner", - team: { - create: { - name: `${user.name}'s Team`, - products: { - create: [ - { - name: "My Product", - environments: { - create: [ - { - type: "production", - ...populateEnvironment, - }, - { - type: "development", - ...populateEnvironment, - }, - ], - }, - }, - ], - }, - }, - }, - }, - ], - }, - }, - }; - } + // create a user and assign him to the team - type UserWithMemberships = Prisma.UserGetPayload<{ include: { memberships: true } }>; - - const userData = (await prisma.user.create({ - ...data, - include: { - memberships: true, - }, - // TODO: This is a hack to get the correct types (casting), we should find a better way to do this - })) as UserWithMemberships; - - const teamId = userData.memberships[0].teamId; - - if (teamId) { - fetch(`${WEBAPP_URL}/api/v1/teams/${teamId}/add_demo_product`, { - method: "POST", - headers: { - "x-api-key": INTERNAL_SECRET, - }, + const profile = await createProfile(user); + await createMembership(invite.teamId, profile.id, { + accepted: true, + role: invite.role, }); - } - if (inviteId) { - sendInviteAcceptedEmail(invite.creator.name, user.name, invite.creator.email); - await prisma.invite.delete({ where: { id: inviteId } }); - } + if (!EMAIL_VERIFICATION_DISABLED) { + await sendVerificationEmail(profile); + } - if (env.NEXT_PUBLIC_EMAIL_VERIFICATION_DISABLED !== "1") { - await sendVerificationEmail(userData); + await sendInviteAcceptedEmail(invite.creator.name, user.name, invite.creator.email); + await deleteInvite(inviteId); + + return NextResponse.json(profile); + } else { + const team = await createTeam({ + name: `${user.name}'s Team`, + }); + await createProduct(team.id, { name: "My Product" }); + const profile = await createProfile(user); + await createMembership(team.id, profile.id, { role: "owner", accepted: true }); + + if (!EMAIL_VERIFICATION_DISABLED) { + await sendVerificationEmail(profile); + } + return NextResponse.json(profile); } - return NextResponse.json(userData); } catch (e) { if (e.code === "P2002") { return NextResponse.json( diff --git a/apps/web/app/api/v1/webhooks/[webhookId]/route.ts b/apps/web/app/api/v1/webhooks/[webhookId]/route.ts index e500401fcd..f0d51dcba9 100644 --- a/apps/web/app/api/v1/webhooks/[webhookId]/route.ts +++ b/apps/web/app/api/v1/webhooks/[webhookId]/route.ts @@ -1,5 +1,5 @@ import { responses } from "@/lib/api/response"; -import { getApiKeyFromKey } from "@formbricks/lib/services/apiKey"; +import { getApiKeyFromKey } from "@formbricks/lib/apiKey/service"; import { deleteWebhook, getWebhook } from "@formbricks/lib/services/webhook"; import { headers } from "next/headers"; diff --git a/apps/web/app/api/v1/webhooks/route.ts b/apps/web/app/api/v1/webhooks/route.ts index 31d2d77a88..ae1fd52d05 100644 --- a/apps/web/app/api/v1/webhooks/route.ts +++ b/apps/web/app/api/v1/webhooks/route.ts @@ -1,7 +1,7 @@ import { responses } from "@/lib/api/response"; import { transformErrorToDetails } from "@/lib/api/validator"; +import { getApiKeyFromKey } from "@formbricks/lib/apiKey/service"; import { DatabaseError, InvalidInputError } from "@formbricks/types/v1/errors"; -import { getApiKeyFromKey } from "@formbricks/lib/services/apiKey"; import { createWebhook, getWebhooks } from "@formbricks/lib/services/webhook"; import { ZWebhookInput } from "@formbricks/types/v1/webhooks"; import { headers } from "next/headers"; diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsx index 8c0a36a8b7..e6489cb9d8 100644 --- a/apps/web/app/page.tsx +++ b/apps/web/app/page.tsx @@ -1,28 +1,10 @@ import ClientLogout from "@/app/ClientLogout"; import { authOptions } from "@/app/api/auth/[...nextauth]/authOptions"; -import { WEBAPP_URL } from "@formbricks/lib/constants"; +import { getFirstEnvironmentByUserId } from "@formbricks/lib/services/environment"; import type { Session } from "next-auth"; import { getServerSession } from "next-auth"; -import { headers } from "next/headers"; import { redirect } from "next/navigation"; -async function getEnvironment() { - const cookie = headers().get("cookie") || ""; - const res = await fetch(`${WEBAPP_URL}/api/v1/environments/find-first`, { - headers: { - cookie, - }, - }); - - if (!res.ok) { - const error = await res.json(); - console.error(error); - throw new Error("Failed to fetch data"); - } - - return res.json(); -} - export default async function Home() { const session: Session | null = await getServerSession(authOptions); @@ -36,7 +18,10 @@ export default async function Home() { let environment; try { - environment = await getEnvironment(); + environment = await getFirstEnvironmentByUserId(session?.user.id); + if (!environment) { + throw new Error("No environment found"); + } } catch (error) { console.error("error getting environment", error); } diff --git a/apps/web/app/s/[surveyId]/LegalFooter.tsx b/apps/web/app/s/[surveyId]/LegalFooter.tsx index 583d4582ef..dbe33b4815 100644 --- a/apps/web/app/s/[surveyId]/LegalFooter.tsx +++ b/apps/web/app/s/[surveyId]/LegalFooter.tsx @@ -1,19 +1,19 @@ -import { env } from "@/env.mjs"; +import { IMPRINT_URL, PRIVACY_URL } from "@formbricks/lib/constants"; import Link from "next/link"; export default function LegalFooter() { - if (!env.NEXT_PUBLIC_IMPRINT_URL && !env.NEXT_PUBLIC_PRIVACY_URL) return null; + if (!IMPRINT_URL && !PRIVACY_URL) return null; return (
    - {env.NEXT_PUBLIC_IMPRINT_URL && ( - + {IMPRINT_URL && ( + Imprint )} - {env.NEXT_PUBLIC_IMPRINT_URL && env.NEXT_PUBLIC_PRIVACY_URL && | } - {env.NEXT_PUBLIC_PRIVACY_URL && ( - + {IMPRINT_URL && PRIVACY_URL && | } + {PRIVACY_URL && ( + Privacy Policy )} diff --git a/apps/web/app/s/[surveyId]/LinkSurvey.tsx b/apps/web/app/s/[surveyId]/LinkSurvey.tsx index 626e34c769..242b04d463 100644 --- a/apps/web/app/s/[surveyId]/LinkSurvey.tsx +++ b/apps/web/app/s/[surveyId]/LinkSurvey.tsx @@ -3,7 +3,6 @@ import ContentWrapper from "@/components/shared/ContentWrapper"; import { SurveyInline } from "@/components/shared/Survey"; import { createDisplay } from "@formbricks/lib/client/display"; -import { WEBAPP_URL } from "@formbricks/lib/constants"; import { ResponseQueue } from "@formbricks/lib/responseQueue"; import { SurveyState } from "@formbricks/lib/surveyState"; import { TProduct } from "@formbricks/types/v1/product"; @@ -13,7 +12,8 @@ import { useSearchParams } from "next/navigation"; import { useEffect, useMemo, useState } from "react"; import VerifyEmail from "@/app/s/[surveyId]/VerifyEmail"; import { getPrefillResponseData } from "@/app/s/[surveyId]/prefilling"; -import { TResponseData } from "@formbricks/types/v1/responses"; +import { TResponse, TResponseData } from "@formbricks/types/v1/responses"; +import SurveyLinkUsed from "@/app/s/[surveyId]/SurveyLinkUsed"; interface LinkSurveyProps { survey: TSurvey; @@ -21,6 +21,9 @@ interface LinkSurveyProps { personId?: string; emailVerificationStatus?: string; prefillAnswer?: string; + singleUseId?: string; + singleUseResponse?: TResponse; + webAppUrl: string; } export default function LinkSurvey({ @@ -29,10 +32,15 @@ export default function LinkSurvey({ personId, emailVerificationStatus, prefillAnswer, + singleUseId, + singleUseResponse, + webAppUrl, }: LinkSurveyProps) { + const responseId = singleUseResponse?.id; const searchParams = useSearchParams(); const isPreview = searchParams?.get("preview") === "true"; - const [surveyState, setSurveyState] = useState(new SurveyState(survey.id)); + // pass in the responseId if the survey is a single use survey, ensures survey state is updated with the responseId + const [surveyState, setSurveyState] = useState(new SurveyState(survey.id, singleUseId, responseId)); const [activeQuestionId, setActiveQuestionId] = useState(survey.questions[0].id); const prefillResponseData: TResponseData | undefined = prefillAnswer ? getPrefillResponseData(survey.questions[0], survey, prefillAnswer) @@ -42,7 +50,7 @@ export default function LinkSurvey({ () => new ResponseQueue( { - apiHost: WEBAPP_URL, + apiHost: webAppUrl, retryAttempts: 2, onResponseSendingFailed: (response) => { alert(`Failed to send response: ${JSON.stringify(response, null, 2)}`); @@ -52,9 +60,16 @@ export default function LinkSurvey({ }, surveyState ), - [] + [personId, webAppUrl] ); const [autoFocus, setAutofocus] = useState(false); + const hasFinishedSingleUseResponse = useMemo(() => { + if (singleUseResponse && singleUseResponse.finished) { + return true; + } + return false; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); // Not in an iframe, enable autofocus on input fields. useEffect(() => { @@ -63,6 +78,14 @@ export default function LinkSurvey({ } }, []); + useEffect(() => { + responseQueue.updateSurveyState(surveyState); + }, [responseQueue, surveyState]); + + if (!surveyState.isResponseFinished() && hasFinishedSingleUseResponse) { + return ; + } + if (emailVerificationStatus && emailVerificationStatus !== "verified") { if (emailVerificationStatus === "fishy") { return ; @@ -89,9 +112,16 @@ export default function LinkSurvey({ survey={survey} brandColor={product.brandColor} formbricksSignature={product.formbricksSignature} - onDisplay={() => createDisplay({ surveyId: survey.id }, window?.location?.origin)} + onDisplay={async () => { + if (!isPreview) { + const { id } = await createDisplay({ surveyId: survey.id }, webAppUrl); + const newSurveyState = surveyState.copy(); + newSurveyState.updateDisplayId(id); + setSurveyState(newSurveyState); + } + }} onResponse={(responseUpdate) => { - responseQueue.add(responseUpdate); + !isPreview && responseQueue.add(responseUpdate); }} onActiveQuestionChange={(questionId) => setActiveQuestionId(questionId)} activeQuestionId={activeQuestionId} diff --git a/apps/web/app/s/[surveyId]/SurveyInactive.tsx b/apps/web/app/s/[surveyId]/SurveyInactive.tsx index 1796b10665..233fca2be8 100644 --- a/apps/web/app/s/[surveyId]/SurveyInactive.tsx +++ b/apps/web/app/s/[surveyId]/SurveyInactive.tsx @@ -1,6 +1,6 @@ import { TSurveyClosedMessage } from "@formbricks/types/v1/surveys"; import { Button } from "@formbricks/ui"; -import { CheckCircleIcon, PauseCircleIcon } from "@heroicons/react/24/solid"; +import { CheckCircleIcon, PauseCircleIcon, QuestionMarkCircleIcon } from "@heroicons/react/24/solid"; import Image from "next/image"; import Link from "next/link"; import footerLogo from "./footerlogo.svg"; @@ -9,17 +9,19 @@ const SurveyInactive = ({ status, surveyClosedMessage, }: { - status: "paused" | "completed"; + status: "paused" | "completed" | "link invalid"; surveyClosedMessage?: TSurveyClosedMessage | null; }) => { const icons = { paused: , completed: , + "link invalid": , }; const descriptions = { paused: "This free & open-source survey is temporarily paused.", completed: "This free & open-source survey has been closed.", + "link invalid": "This survey can only be taken by invitation.", }; return ( @@ -31,12 +33,11 @@ const SurveyInactive = ({ {status === "completed" && surveyClosedMessage ? surveyClosedMessage.heading : `Survey ${status}.`}

    - {" "} {status === "completed" && surveyClosedMessage ? surveyClosedMessage.subheading : descriptions[status]}

    - {!(status === "completed" && surveyClosedMessage) && ( + {!(status === "completed" && surveyClosedMessage) && status !== "link invalid" && ( diff --git a/apps/web/app/s/[surveyId]/SurveyLinkUsed.tsx b/apps/web/app/s/[surveyId]/SurveyLinkUsed.tsx new file mode 100644 index 0000000000..c9f694622b --- /dev/null +++ b/apps/web/app/s/[surveyId]/SurveyLinkUsed.tsx @@ -0,0 +1,35 @@ +import { SurveySingleUse } from "@formbricks/types/surveys"; +import { CheckCircleIcon } from "@heroicons/react/24/solid"; +import Image from "next/image"; +import Link from "next/link"; +import footerLogo from "./footerlogo.svg"; + +type SurveyLinkUsedProps = { + singleUseMessage: Omit | null; +}; + +const SurveyLinkUsed = ({ singleUseMessage }: SurveyLinkUsedProps) => { + const defaultHeading = "The survey has already been answered."; + const defaultSubheading = "You can only use this link once."; + return ( +
    +
    +
    + +

    + {!!singleUseMessage?.heading ? singleUseMessage?.heading : defaultHeading} +

    +

    + {!!singleUseMessage?.subheading ? singleUseMessage?.subheading : defaultSubheading} +

    +
    +
    + + Brand logo + +
    +
    + ); +}; + +export default SurveyLinkUsed; diff --git a/apps/web/app/s/[surveyId]/page.tsx b/apps/web/app/s/[surveyId]/page.tsx index 5a427d9936..43a4940dc3 100644 --- a/apps/web/app/s/[surveyId]/page.tsx +++ b/apps/web/app/s/[surveyId]/page.tsx @@ -2,16 +2,33 @@ export const revalidate = REVALIDATION_INTERVAL; import LinkSurvey from "@/app/s/[surveyId]/LinkSurvey"; import SurveyInactive from "@/app/s/[surveyId]/SurveyInactive"; -import { REVALIDATION_INTERVAL } from "@formbricks/lib/constants"; +import { REVALIDATION_INTERVAL, WEBAPP_URL } from "@formbricks/lib/constants"; import { getOrCreatePersonByUserId } from "@formbricks/lib/services/person"; import { getProductByEnvironmentId } from "@formbricks/lib/services/product"; -import { getSurvey } from "@formbricks/lib/services/survey"; +import { getSurvey } from "@formbricks/lib/survey/service"; import { getEmailVerificationStatus } from "./helpers"; import { checkValidity } from "@/app/s/[surveyId]/prefilling"; import { notFound } from "next/navigation"; +import { getResponseBySingleUseId } from "@formbricks/lib/response/service"; +import { TResponse } from "@formbricks/types/v1/responses"; +import { validateSurveySingleUseId } from "@/lib/singleUseSurveys"; -export default async function LinkSurveyPage({ params, searchParams }) { +interface LinkSurveyPageProps { + params: { + surveyId: string; + }; + searchParams: { + suId?: string; + userId?: string; + verify?: string; + }; +} + +export default async function LinkSurveyPage({ params, searchParams }: LinkSurveyPageProps) { const survey = await getSurvey(params.surveyId); + const suId = searchParams.suId; + const isSingleUseSurvey = survey?.singleUse?.enabled; + const isSingleUseSurveyEncrypted = survey?.singleUse?.isEncrypted; if (!survey || survey.type !== "link" || survey.status === "draft") { notFound(); @@ -30,14 +47,41 @@ export default async function LinkSurveyPage({ params, searchParams }) { ); } + let singleUseId: string | undefined = undefined; + if (isSingleUseSurvey) { + // check if the single use id is present for single use surveys + if (!suId) { + return ; + } + + // if encryption is enabled, validate the single use id + let validatedSingleUseId: string | undefined = undefined; + if (isSingleUseSurveyEncrypted) { + validatedSingleUseId = validateSurveySingleUseId(suId); + if (!validatedSingleUseId) { + return ; + } + } + // if encryption is disabled, use the suId as is + singleUseId = validatedSingleUseId ?? suId; + } + + let singleUseResponse: TResponse | undefined = undefined; + if (isSingleUseSurvey) { + singleUseResponse = (await getResponseBySingleUseId(survey.id, singleUseId)) ?? undefined; + } + // verify email: Check if the survey requires email verification - let emailVerificationStatus; + let emailVerificationStatus: string | undefined = undefined; if (survey.verifyEmail) { const token = searchParams && Object.keys(searchParams).length !== 0 && searchParams.hasOwnProperty("verify") ? searchParams.verify : undefined; - emailVerificationStatus = await getEmailVerificationStatus(survey.id, token); + + if (token) { + emailVerificationStatus = await getEmailVerificationStatus(survey.id, token); + } } // get product and person @@ -59,6 +103,9 @@ export default async function LinkSurveyPage({ params, searchParams }) { personId={person?.id} emailVerificationStatus={emailVerificationStatus} prefillAnswer={isPrefilledAnswerValid ? prefillAnswer : null} + singleUseId={isSingleUseSurvey ? singleUseId : undefined} + singleUseResponse={singleUseResponse ? singleUseResponse : undefined} + webAppUrl={WEBAPP_URL} /> ); } diff --git a/apps/web/components/auth/SigninForm.tsx b/apps/web/components/auth/SigninForm.tsx index 6f0c15fe61..8f205693dd 100644 --- a/apps/web/components/auth/SigninForm.tsx +++ b/apps/web/components/auth/SigninForm.tsx @@ -1,7 +1,6 @@ "use client"; import { GoogleButton } from "@/components/auth/GoogleButton"; -import { env } from "@/env.mjs"; import { Button, PasswordInput } from "@formbricks/ui"; import { XCircleIcon } from "@heroicons/react/24/solid"; import { signIn } from "next-auth/react"; @@ -10,7 +9,17 @@ import { useSearchParams } from "next/navigation"; import { useRef, useState } from "react"; import { GithubButton } from "./GithubButton"; -export const SigninForm = () => { +export const SigninForm = ({ + publicSignUpEnabled, + passwordResetEnabled, + googleOAuthEnabled, + githubOAuthEnabled, +}: { + publicSignUpEnabled: boolean; + passwordResetEnabled: boolean; + googleOAuthEnabled: boolean; + githubOAuthEnabled: boolean; +}) => { const searchParams = useSearchParams(); const emailRef = useRef(null); @@ -79,7 +88,7 @@ export const SigninForm = () => { className="focus:border-brand focus:ring-brand block w-full rounded-md border-slate-300 shadow-sm sm:text-sm" />
    - {env.NEXT_PUBLIC_PASSWORD_RESET_DISABLED !== "1" && isPasswordFocused && ( + {passwordResetEnabled && isPasswordFocused && (
    { - {env.NEXT_PUBLIC_GOOGLE_AUTH_ENABLED === "1" && ( + {googleOAuthEnabled && ( <> )} - {env.NEXT_PUBLIC_GITHUB_AUTH_ENABLED === "1" && ( + {githubOAuthEnabled && ( <> )}
    - {env.NEXT_PUBLIC_SIGNUP_DISABLED !== "1" && ( + {publicSignUpEnabled && (
    New to Formbricks?
    diff --git a/apps/web/components/auth/SignupForm.tsx b/apps/web/components/auth/SignupForm.tsx index 4e69aced10..9ec41de945 100644 --- a/apps/web/components/auth/SignupForm.tsx +++ b/apps/web/components/auth/SignupForm.tsx @@ -2,7 +2,6 @@ import { GoogleButton } from "@/components/auth/GoogleButton"; import IsPasswordValid from "@/components/auth/IsPasswordValid"; -import { env } from "@/env.mjs"; import { createUser } from "@/lib/users/users"; import { Button, PasswordInput } from "@formbricks/ui"; import { XCircleIcon } from "@heroicons/react/24/solid"; @@ -11,7 +10,23 @@ import { useRouter, useSearchParams } from "next/navigation"; import { useMemo, useRef, useState } from "react"; import { GithubButton } from "./GithubButton"; -export const SignupForm = () => { +export const SignupForm = ({ + webAppUrl, + privacyUrl, + termsUrl, + passwordResetEnabled, + emailVerificationDisabled, + googleOAuthEnabled, + githubOAuthEnabled, +}: { + webAppUrl: string; + privacyUrl: string | undefined; + termsUrl: string | undefined; + passwordResetEnabled: boolean; + emailVerificationDisabled: boolean; + googleOAuthEnabled: boolean; + githubOAuthEnabled: boolean; +}) => { const searchParams = useSearchParams(); const router = useRouter(); const [error, setError] = useState(""); @@ -19,15 +34,13 @@ export const SignupForm = () => { const nameRef = useRef(null); const inviteToken = searchParams?.get("inviteToken"); - // const callbackUrl = env.NEXT_PUBLIC_WEBAPP_URL + "/invite?token=" + inviteToken; - const callbackUrl = useMemo(() => { if (inviteToken) { - return env.NEXT_PUBLIC_WEBAPP_URL + "/invite?token=" + inviteToken; + return webAppUrl + "/invite?token=" + inviteToken; } else { - return env.NEXT_PUBLIC_WEBAPP_URL; + return webAppUrl; } - }, [inviteToken]); + }, [inviteToken, webAppUrl]); const handleSubmit = async (e: any) => { e.preventDefault(); @@ -45,10 +58,9 @@ export const SignupForm = () => { e.target.elements.password.value, inviteToken ); - const url = - env.NEXT_PUBLIC_EMAIL_VERIFICATION_DISABLED === "1" - ? `/auth/signup-without-verification-success` - : `/auth/verification-requested?email=${encodeURIComponent(e.target.elements.email.value)}`; + const url = emailVerificationDisabled + ? `/auth/signup-without-verification-success` + : `/auth/verification-requested?email=${encodeURIComponent(e.target.elements.email.value)}`; router.push(url); } catch (e: any) { @@ -144,7 +156,7 @@ export const SignupForm = () => { className="focus:border-brand focus:ring-brand block w-full rounded-md shadow-sm sm:text-sm" />
    - {env.NEXT_PUBLIC_PASSWORD_RESET_DISABLED !== "1" && isPasswordFocused && ( + {passwordResetEnabled && isPasswordFocused && (
    { - {env.NEXT_PUBLIC_GOOGLE_AUTH_ENABLED === "1" && ( + {googleOAuthEnabled && ( <> )} - {env.NEXT_PUBLIC_GITHUB_AUTH_ENABLED === "1" && ( + {githubOAuthEnabled && ( <> )}
    - {(env.NEXT_PUBLIC_TERMS_URL || env.NEXT_PUBLIC_PRIVACY_URL) && ( + {(termsUrl || privacyUrl) && (
    By signing up, you agree to our
    - {env.NEXT_PUBLIC_TERMS_URL && ( - + {termsUrl && ( + Terms of Service )} - {env.NEXT_PUBLIC_TERMS_URL && env.NEXT_PUBLIC_PRIVACY_URL && and } - {env.NEXT_PUBLIC_PRIVACY_URL && ( - + {termsUrl && privacyUrl && and } + {privacyUrl && ( + Privacy Policy. )} diff --git a/apps/web/components/environments/SecondNavBar.tsx b/apps/web/components/environments/SecondNavBar.tsx index 96b3b32e8c..f825f92710 100644 --- a/apps/web/components/environments/SecondNavBar.tsx +++ b/apps/web/components/environments/SecondNavBar.tsx @@ -1,27 +1,39 @@ import { cn } from "@formbricks/lib/cn"; import SurveyNavBarName from "@/components/shared/SurveyNavBarName"; import Link from "next/link"; +import { getProductByEnvironmentId } from "@formbricks/lib/services/product"; +import { getSurvey } from "@formbricks/lib/survey/service"; interface SecondNavbarProps { tabs: { id: string; label: string; href: string; icon?: React.ReactNode }[]; activeId: string; surveyId?: string; - environmentId?: string; + environmentId: string; } -export default function SecondNavbar({ +export default async function SecondNavbar({ tabs, activeId, surveyId, environmentId, ...props }: SecondNavbarProps) { + const product = await getProductByEnvironmentId(environmentId!); + if (!product) { + throw new Error("Product not found"); + } + + let survey; + if (surveyId) { + survey = await getSurvey(surveyId); + } + return (
    - {surveyId && environmentId && ( - + {survey && environmentId && ( + )}
    {" "}