Compare commits

..

3 Commits

Author SHA1 Message Date
Johannes
590c85d1ca add sources UI 2026-01-28 08:54:52 +04:00
Harsh Bhat
39c99baaac feat: Add mock data and UI for taxanomy & knowledge 2026-01-27 16:12:19 +04:00
Harsh Bhat
238b2adf3f feat: Unify POC hackathon 2026-01-27 14:58:20 +04:00
544 changed files with 16447 additions and 26561 deletions

View File

@@ -184,13 +184,8 @@ ENTERPRISE_LICENSE_KEY=
# Ignore Rate Limiting across the Formbricks app
# RATE_LIMITING_DISABLED=1
# OpenTelemetry OTLP endpoint (base URL, exporters append /v1/traces and /v1/metrics)
# OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
# OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
# OTEL_SERVICE_NAME=formbricks
# OTEL_RESOURCE_ATTRIBUTES=deployment.environment=development
# OTEL_TRACES_SAMPLER=parentbased_traceidratio
# OTEL_TRACES_SAMPLER_ARG=1
# OpenTelemetry URL for tracing
# OPENTELEMETRY_LISTENER_URL=http://localhost:4318/v1/traces
# Unsplash API Key
UNSPLASH_ACCESS_KEY=

View File

@@ -65,8 +65,8 @@ jobs:
set -euo pipefail
echo "Updating Chart.yaml with version: ${VERSION}"
yq -i ".version = \"${VERSION}\"" charts/formbricks/Chart.yaml
yq -i ".appVersion = \"${VERSION}\"" charts/formbricks/Chart.yaml
yq -i ".version = \"${VERSION}\"" helm-chart/Chart.yaml
yq -i ".appVersion = \"${VERSION}\"" helm-chart/Chart.yaml
echo "✅ Successfully updated Chart.yaml"
@@ -77,7 +77,7 @@ jobs:
set -euo pipefail
echo "Packaging Helm chart version: ${VERSION}"
helm package ./charts/formbricks
helm package ./helm-chart
echo "✅ Successfully packaged formbricks-${VERSION}.tgz"

View File

@@ -9,7 +9,6 @@ on:
merge_group:
permissions:
contents: read
pull-requests: read
jobs:
sonarqube:
name: SonarQube
@@ -51,9 +50,6 @@ jobs:
pnpm test:coverage
- name: SonarQube Scan
uses: SonarSource/sonarqube-scan-action@2500896589ef8f7247069a56136f8dc177c27ccf
with:
args: >
-Dsonar.verbose=true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}

View File

@@ -6,9 +6,19 @@ permissions:
on:
pull_request:
types: [opened, synchronize, reopened]
paths:
- "apps/web/**/*.ts"
- "apps/web/**/*.tsx"
- "apps/web/locales/**/*.json"
- "scan-translations.ts"
push:
branches:
- main
paths:
- "apps/web/**/*.ts"
- "apps/web/**/*.tsx"
- "apps/web/locales/**/*.json"
- "scan-translations.ts"
jobs:
validate-translations:
@@ -22,39 +32,32 @@ jobs:
with:
egress-policy: audit
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Checkout repository
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Check for relevant changes
id: changes
uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
- name: Setup Node.js
uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0
with:
filters: |
translations:
- 'apps/web/**/*.ts'
- 'apps/web/**/*.tsx'
- 'apps/web/locales/**/*.json'
- 'packages/surveys/src/**/*.{ts,tsx}'
- 'packages/surveys/locales/**/*.json'
- 'packages/email/**/*.{ts,tsx}'
node-version: 18
- name: Setup Node.js 22.x
if: steps.changes.outputs.translations == 'true'
uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af
- name: Setup pnpm
uses: pnpm/action-setup@a3252b78c470c02df07e9d59298aecedc3ccdd6d # v3.0.0
with:
node-version: 22.x
- name: Install pnpm
if: steps.changes.outputs.translations == 'true'
uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4.1.0
version: 9.15.9
- name: Install dependencies
if: steps.changes.outputs.translations == 'true'
run: pnpm install --config.platform=linux --config.architecture=x64
run: pnpm install --frozen-lockfile
- name: Validate translation keys
if: steps.changes.outputs.translations == 'true'
run: pnpm run scan-translations
run: |
echo ""
echo "🔍 Validating translation keys..."
echo ""
pnpm run scan-translations
- name: Skip (no translation-related changes)
if: steps.changes.outputs.translations != 'true'
run: echo "No translation-related files changed — skipping validation."
- name: Summary
if: success()
run: |
echo ""
echo "✅ Translation validation completed successfully!"
echo ""

3
.gitignore vendored
View File

@@ -13,7 +13,6 @@
**/.next/
**/out/
**/build
**/next-env.d.ts
# node
**/dist/
@@ -64,5 +63,3 @@ packages/ios/FormbricksSDK/FormbricksSDK.xcodeproj/project.xcworkspace/xcuserdat
.cursorrules
i18n.cache
stats.html
# next-agents-md
.next-docs/

View File

@@ -1 +1,40 @@
pnpm lint-staged
# Load environment variables from .env files
if [ -f .env ]; then
set -a
. .env
set +a
fi
pnpm lint-staged
# Run Lingo.dev i18n workflow if LINGODOTDEV_API_KEY is set
if [ -n "$LINGODOTDEV_API_KEY" ]; then
echo ""
echo "🌍 Running Lingo.dev translation workflow..."
echo ""
# Run translation generation and validation
if pnpm run i18n; then
echo ""
echo "✅ Translation validation passed"
echo ""
# Add updated locale files to git
git add apps/web/locales/*.json
else
echo ""
echo "❌ Translation validation failed!"
echo ""
echo "Please fix the translation issues above before committing:"
echo " • Add missing translation keys to your locale files"
echo " • Remove unused translation keys"
echo ""
echo "Or run 'pnpm i18n' to see the detailed report"
echo ""
exit 1
fi
else
echo ""
echo "⚠️ Skipping translation validation: LINGODOTDEV_API_KEY is not set"
echo " (This is expected for community contributors)"
echo ""
fi

File diff suppressed because one or more lines are too long

View File

@@ -1,4 +1,20 @@
module.exports = {
extends: ["@formbricks/eslint-config/legacy-next.js"],
ignorePatterns: ["**/package.json", "**/tsconfig.json"],
overrides: [
{
files: ["locales/*.json"],
plugins: ["i18n-json"],
rules: {
"i18n-json/identical-keys": [
"error",
{
filePath: require("path").join(__dirname, "locales", "en-US.json"),
checkExtraKeys: false,
checkMissingKeys: true,
},
],
},
},
],
};

View File

@@ -1,4 +1,4 @@
FROM node:24-alpine3.23 AS base
FROM node:22-alpine3.22 AS base
#
## step 1: Prune monorepo
@@ -20,7 +20,7 @@ FROM base AS installer
# Enable corepack and prepare pnpm
RUN npm install --ignore-scripts -g corepack@latest
RUN corepack enable
RUN corepack prepare pnpm@10.28.2 --activate
RUN corepack prepare pnpm@9.15.9 --activate
# Install necessary build tools and compilers
RUN apk update && apk add --no-cache cmake g++ gcc jq make openssl-dev python3
@@ -69,14 +69,20 @@ RUN --mount=type=secret,id=database_url \
--mount=type=secret,id=sentry_auth_token \
/tmp/read-secrets.sh pnpm build --filter=@formbricks/web...
# Extract Prisma version
RUN jq -r '.devDependencies.prisma' packages/database/package.json > /prisma_version.txt
#
## step 3: setup production runner
#
FROM base AS runner
# Update npm to latest, then create user
# Note: npm's bundled tar has a known vulnerability but npm is only used during build, not at runtime
RUN npm install --ignore-scripts -g npm@latest \
RUN npm install --ignore-scripts -g corepack@latest && \
corepack enable
RUN apk add --no-cache curl \
&& apk add --no-cache supercronic \
# && addgroup --system --gid 1001 nodejs \
&& addgroup -S nextjs \
&& adduser -S -u 1001 -G nextjs nextjs
@@ -107,13 +113,15 @@ RUN chown nextjs:nextjs ./packages/database/schema.prisma && chmod 644 ./package
COPY --from=installer /app/packages/database/dist ./packages/database/dist
RUN chown -R nextjs:nextjs ./packages/database/dist && chmod -R 755 ./packages/database/dist
# Copy prisma client packages
COPY --from=installer /app/node_modules/@prisma/client ./node_modules/@prisma/client
RUN chown -R nextjs:nextjs ./node_modules/@prisma/client && chmod -R 755 ./node_modules/@prisma/client
COPY --from=installer /app/node_modules/.prisma ./node_modules/.prisma
RUN chown -R nextjs:nextjs ./node_modules/.prisma && chmod -R 755 ./node_modules/.prisma
COPY --from=installer /prisma_version.txt .
RUN chown nextjs:nextjs ./prisma_version.txt && chmod 644 ./prisma_version.txt
COPY --from=installer /app/node_modules/@paralleldrive/cuid2 ./node_modules/@paralleldrive/cuid2
RUN chmod -R 755 ./node_modules/@paralleldrive/cuid2
@@ -126,25 +134,7 @@ RUN chmod -R 755 ./node_modules/@noble/hashes
COPY --from=installer /app/node_modules/zod ./node_modules/zod
RUN chmod -R 755 ./node_modules/zod
# Pino loads transport code in worker threads via dynamic require().
# Next.js file tracing only traces static imports, missing runtime-loaded files
# (e.g. pino/lib/transport-stream.js, transport targets).
# Copy the full packages to ensure all runtime files are available.
COPY --from=installer /app/node_modules/pino ./node_modules/pino
RUN chmod -R 755 ./node_modules/pino
COPY --from=installer /app/node_modules/pino-opentelemetry-transport ./node_modules/pino-opentelemetry-transport
RUN chmod -R 755 ./node_modules/pino-opentelemetry-transport
COPY --from=installer /app/node_modules/pino-abstract-transport ./node_modules/pino-abstract-transport
RUN chmod -R 755 ./node_modules/pino-abstract-transport
COPY --from=installer /app/node_modules/otlp-logger ./node_modules/otlp-logger
RUN chmod -R 755 ./node_modules/otlp-logger
# Install prisma CLI globally for database migrations and fix permissions for nextjs user
RUN npm install --ignore-scripts -g prisma@6 \
&& chown -R nextjs:nextjs /usr/local/lib/node_modules/prisma
RUN npm install -g prisma@6
# Create a startup script to handle the conditional logic
COPY --from=installer /app/apps/web/scripts/docker/next-start.sh /home/nextjs/start.sh
@@ -154,8 +144,10 @@ EXPOSE 3000
ENV HOSTNAME="0.0.0.0"
USER nextjs
# Prepare pnpm as the nextjs user to ensure it's available at runtime
# Prepare volumes for uploads and SAML connections
RUN mkdir -p /home/nextjs/apps/web/uploads/ && \
RUN corepack prepare pnpm@9.15.9 --activate && \
mkdir -p /home/nextjs/apps/web/uploads/ && \
mkdir -p /home/nextjs/apps/web/saml-connection
VOLUME /home/nextjs/apps/web/uploads/

View File

@@ -25,7 +25,7 @@ const mockProject: TProject = {
},
placement: "bottomRight",
clickOutsideClose: true,
overlay: "none",
darkOverlay: false,
environments: [],
languages: [],
logo: null,

View File

@@ -3,7 +3,7 @@
import { zodResolver } from "@hookform/resolvers/zod";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "react-hot-toast";
import { useTranslation } from "react-i18next";
@@ -17,7 +17,6 @@ import {
import { createProjectAction } from "@/app/(app)/environments/[environmentId]/actions";
import { previewSurvey } from "@/app/lib/templates";
import { FORMBRICKS_SURVEYS_FILTERS_KEY_LS } from "@/lib/localStorage";
import { buildStylingFromBrandColor } from "@/lib/styling/constants";
import { getFormattedErrorMessage } from "@/lib/utils/helper";
import { TOrganizationTeam } from "@/modules/ee/teams/project-teams/types/team";
import { CreateTeamModal } from "@/modules/ee/teams/team-list/components/create-team-modal";
@@ -65,17 +64,10 @@ export const ProjectSettings = ({
const { t } = useTranslation();
const addProject = async (data: TProjectUpdateInput) => {
try {
// Build the full styling from the chosen brand color so all derived
// colours (question, button, input, option, progress, etc.) are persisted.
// Without this, only brandColor is saved and the look-and-feel page falls
// back to STYLE_DEFAULTS computed from the default brand (#64748b).
const fullStyling = buildStylingFromBrandColor(data.styling?.brandColor?.light);
const createProjectResponse = await createProjectAction({
organizationId,
data: {
...data,
styling: fullStyling,
config: { channel, industry },
teamIds: data.teamIds,
},
@@ -120,7 +112,6 @@ export const ProjectSettings = ({
const projectName = form.watch("name");
const logoUrl = form.watch("logo.url");
const brandColor = form.watch("styling.brandColor.light") ?? defaultBrandColor;
const previewStyling = useMemo(() => buildStylingFromBrandColor(brandColor), [brandColor]);
const { isSubmitting } = form.formState;
const organizationTeamsOptions = organizationTeams.map((team) => ({
@@ -235,7 +226,7 @@ export const ProjectSettings = ({
alt="Logo"
width={256}
height={56}
className="absolute left-2 top-2 -mb-6 h-20 w-auto max-w-64 rounded-lg border object-contain p-1"
className="absolute top-2 left-2 -mb-6 h-20 w-auto max-w-64 rounded-lg border object-contain p-1"
/>
)}
<p className="text-sm text-slate-400">{t("common.preview")}</p>
@@ -244,7 +235,7 @@ export const ProjectSettings = ({
appUrl={publicDomain}
isPreviewMode={true}
survey={previewSurvey(projectName || "my Product", t)}
styling={previewStyling}
styling={{ brandColor: { light: brandColor } }}
isBrandingEnabled={false}
languageCode="default"
onFileUpload={async (file) => file.name}

View File

@@ -2,7 +2,7 @@
import { z } from "zod";
import { ZId } from "@formbricks/types/common";
import { AuthorizationError, OperationNotAllowedError } from "@formbricks/types/errors";
import { OperationNotAllowedError } from "@formbricks/types/errors";
import { ZProjectUpdateInput } from "@formbricks/types/project";
import { getMembershipByUserIdOrganizationId } from "@/lib/membership/service";
import { getOrganization } from "@/lib/organization/service";
@@ -138,7 +138,7 @@ export const getProjectsForSwitcherAction = authenticatedActionClient
// Need membership for getProjectsByUserId (1 DB query)
const membership = await getMembershipByUserIdOrganizationId(ctx.user.id, parsedInput.organizationId);
if (!membership) {
throw new AuthorizationError("Membership not found");
throw new Error("Membership not found");
}
return await getProjectsByUserId(ctx.user.id, membership);

View File

@@ -36,7 +36,7 @@ export const EnvironmentLayout = async ({ layoutData, children }: EnvironmentLay
// Calculate derived values (no queries)
const { isMember, isOwner, isManager } = getAccessFlags(membership.role);
const { features, lastChecked, isPendingDowngrade, active, status } = license;
const { features, lastChecked, isPendingDowngrade, active } = license;
const isMultiOrgEnabled = features?.isMultiOrgEnabled ?? false;
const organizationProjectsLimit = await getOrganizationProjectsLimit(organization.billing.limits);
const isOwnerOrManager = isOwner || isManager;
@@ -63,7 +63,6 @@ export const EnvironmentLayout = async ({ layoutData, children }: EnvironmentLay
active={active}
environmentId={environment.id}
locale={user.locale}
status={status}
/>
<div className="flex h-full">

View File

@@ -2,6 +2,7 @@
import {
ArrowUpRightIcon,
BarChartIcon,
ChevronRightIcon,
Cog,
LogOutIcon,
@@ -9,6 +10,7 @@ import {
PanelLeftCloseIcon,
PanelLeftOpenIcon,
RocketIcon,
ShapesIcon,
UserCircleIcon,
UserIcon,
} from "lucide-react";
@@ -99,7 +101,7 @@ export const MainNavigation = ({
const mainNavigation = useMemo(
() => [
{
name: t("common.surveys"),
name: "Ask",
href: `/environments/${environment.id}/surveys`,
icon: MessageCircle,
isActive: pathname?.includes("/surveys"),
@@ -107,15 +109,24 @@ export const MainNavigation = ({
},
{
href: `/environments/${environment.id}/contacts`,
name: t("common.contacts"),
name: "Distribute",
icon: UserIcon,
isActive:
pathname?.includes("/contacts") ||
pathname?.includes("/segments") ||
pathname?.includes("/attributes"),
isActive: pathname?.includes("/contacts") || pathname?.includes("/segments"),
},
{
name: t("common.configuration"),
name: "Unify",
href: `/environments/${environment.id}/workspace/unify`,
icon: ShapesIcon,
isActive: pathname?.includes("/unify") && !pathname?.includes("/analyze"),
},
{
name: "Analyze",
href: `/environments/${environment.id}/workspace/analyze`,
icon: BarChartIcon,
isActive: pathname?.includes("/workspace/analyze"),
},
{
name: "Configure",
href: `/environments/${environment.id}/workspace/general`,
icon: Cog,
isActive: pathname?.includes("/project"),
@@ -188,7 +199,7 @@ export const MainNavigation = ({
size="icon"
onClick={toggleSidebar}
className={cn(
"rounded-xl bg-slate-50 p-1 text-slate-600 transition-all hover:bg-slate-100 focus:ring-0 focus:ring-transparent focus:outline-none"
"rounded-xl bg-slate-50 p-1 text-slate-600 transition-all hover:bg-slate-100 focus:outline-none focus:ring-0 focus:ring-transparent"
)}>
{isCollapsed ? (
<PanelLeftOpenIcon strokeWidth={1.5} />

View File

@@ -81,7 +81,7 @@ export const OrganizationBreadcrumb = ({
getOrganizationsForSwitcherAction({ organizationId: currentOrganizationId }).then((result) => {
if (result?.data) {
// Sort organizations by name
const sorted = [...result.data].sort((a, b) => a.name.localeCompare(b.name));
const sorted = result.data.toSorted((a, b) => a.name.localeCompare(b.name));
setOrganizations(sorted);
} else {
// Handle server errors or validation errors

View File

@@ -82,7 +82,7 @@ export const ProjectBreadcrumb = ({
getProjectsForSwitcherAction({ organizationId: currentOrganizationId }).then((result) => {
if (result?.data) {
// Sort projects by name
const sorted = [...result.data].sort((a, b) => a.name.localeCompare(b.name));
const sorted = result.data.toSorted((a, b) => a.name.localeCompare(b.name));
setProjects(sorted);
} else {
// Handle server errors or validation errors
@@ -133,6 +133,11 @@ export const ProjectBreadcrumb = ({
label: t("common.tags"),
href: `/environments/${currentEnvironmentId}/workspace/tags`,
},
{
id: "unify",
label: "Unify Feedback",
href: `/environments/${currentEnvironmentId}/workspace/unify`,
},
];
if (!currentProject) {

View File

@@ -30,7 +30,7 @@ export const NotificationSwitch = ({
const isChecked =
notificationType === "unsubscribedOrganizationIds"
? !notificationSettings.unsubscribedOrganizationIds?.includes(surveyOrProjectOrOrganizationId)
: notificationSettings[notificationType]?.[surveyOrProjectOrOrganizationId] === true;
: notificationSettings[notificationType][surveyOrProjectOrOrganizationId] === true;
const handleSwitchChange = async () => {
setIsLoading(true);
@@ -49,11 +49,8 @@ export const NotificationSwitch = ({
];
}
} else {
updatedNotificationSettings[notificationType] = {
...updatedNotificationSettings[notificationType],
[surveyOrProjectOrOrganizationId]:
!updatedNotificationSettings[notificationType]?.[surveyOrProjectOrOrganizationId],
};
updatedNotificationSettings[notificationType][surveyOrProjectOrOrganizationId] =
!updatedNotificationSettings[notificationType][surveyOrProjectOrOrganizationId];
}
const updatedNotificationSettingsActionResponse = await updateNotificationSettingsAction({
@@ -81,7 +78,7 @@ export const NotificationSwitch = ({
) {
switch (notificationType) {
case "alert":
if (notificationSettings[notificationType]?.[surveyOrProjectOrOrganizationId] === true) {
if (notificationSettings[notificationType][surveyOrProjectOrOrganizationId] === true) {
handleSwitchChange();
toast.success(
t(

View File

@@ -1,142 +0,0 @@
"use client";
import { TFunction } from "i18next";
import { RotateCcwIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { recheckLicenseAction } from "@/modules/ee/license-check/actions";
import { Alert, AlertDescription } from "@/modules/ui/components/alert";
import { Badge } from "@/modules/ui/components/badge";
import { Button } from "@/modules/ui/components/button";
import { SettingsCard } from "../../../components/SettingsCard";
type LicenseStatus = "active" | "expired" | "unreachable" | "invalid_license";
interface EnterpriseLicenseStatusProps {
status: LicenseStatus;
gracePeriodEnd?: Date;
environmentId: string;
}
const getBadgeConfig = (
status: LicenseStatus,
t: TFunction
): { type: "success" | "error" | "warning" | "gray"; label: string } => {
switch (status) {
case "active":
return { type: "success", label: t("environments.settings.enterprise.license_status_active") };
case "expired":
return { type: "error", label: t("environments.settings.enterprise.license_status_expired") };
case "unreachable":
return { type: "warning", label: t("environments.settings.enterprise.license_status_unreachable") };
case "invalid_license":
return { type: "error", label: t("environments.settings.enterprise.license_status_invalid") };
default:
return { type: "gray", label: t("environments.settings.enterprise.license_status") };
}
};
export const EnterpriseLicenseStatus = ({
status,
gracePeriodEnd,
environmentId,
}: EnterpriseLicenseStatusProps) => {
const { t } = useTranslation();
const router = useRouter();
const [isRechecking, setIsRechecking] = useState(false);
const handleRecheck = async () => {
setIsRechecking(true);
try {
const result = await recheckLicenseAction({ environmentId });
if (result?.serverError) {
toast.error(result.serverError || t("environments.settings.enterprise.recheck_license_failed"));
return;
}
if (result?.data) {
if (result.data.status === "unreachable") {
toast.error(t("environments.settings.enterprise.recheck_license_unreachable"));
} else if (result.data.status === "invalid_license") {
toast.error(t("environments.settings.enterprise.recheck_license_invalid"));
} else {
toast.success(t("environments.settings.enterprise.recheck_license_success"));
}
router.refresh();
} else {
toast.error(t("environments.settings.enterprise.recheck_license_failed"));
}
} catch (error) {
toast.error(
error instanceof Error ? error.message : t("environments.settings.enterprise.recheck_license_failed")
);
} finally {
setIsRechecking(false);
}
};
const badgeConfig = getBadgeConfig(status, t);
return (
<SettingsCard
title={t("environments.settings.enterprise.license_status")}
description={t("environments.settings.enterprise.license_status_description")}>
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between gap-3">
<div className="flex flex-col gap-1.5">
<Badge type={badgeConfig.type} text={badgeConfig.label} size="normal" className="w-fit" />
</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={handleRecheck}
disabled={isRechecking}
className="shrink-0">
{isRechecking ? (
<>
<RotateCcwIcon className="mr-2 h-4 w-4 animate-spin" />
{t("environments.settings.enterprise.rechecking")}
</>
) : (
<>
<RotateCcwIcon className="mr-2 h-4 w-4" />
{t("environments.settings.enterprise.recheck_license")}
</>
)}
</Button>
</div>
{status === "unreachable" && gracePeriodEnd && (
<Alert variant="warning" size="small">
<AlertDescription className="overflow-visible whitespace-normal">
{t("environments.settings.enterprise.license_unreachable_grace_period", {
gracePeriodEnd: new Date(gracePeriodEnd).toLocaleDateString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
}),
})}
</AlertDescription>
</Alert>
)}
{status === "invalid_license" && (
<Alert variant="error" size="small">
<AlertDescription className="overflow-visible whitespace-normal">
{t("environments.settings.enterprise.license_invalid_description")}
</AlertDescription>
</Alert>
)}
<p className="border-t border-slate-100 pt-4 text-sm text-slate-500">
{t("environments.settings.enterprise.questions_please_reach_out_to")}{" "}
<a
className="font-medium text-slate-700 underline hover:text-slate-900"
href="mailto:hola@formbricks.com">
hola@formbricks.com
</a>
</p>
</div>
</SettingsCard>
);
};

View File

@@ -2,10 +2,9 @@ import { CheckIcon } from "lucide-react";
import Link from "next/link";
import { notFound } from "next/navigation";
import { OrganizationSettingsNavbar } from "@/app/(app)/environments/[environmentId]/settings/(organization)/components/OrganizationSettingsNavbar";
import { EnterpriseLicenseStatus } from "@/app/(app)/environments/[environmentId]/settings/(organization)/enterprise/components/EnterpriseLicenseStatus";
import { IS_FORMBRICKS_CLOUD } from "@/lib/constants";
import { getTranslate } from "@/lingodotdev/server";
import { GRACE_PERIOD_MS, getEnterpriseLicense } from "@/modules/ee/license-check/lib/license";
import { getEnterpriseLicense } from "@/modules/ee/license-check/lib/license";
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
import { Button } from "@/modules/ui/components/button";
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
@@ -26,8 +25,7 @@ const Page = async (props) => {
return notFound();
}
const licenseState = await getEnterpriseLicense();
const hasLicense = licenseState.status !== "no-license";
const { active: isEnterpriseEdition } = await getEnterpriseLicense();
const paidFeatures = [
{
@@ -92,22 +90,35 @@ const Page = async (props) => {
activeId="enterprise"
/>
</PageHeader>
{hasLicense ? (
<EnterpriseLicenseStatus
status={licenseState.status as "active" | "expired" | "unreachable" | "invalid_license"}
gracePeriodEnd={
licenseState.status === "unreachable"
? new Date(licenseState.lastChecked.getTime() + GRACE_PERIOD_MS)
: undefined
}
environmentId={params.environmentId}
/>
{isEnterpriseEdition ? (
<div>
<div className="mt-8 max-w-4xl rounded-lg border border-slate-300 bg-slate-100 shadow-sm">
<div className="space-y-4 p-8">
<div className="flex items-center gap-x-2">
<div className="rounded-full border border-green-300 bg-green-100 p-0.5 dark:bg-green-800">
<CheckIcon className="h-5 w-5 p-0.5 text-green-500 dark:text-green-400" />
</div>
<p className="text-slate-800">
{t(
"environments.settings.enterprise.your_enterprise_license_is_active_all_features_unlocked"
)}
</p>
</div>
<p className="text-sm text-slate-500">
{t("environments.settings.enterprise.questions_please_reach_out_to")}{" "}
<a className="font-semibold underline" href="mailto:hola@formbricks.com">
hola@formbricks.com
</a>
</p>
</div>
</div>
</div>
) : (
<div>
<div className="relative isolate mt-8 overflow-hidden rounded-lg bg-slate-900 px-3 pt-8 shadow-2xl sm:px-8 md:pt-12 lg:flex lg:gap-x-10 lg:px-12 lg:pt-0">
<svg
viewBox="0 0 1024 1024"
className="absolute left-1/2 top-1/2 -z-10 h-[64rem] w-[64rem] -translate-y-1/2 [mask-image:radial-gradient(closest-side,white,transparent)] sm:left-full sm:-ml-80 lg:left-1/2 lg:ml-0 lg:-translate-x-1/2 lg:translate-y-0"
className="absolute top-1/2 left-1/2 -z-10 h-[64rem] w-[64rem] -translate-y-1/2 [mask-image:radial-gradient(closest-side,white,transparent)] sm:left-full sm:-ml-80 lg:left-1/2 lg:ml-0 lg:-translate-x-1/2 lg:translate-y-0"
aria-hidden="true">
<circle
cx={512}
@@ -142,8 +153,8 @@ const Page = async (props) => {
{t("environments.settings.enterprise.enterprise_features")}
</h2>
<ul className="my-4 space-y-4">
{paidFeatures.map((feature) => (
<li key={feature.title} className="flex items-center">
{paidFeatures.map((feature, index) => (
<li key={index} className="flex items-center">
<div className="rounded-full border border-green-300 bg-green-100 p-0.5 dark:bg-green-800">
<CheckIcon className="h-5 w-5 p-0.5 text-green-500 dark:text-green-400" />
</div>

View File

@@ -7,7 +7,6 @@ import { useTranslation } from "react-i18next";
import { TOrganization } from "@formbricks/types/organizations";
import { deleteOrganizationAction } from "@/app/(app)/environments/[environmentId]/settings/(organization)/general/actions";
import { FORMBRICKS_ENVIRONMENT_ID_LS } from "@/lib/localStorage";
import { getFormattedErrorMessage } from "@/lib/utils/helper";
import { Alert, AlertDescription } from "@/modules/ui/components/alert";
import { Button } from "@/modules/ui/components/button";
import { DeleteDialog } from "@/modules/ui/components/delete-dialog";
@@ -33,12 +32,7 @@ export const DeleteOrganization = ({
setIsDeleting(true);
try {
const result = await deleteOrganizationAction({ organizationId: organization.id });
if (result?.serverError) {
toast.error(getFormattedErrorMessage(result));
setIsDeleting(false);
return;
}
await deleteOrganizationAction({ organizationId: organization.id });
toast.success(t("environments.settings.general.organization_deleted_successfully"));
if (typeof localStorage !== "undefined") {
localStorage.removeItem(FORMBRICKS_ENVIRONMENT_ID_LS);

View File

@@ -4,7 +4,6 @@ import { revalidatePath } from "next/cache";
import { z } from "zod";
import { ZId } from "@formbricks/types/common";
import { ZResponseFilterCriteria } from "@formbricks/types/responses";
import { getDisplaysBySurveyIdWithContact } from "@/lib/display/service";
import { getResponseCountBySurveyId, getResponses } from "@/lib/response/service";
import { authenticatedActionClient } from "@/lib/utils/action-client";
import { checkAuthorizationUpdated } from "@/lib/utils/action-client/action-client-middleware";
@@ -107,31 +106,3 @@ export const getResponseCountAction = authenticatedActionClient
return getResponseCountBySurveyId(parsedInput.surveyId, parsedInput.filterCriteria);
});
const ZGetDisplaysWithContactAction = z.object({
surveyId: ZId,
limit: z.number().int().min(1).max(100),
offset: z.number().int().nonnegative(),
});
export const getDisplaysWithContactAction = authenticatedActionClient
.schema(ZGetDisplaysWithContactAction)
.action(async ({ ctx, parsedInput }) => {
await checkAuthorizationUpdated({
userId: ctx.user.id,
organizationId: await getOrganizationIdFromSurveyId(parsedInput.surveyId),
access: [
{
type: "organization",
roles: ["owner", "manager"],
},
{
type: "projectTeam",
minPermission: "read",
projectId: await getProjectIdFromSurveyId(parsedInput.surveyId),
},
],
});
return getDisplaysBySurveyIdWithContact(parsedInput.surveyId, parsedInput.limit, parsedInput.offset);
});

View File

@@ -316,14 +316,6 @@ export const generateResponseTableColumns = (
},
};
const responseIdColumn: ColumnDef<TResponseTableData> = {
accessorKey: "responseId",
header: () => <div className="gap-x-1.5">{t("common.response_id")}</div>,
cell: ({ row }) => {
return <IdBadge id={row.original.responseId} />;
},
};
const quotasColumn: ColumnDef<TResponseTableData> = {
accessorKey: "quota",
header: t("common.quota"),
@@ -422,7 +414,6 @@ export const generateResponseTableColumns = (
const baseColumns = [
personColumn,
singleUseIdColumn,
responseIdColumn,
dateColumn,
...(showQuotasColumn ? [quotasColumn] : []),
statusColumn,

View File

@@ -8,7 +8,7 @@ import { TSurvey, TSurveyElementSummaryFileUpload } from "@formbricks/types/surv
import { TUserLocale } from "@formbricks/types/user";
import { timeSince } from "@/lib/time";
import { getContactIdentifier } from "@/lib/utils/contact";
import { getOriginalFileNameFromUrl } from "@/modules/storage/url-helpers";
import { getOriginalFileNameFromUrl } from "@/modules/storage/utils";
import { PersonAvatar } from "@/modules/ui/components/avatars";
import { Button } from "@/modules/ui/components/button";
import { EmptyState } from "@/modules/ui/components/empty-state";

View File

@@ -1,125 +0,0 @@
"use client";
import { AlertCircleIcon, InfoIcon } from "lucide-react";
import Link from "next/link";
import { useTranslation } from "react-i18next";
import { TDisplayWithContact } from "@formbricks/types/displays";
import { TUserLocale } from "@formbricks/types/user";
import { timeSince } from "@/lib/time";
import { Button } from "@/modules/ui/components/button";
interface SummaryImpressionsProps {
displays: TDisplayWithContact[];
isLoading: boolean;
hasMore: boolean;
displaysError: string | null;
environmentId: string;
locale: TUserLocale;
onLoadMore: () => void;
onRetry: () => void;
}
const getDisplayContactIdentifier = (display: TDisplayWithContact): string => {
if (!display.contact) return "";
return display.contact.attributes?.email || display.contact.attributes?.userId || display.contact.id;
};
export const SummaryImpressions = ({
displays,
isLoading,
hasMore,
displaysError,
environmentId,
locale,
onLoadMore,
onRetry,
}: SummaryImpressionsProps) => {
const { t } = useTranslation();
const renderContent = () => {
if (displaysError) {
return (
<div className="p-8">
<div className="flex flex-col items-center gap-4 text-center">
<div className="flex items-center gap-2 text-red-600">
<AlertCircleIcon className="h-5 w-5" />
<span className="text-sm font-medium">{t("common.error_loading_data")}</span>
</div>
<p className="text-sm text-slate-500">{displaysError}</p>
<Button onClick={onRetry} variant="secondary" size="sm">
{t("common.try_again")}
</Button>
</div>
</div>
);
}
if (displays.length === 0) {
return (
<div className="p-8 text-center text-sm text-slate-500">
{t("environments.surveys.summary.no_identified_impressions")}
</div>
);
}
return (
<>
<div className="grid min-h-10 grid-cols-4 items-center border-b border-slate-200 bg-slate-100 text-sm font-semibold text-slate-600">
<div className="col-span-2 px-4 md:px-6">{t("common.user")}</div>
<div className="col-span-2 px-4 md:px-6">{t("environments.contacts.survey_viewed_at")}</div>
</div>
<div className="max-h-[62vh] overflow-y-auto">
{displays.map((display) => (
<div
key={display.id}
className="grid grid-cols-4 items-center border-b border-slate-100 py-2 text-xs text-slate-800 last:border-transparent md:text-sm">
<div className="col-span-2 pl-4 md:pl-6">
{display.contact ? (
<Link
className="ph-no-capture break-all text-slate-600 hover:underline"
href={`/environments/${environmentId}/contacts/${display.contact.id}`}>
{getDisplayContactIdentifier(display)}
</Link>
) : (
<span className="break-all text-slate-600">{t("common.anonymous")}</span>
)}
</div>
<div className="col-span-2 px-4 text-slate-500 md:px-6">
{timeSince(display.createdAt.toString(), locale)}
</div>
</div>
))}
</div>
{hasMore && (
<div className="flex justify-center border-t border-slate-100 py-4">
<Button onClick={onLoadMore} variant="secondary" size="sm">
{t("common.load_more")}
</Button>
</div>
)}
</>
);
};
if (isLoading) {
return (
<div className="rounded-xl border border-slate-200 bg-white p-8 shadow-sm">
<div className="flex items-center justify-center">
<div className="h-6 w-32 animate-pulse rounded-full bg-slate-200"></div>
</div>
</div>
);
}
return (
<div className="rounded-xl border border-slate-200 bg-white shadow-sm">
<div className="flex items-center gap-2 rounded-t-xl border-b border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-600">
<InfoIcon className="h-4 w-4 shrink-0" />
<span>{t("environments.surveys.summary.impressions_identified_only")}</span>
</div>
{renderContent()}
</div>
);
};

View File

@@ -10,8 +10,8 @@ interface SummaryMetadataProps {
surveySummary: TSurveySummary["meta"];
quotasCount: number;
isLoading: boolean;
tab: "dropOffs" | "quotas" | "impressions" | undefined;
setTab: React.Dispatch<React.SetStateAction<"dropOffs" | "quotas" | "impressions" | undefined>>;
tab: "dropOffs" | "quotas" | undefined;
setTab: React.Dispatch<React.SetStateAction<"dropOffs" | "quotas" | undefined>>;
isQuotasAllowed: boolean;
}
@@ -53,7 +53,7 @@ export const SummaryMetadata = ({
const { t } = useTranslation();
const dropoffCountValue = dropOffCount === 0 ? <span>-</span> : dropOffCount;
const handleTabChange = (val: "dropOffs" | "quotas" | "impressions") => {
const handleTabChange = (val: "dropOffs" | "quotas") => {
const change = tab === val ? undefined : val;
setTab(change);
};
@@ -65,16 +65,12 @@ export const SummaryMetadata = ({
`grid gap-4 sm:grid-cols-2 md:grid-cols-3 md:gap-x-2 lg:grid-cols-3 2xl:grid-cols-5`,
isQuotasAllowed && quotasCount > 0 && "2xl:grid-cols-6"
)}>
<InteractiveCard
key="impressions"
tab="impressions"
<StatCard
label={t("environments.surveys.summary.impressions")}
percentage={null}
value={displayCount === 0 ? <span>-</span> : displayCount}
tooltipText={t("environments.surveys.summary.impressions_tooltip")}
isLoading={isLoading}
onClick={() => handleTabChange("impressions")}
isActive={tab === "impressions"}
/>
<StatCard
label={t("environments.surveys.summary.starts")}

View File

@@ -1,31 +1,21 @@
"use client";
import { useSearchParams } from "next/navigation";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { TDisplayWithContact } from "@formbricks/types/displays";
import { useEffect, useMemo, useState } from "react";
import { TEnvironment } from "@formbricks/types/environment";
import { TSurvey, TSurveySummary } from "@formbricks/types/surveys/types";
import { TUserLocale } from "@formbricks/types/user";
import {
getDisplaysWithContactAction,
getSurveySummaryAction,
} from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/actions";
import { getSurveySummaryAction } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/actions";
import { useResponseFilter } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/components/response-filter-context";
import ScrollToTop from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/ScrollToTop";
import { SummaryDropOffs } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SummaryDropOffs";
import { SummaryImpressions } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SummaryImpressions";
import { CustomFilter } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/components/CustomFilter";
import { getFormattedFilters } from "@/app/lib/surveys/surveys";
import { getFormattedErrorMessage } from "@/lib/utils/helper";
import { replaceHeadlineRecall } from "@/lib/utils/recall";
import { QuotasSummary } from "@/modules/ee/quotas/components/quotas-summary";
import { SummaryList } from "./SummaryList";
import { SummaryMetadata } from "./SummaryMetadata";
const DISPLAYS_PER_PAGE = 15;
const defaultSurveySummary: TSurveySummary = {
meta: {
completedPercentage: 0,
@@ -61,76 +51,17 @@ export const SummaryPage = ({
initialSurveySummary,
isQuotasAllowed,
}: SummaryPageProps) => {
const { t } = useTranslation();
const searchParams = useSearchParams();
const [surveySummary, setSurveySummary] = useState<TSurveySummary>(
initialSurveySummary || defaultSurveySummary
);
const [tab, setTab] = useState<"dropOffs" | "quotas" | "impressions" | undefined>(undefined);
const [tab, setTab] = useState<"dropOffs" | "quotas" | undefined>(undefined);
const [isLoading, setIsLoading] = useState(!initialSurveySummary);
const { selectedFilter, dateRange, resetState } = useResponseFilter();
const [displays, setDisplays] = useState<TDisplayWithContact[]>([]);
const [isDisplaysLoading, setIsDisplaysLoading] = useState(false);
const [hasMoreDisplays, setHasMoreDisplays] = useState(true);
const [displaysError, setDisplaysError] = useState<string | null>(null);
const displaysFetchedRef = useRef(false);
const fetchDisplays = useCallback(
async (offset: number) => {
const response = await getDisplaysWithContactAction({
surveyId,
limit: DISPLAYS_PER_PAGE,
offset,
});
if (!response?.data) {
const errorMessage = getFormattedErrorMessage(response);
throw new Error(errorMessage);
}
return response?.data ?? [];
},
[surveyId]
);
const loadInitialDisplays = useCallback(async () => {
setIsDisplaysLoading(true);
setDisplaysError(null);
try {
const data = await fetchDisplays(0);
setDisplays(data);
setHasMoreDisplays(data.length === DISPLAYS_PER_PAGE);
} catch (error) {
toast.error(error);
setDisplays([]);
setHasMoreDisplays(false);
} finally {
setIsDisplaysLoading(false);
}
}, [fetchDisplays, t]);
const handleLoadMoreDisplays = useCallback(async () => {
try {
const data = await fetchDisplays(displays.length);
setDisplays((prev) => [...prev, ...data]);
setHasMoreDisplays(data.length === DISPLAYS_PER_PAGE);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : t("common.something_went_wrong");
toast.error(errorMessage);
}
}, [fetchDisplays, displays.length, t]);
useEffect(() => {
if (tab === "impressions" && !displaysFetchedRef.current) {
displaysFetchedRef.current = true;
loadInitialDisplays();
}
}, [tab, loadInitialDisplays]);
// Only fetch data when filters change or when there's no initial data
useEffect(() => {
// If we have initial data and no filters are applied, don't fetch
@@ -190,18 +121,6 @@ export const SummaryPage = ({
setTab={setTab}
isQuotasAllowed={isQuotasAllowed}
/>
{tab === "impressions" && (
<SummaryImpressions
displays={displays}
isLoading={isDisplaysLoading}
hasMore={hasMoreDisplays}
displaysError={displaysError}
environmentId={environment.id}
locale={locale}
onLoadMore={handleLoadMoreDisplays}
onRetry={loadInitialDisplays}
/>
)}
{tab === "dropOffs" && <SummaryDropOffs dropOff={surveySummary.dropOff} survey={surveyMemoized} />}
{isQuotasAllowed && tab === "quotas" && <QuotasSummary quotas={surveySummary.quotas} />}
<div className="flex gap-1.5">

View File

@@ -4,9 +4,9 @@ import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";
import { BaseCard } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/base-card";
interface InteractiveCardProps {
tab: "dropOffs" | "quotas" | "impressions";
tab: "dropOffs" | "quotas";
label: string;
percentage: number | null;
percentage: number;
value: React.ReactNode;
tooltipText: string;
isLoading: boolean;

View File

@@ -352,7 +352,7 @@ export const AnonymousLinksTab = ({
},
{
title: t("environments.surveys.share.anonymous_links.custom_start_point"),
href: "https://formbricks.com/docs/xm-and-surveys/surveys/link-surveys/start-at-block",
href: "https://formbricks.com/docs/xm-and-surveys/surveys/link-surveys/start-at-question",
},
]}
/>

View File

@@ -241,7 +241,7 @@ export const ResponseFilter = ({ survey }: ResponseFilterProps) => {
<Popover open={isOpen} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>
<PopoverTriggerButton isOpen={isOpen}>
{t("common.filter")} <b>{activeFilterCount > 0 && `(${activeFilterCount})`}</b>
Filter <b>{activeFilterCount > 0 && `(${activeFilterCount})`}</b>
</PopoverTriggerButton>
</PopoverTrigger>
<PopoverContent
@@ -329,7 +329,7 @@ export const ResponseFilter = ({ survey }: ResponseFilterProps) => {
</div>
{i !== filterValue.filter.length - 1 && (
<div className="my-4 flex items-center">
<p className="mr-4 font-semibold text-slate-800">{t("common.and")}</p>
<p className="mr-4 font-semibold text-slate-800">and</p>
<hr className="w-full text-slate-600" />
</div>
)}

View File

@@ -0,0 +1,45 @@
"use client";
import { useState } from "react";
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
import { PageHeader } from "@/modules/ui/components/page-header";
import { CreateDashboardModal } from "./create-dashboard-modal";
import { DashboardsTable } from "./dashboards-table";
import { TDashboard } from "./types";
interface AnalyzeSectionProps {
environmentId: string;
}
export function AnalyzeSection({ environmentId }: AnalyzeSectionProps) {
const [dashboards, setDashboards] = useState<TDashboard[]>([]);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
const handleCreateDashboard = (dashboard: TDashboard) => {
setDashboards((prev) => [dashboard, ...prev]);
};
const handleDashboardClick = (dashboard: TDashboard) => {
// TODO: Navigate to dashboard detail view
console.log("Dashboard clicked:", dashboard);
};
return (
<PageContentWrapper>
<PageHeader
pageTitle="Analyze"
cta={
<CreateDashboardModal
open={isCreateModalOpen}
onOpenChange={setIsCreateModalOpen}
onCreateDashboard={handleCreateDashboard}
/>
}
/>
<div className="space-y-6">
<DashboardsTable dashboards={dashboards} onDashboardClick={handleDashboardClick} />
</div>
</PageContentWrapper>
);
}

View File

@@ -0,0 +1,107 @@
"use client";
import { PlusIcon } from "lucide-react";
import { useState } from "react";
import { Button } from "@/modules/ui/components/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/modules/ui/components/dialog";
import { Input } from "@/modules/ui/components/input";
import { Label } from "@/modules/ui/components/label";
import { TDashboard } from "./types";
interface CreateDashboardModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onCreateDashboard: (dashboard: TDashboard) => void;
}
export function CreateDashboardModal({ open, onOpenChange, onCreateDashboard }: CreateDashboardModalProps) {
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const handleCreate = () => {
if (!name.trim()) return;
const newDashboard: TDashboard = {
id: crypto.randomUUID(),
name: name.trim(),
description: description.trim() || undefined,
widgetCount: 0,
createdAt: new Date(),
updatedAt: new Date(),
};
onCreateDashboard(newDashboard);
resetForm();
onOpenChange(false);
};
const resetForm = () => {
setName("");
setDescription("");
};
const handleOpenChange = (newOpen: boolean) => {
if (!newOpen) {
resetForm();
}
onOpenChange(newOpen);
};
return (
<>
<Button onClick={() => onOpenChange(true)} size="sm">
Create dashboard
<PlusIcon className="ml-2 h-4 w-4" />
</Button>
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>Create Dashboard</DialogTitle>
<DialogDescription>
Create a new dashboard to visualize and analyze your unified feedback data.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="dashboardName">Name</Label>
<Input
id="dashboardName"
placeholder="e.g., Product Feedback Overview"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="dashboardDescription">Description (optional)</Label>
<Input
id="dashboardDescription"
placeholder="e.g., Weekly overview of customer feedback trends"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => handleOpenChange(false)}>
Cancel
</Button>
<Button onClick={handleCreate} disabled={!name.trim()}>
Create dashboard
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}

View File

@@ -0,0 +1,79 @@
"use client";
import { formatDistanceToNow } from "date-fns";
import { LayoutDashboardIcon } from "lucide-react";
import { TDashboard } from "./types";
interface DashboardsTableProps {
dashboards: TDashboard[];
onDashboardClick: (dashboard: TDashboard) => void;
}
export function DashboardsTable({ dashboards, onDashboardClick }: DashboardsTableProps) {
if (dashboards.length === 0) {
return (
<div className="flex flex-col items-center justify-center rounded-xl border border-slate-200 bg-white py-16">
<LayoutDashboardIcon className="h-12 w-12 text-slate-300" />
<p className="mt-4 text-sm font-medium text-slate-600">No dashboards yet</p>
<p className="mt-1 text-sm text-slate-500">Create your first dashboard to start analyzing feedback</p>
</div>
);
}
return (
<div className="rounded-xl border border-slate-200 bg-white">
{/* Table Header */}
<div className="grid h-12 grid-cols-12 content-center border-b border-slate-200 text-left text-sm font-semibold text-slate-900">
<div className="col-span-5 pl-6">Name</div>
<div className="col-span-3 hidden text-center sm:block">Widgets</div>
<div className="col-span-2 hidden text-center sm:block">Updated</div>
<div className="col-span-2 hidden pr-6 text-right sm:block">Created</div>
</div>
{/* Table Rows */}
<div className="divide-y divide-slate-100">
{dashboards.map((dashboard) => (
<div
key={dashboard.id}
role="button"
tabIndex={0}
className="grid h-16 cursor-pointer grid-cols-12 content-center p-2 text-left transition-colors ease-in-out hover:bg-slate-50"
onClick={() => onDashboardClick(dashboard)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
onDashboardClick(dashboard);
}
}}>
{/* Name Column */}
<div className="col-span-5 flex items-center gap-3 pl-4">
<div className="flex h-8 w-8 items-center justify-center rounded-md bg-slate-100">
<LayoutDashboardIcon className="h-4 w-4 text-slate-600" />
</div>
<div className="flex flex-col">
<span className="text-sm font-medium text-slate-900">{dashboard.name}</span>
{dashboard.description && (
<span className="truncate text-xs text-slate-500">{dashboard.description}</span>
)}
</div>
</div>
{/* Widgets Column */}
<div className="col-span-3 hidden items-center justify-center text-sm text-slate-600 sm:flex">
{dashboard.widgetCount} {dashboard.widgetCount === 1 ? "widget" : "widgets"}
</div>
{/* Updated Column */}
<div className="col-span-2 hidden items-center justify-center text-sm text-slate-500 sm:flex">
{formatDistanceToNow(dashboard.updatedAt, { addSuffix: true })}
</div>
{/* Created Column */}
<div className="col-span-2 hidden items-center justify-end pr-4 text-sm text-slate-500 sm:flex">
{formatDistanceToNow(dashboard.createdAt, { addSuffix: true })}
</div>
</div>
))}
</div>
</div>
);
}

View File

@@ -0,0 +1,4 @@
export { AnalyzeSection } from "./AnalyzeSection";
export { CreateDashboardModal } from "./create-dashboard-modal";
export { DashboardsTable } from "./dashboards-table";
export type { TDashboard } from "./types";

View File

@@ -0,0 +1,8 @@
export interface TDashboard {
id: string;
name: string;
description?: string;
widgetCount: number;
createdAt: Date;
updatedAt: Date;
}

View File

@@ -0,0 +1,10 @@
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
import { AnalyzeSection } from "./components";
export default async function AnalyzePage(props: { params: Promise<{ environmentId: string }> }) {
const params = await props.params;
await getEnvironmentAuth(params.environmentId);
return <AnalyzeSection environmentId={params.environmentId} />;
}

View File

@@ -21,7 +21,6 @@ import { createOrUpdateIntegrationAction } from "@/app/(app)/environments/[envir
import { BaseSelectDropdown } from "@/app/(app)/environments/[environmentId]/workspace/integrations/airtable/components/BaseSelectDropdown";
import { fetchTables } from "@/app/(app)/environments/[environmentId]/workspace/integrations/airtable/lib/airtable";
import AirtableLogo from "@/images/airtableLogo.svg";
import { getFormattedErrorMessage } from "@/lib/utils/helper";
import { recallToHeadline } from "@/lib/utils/recall";
import { getElementsFromBlocks } from "@/modules/survey/lib/client-utils";
import { AdditionalIntegrationSettings } from "@/modules/ui/components/additional-integration-settings";
@@ -269,14 +268,7 @@ export const AddIntegrationModal = ({
airtableIntegrationData.config?.data.push(integrationData);
}
const result = await createOrUpdateIntegrationAction({
environmentId,
integrationData: airtableIntegrationData,
});
if (result?.serverError) {
toast.error(getFormattedErrorMessage(result));
return;
}
await createOrUpdateIntegrationAction({ environmentId, integrationData: airtableIntegrationData });
if (isEditMode) {
toast.success(t("environments.integrations.integration_updated_successfully"));
} else {
@@ -312,11 +304,7 @@ export const AddIntegrationModal = ({
const integrationData = structuredClone(airtableIntegrationData);
integrationData.config.data.splice(index, 1);
const result = await createOrUpdateIntegrationAction({ environmentId, integrationData });
if (result?.serverError) {
toast.error(getFormattedErrorMessage(result));
return;
}
await createOrUpdateIntegrationAction({ environmentId, integrationData });
handleClose();
router.refresh();

View File

@@ -1,49 +1,12 @@
"use server";
import { z } from "zod";
import { ZId } from "@formbricks/types/common";
import {
TIntegrationGoogleSheets,
ZIntegrationGoogleSheets,
} from "@formbricks/types/integration/google-sheet";
import { getSpreadsheetNameById, validateGoogleSheetsConnection } from "@/lib/googleSheet/service";
import { getIntegrationByType } from "@/lib/integration/service";
import { ZIntegrationGoogleSheets } from "@formbricks/types/integration/google-sheet";
import { getSpreadsheetNameById } from "@/lib/googleSheet/service";
import { authenticatedActionClient } from "@/lib/utils/action-client";
import { checkAuthorizationUpdated } from "@/lib/utils/action-client/action-client-middleware";
import { getOrganizationIdFromEnvironmentId, getProjectIdFromEnvironmentId } from "@/lib/utils/helper";
const ZValidateGoogleSheetsConnectionAction = z.object({
environmentId: ZId,
});
export const validateGoogleSheetsConnectionAction = authenticatedActionClient
.schema(ZValidateGoogleSheetsConnectionAction)
.action(async ({ ctx, parsedInput }) => {
await checkAuthorizationUpdated({
userId: ctx.user.id,
organizationId: await getOrganizationIdFromEnvironmentId(parsedInput.environmentId),
access: [
{
type: "organization",
roles: ["owner", "manager"],
},
{
type: "projectTeam",
projectId: await getProjectIdFromEnvironmentId(parsedInput.environmentId),
minPermission: "readWrite",
},
],
});
const integration = await getIntegrationByType(parsedInput.environmentId, "googleSheets");
if (!integration) {
return { data: false };
}
await validateGoogleSheetsConnection(integration as TIntegrationGoogleSheets);
return { data: true };
});
const ZGetSpreadsheetNameByIdAction = z.object({
googleSheetIntegration: ZIntegrationGoogleSheets,
environmentId: z.string(),

View File

@@ -20,10 +20,6 @@ import {
isValidGoogleSheetsUrl,
} from "@/app/(app)/environments/[environmentId]/workspace/integrations/google-sheets/lib/util";
import GoogleSheetLogo from "@/images/googleSheetsLogo.png";
import {
GOOGLE_SHEET_INTEGRATION_INSUFFICIENT_PERMISSION,
GOOGLE_SHEET_INTEGRATION_INVALID_GRANT,
} from "@/lib/googleSheet/constants";
import { getFormattedErrorMessage } from "@/lib/utils/helper";
import { recallToHeadline } from "@/lib/utils/recall";
import { getElementsFromBlocks } from "@/modules/survey/lib/client-utils";
@@ -122,17 +118,6 @@ export const AddIntegrationModal = ({
resetForm();
}, [selectedIntegration, surveys]);
const showErrorMessageToast = (response: Awaited<ReturnType<typeof getSpreadsheetNameByIdAction>>) => {
const errorMessage = getFormattedErrorMessage(response);
if (errorMessage === GOOGLE_SHEET_INTEGRATION_INVALID_GRANT) {
toast.error(t("environments.integrations.google_sheets.token_expired_error"));
} else if (errorMessage === GOOGLE_SHEET_INTEGRATION_INSUFFICIENT_PERMISSION) {
toast.error(t("environments.integrations.google_sheets.spreadsheet_permission_error"));
} else {
toast.error(errorMessage);
}
};
const linkSheet = async () => {
try {
if (!isValidGoogleSheetsUrl(spreadsheetUrl)) {
@@ -144,7 +129,6 @@ export const AddIntegrationModal = ({
if (selectedElements.length === 0) {
throw new Error(t("environments.integrations.select_at_least_one_question_error"));
}
setIsLinkingSheet(true);
const spreadsheetId = extractSpreadsheetIdFromUrl(spreadsheetUrl);
const spreadsheetNameResponse = await getSpreadsheetNameByIdAction({
googleSheetIntegration,
@@ -153,11 +137,13 @@ export const AddIntegrationModal = ({
});
if (!spreadsheetNameResponse?.data) {
showErrorMessageToast(spreadsheetNameResponse);
return;
const errorMessage = getFormattedErrorMessage(spreadsheetNameResponse);
throw new Error(errorMessage);
}
const spreadsheetName = spreadsheetNameResponse.data;
setIsLinkingSheet(true);
integrationData.spreadsheetId = spreadsheetId;
integrationData.spreadsheetName = spreadsheetName;
integrationData.surveyId = selectedSurvey.id;
@@ -179,14 +165,7 @@ export const AddIntegrationModal = ({
// create action
googleSheetIntegrationData.config.data.push(integrationData);
}
const result = await createOrUpdateIntegrationAction({
environmentId,
integrationData: googleSheetIntegrationData,
});
if (result?.serverError) {
toast.error(getFormattedErrorMessage(result));
return;
}
await createOrUpdateIntegrationAction({ environmentId, integrationData: googleSheetIntegrationData });
if (selectedIntegration) {
toast.success(t("environments.integrations.integration_updated_successfully"));
} else {
@@ -226,14 +205,7 @@ export const AddIntegrationModal = ({
googleSheetIntegrationData.config.data.splice(selectedIntegration!.index, 1);
try {
setIsDeleting(true);
const result = await createOrUpdateIntegrationAction({
environmentId,
integrationData: googleSheetIntegrationData,
});
if (result?.serverError) {
toast.error(getFormattedErrorMessage(result));
return;
}
await createOrUpdateIntegrationAction({ environmentId, integrationData: googleSheetIntegrationData });
toast.success(t("environments.integrations.integration_removed_successfully"));
setOpen(false);
} catch (error) {
@@ -294,7 +266,7 @@ export const AddIntegrationModal = ({
<div className="space-y-4">
<div>
<Label htmlFor="Surveys">{t("common.questions")}</Label>
<div className="mt-1 max-h-[15vh] overflow-y-auto overflow-x-hidden rounded-lg border border-slate-200">
<div className="mt-1 max-h-[15vh] overflow-x-hidden overflow-y-auto rounded-lg border border-slate-200">
<div className="grid content-center rounded-lg bg-slate-50 p-3 text-left text-sm text-slate-900">
{surveyElements.map((question) => (
<div key={question.id} className="my-1 flex items-center space-x-2">

View File

@@ -1,6 +1,6 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useState } from "react";
import { TEnvironment } from "@formbricks/types/environment";
import {
TIntegrationGoogleSheets,
@@ -8,11 +8,9 @@ import {
} from "@formbricks/types/integration/google-sheet";
import { TSurvey } from "@formbricks/types/surveys/types";
import { TUserLocale } from "@formbricks/types/user";
import { validateGoogleSheetsConnectionAction } from "@/app/(app)/environments/[environmentId]/workspace/integrations/google-sheets/actions";
import { ManageIntegration } from "@/app/(app)/environments/[environmentId]/workspace/integrations/google-sheets/components/ManageIntegration";
import { authorize } from "@/app/(app)/environments/[environmentId]/workspace/integrations/google-sheets/lib/google";
import googleSheetLogo from "@/images/googleSheetsLogo.png";
import { GOOGLE_SHEET_INTEGRATION_INVALID_GRANT } from "@/lib/googleSheet/constants";
import { ConnectIntegration } from "@/modules/ui/components/connect-integration";
import { AddIntegrationModal } from "./AddIntegrationModal";
@@ -37,23 +35,10 @@ export const GoogleSheetWrapper = ({
googleSheetIntegration ? googleSheetIntegration.config?.key : false
);
const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
const [showReconnectButton, setShowReconnectButton] = useState<boolean>(false);
const [selectedIntegration, setSelectedIntegration] = useState<
(TIntegrationGoogleSheetsConfigData & { index: number }) | null
>(null);
const validateConnection = useCallback(async () => {
if (!isConnected || !googleSheetIntegration) return;
const response = await validateGoogleSheetsConnectionAction({ environmentId: environment.id });
if (response?.serverError === GOOGLE_SHEET_INTEGRATION_INVALID_GRANT) {
setShowReconnectButton(true);
}
}, [environment.id, isConnected, googleSheetIntegration]);
useEffect(() => {
validateConnection();
}, [validateConnection]);
const handleGoogleAuthorization = async () => {
authorize(environment.id, webAppUrl).then((url: string) => {
if (url) {
@@ -79,8 +64,6 @@ export const GoogleSheetWrapper = ({
setOpenAddIntegrationModal={setIsModalOpen}
setIsConnected={setIsConnected}
setSelectedIntegration={setSelectedIntegration}
showReconnectButton={showReconnectButton}
handleGoogleAuthorization={handleGoogleAuthorization}
locale={locale}
/>
</>

View File

@@ -1,6 +1,6 @@
"use client";
import { RefreshCcwIcon, Trash2Icon } from "lucide-react";
import { Trash2Icon } from "lucide-react";
import { useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
@@ -12,19 +12,15 @@ import { TUserLocale } from "@formbricks/types/user";
import { deleteIntegrationAction } from "@/app/(app)/environments/[environmentId]/workspace/integrations/actions";
import { timeSince } from "@/lib/time";
import { getFormattedErrorMessage } from "@/lib/utils/helper";
import { Alert, AlertButton, AlertDescription } from "@/modules/ui/components/alert";
import { Button } from "@/modules/ui/components/button";
import { DeleteDialog } from "@/modules/ui/components/delete-dialog";
import { EmptyState } from "@/modules/ui/components/empty-state";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/modules/ui/components/tooltip";
interface ManageIntegrationProps {
googleSheetIntegration: TIntegrationGoogleSheets;
setOpenAddIntegrationModal: (v: boolean) => void;
setIsConnected: (v: boolean) => void;
setSelectedIntegration: (v: (TIntegrationGoogleSheetsConfigData & { index: number }) | null) => void;
showReconnectButton: boolean;
handleGoogleAuthorization: () => void;
locale: TUserLocale;
}
@@ -33,8 +29,6 @@ export const ManageIntegration = ({
setOpenAddIntegrationModal,
setIsConnected,
setSelectedIntegration,
showReconnectButton,
handleGoogleAuthorization,
locale,
}: ManageIntegrationProps) => {
const { t } = useTranslation();
@@ -74,17 +68,7 @@ export const ManageIntegration = ({
return (
<div className="mt-6 flex w-full flex-col items-center justify-center p-6">
{showReconnectButton && (
<Alert variant="warning" size="small" className="mb-4 w-full">
<AlertDescription>
{t("environments.integrations.google_sheets.reconnect_button_description")}
</AlertDescription>
<AlertButton onClick={handleGoogleAuthorization}>
{t("environments.integrations.google_sheets.reconnect_button")}
</AlertButton>
</Alert>
)}
<div className="flex w-full justify-end space-x-2">
<div className="flex w-full justify-end">
<div className="mr-6 flex items-center">
<span className="mr-4 h-4 w-4 rounded-full bg-green-600"></span>
<span className="text-slate-500">
@@ -93,19 +77,6 @@ export const ManageIntegration = ({
})}
</span>
</div>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" onClick={handleGoogleAuthorization}>
<RefreshCcwIcon className="mr-2 h-4 w-4" />
{t("environments.integrations.google_sheets.reconnect_button")}
</Button>
</TooltipTrigger>
<TooltipContent>
{t("environments.integrations.google_sheets.reconnect_button_tooltip")}
</TooltipContent>
</Tooltip>
</TooltipProvider>
<Button
onClick={() => {
setSelectedIntegration(null);

View File

@@ -22,7 +22,6 @@ import {
createEmptyMapping,
} from "@/app/(app)/environments/[environmentId]/workspace/integrations/notion/components/MappingRow";
import NotionLogo from "@/images/notion.png";
import { getFormattedErrorMessage } from "@/lib/utils/helper";
import { recallToHeadline } from "@/lib/utils/recall";
import { getElementsFromBlocks } from "@/modules/survey/lib/client-utils";
import { Button } from "@/modules/ui/components/button";
@@ -218,14 +217,7 @@ export const AddIntegrationModal = ({
notionIntegrationData.config.data.push(integrationData);
}
const result = await createOrUpdateIntegrationAction({
environmentId,
integrationData: notionIntegrationData,
});
if (result?.serverError) {
toast.error(getFormattedErrorMessage(result));
return;
}
await createOrUpdateIntegrationAction({ environmentId, integrationData: notionIntegrationData });
if (selectedIntegration) {
toast.success(t("environments.integrations.integration_updated_successfully"));
} else {
@@ -244,14 +236,7 @@ export const AddIntegrationModal = ({
notionIntegrationData.config.data.splice(selectedIntegration!.index, 1);
try {
setIsDeleting(true);
const result = await createOrUpdateIntegrationAction({
environmentId,
integrationData: notionIntegrationData,
});
if (result?.serverError) {
toast.error(getFormattedErrorMessage(result));
return;
}
await createOrUpdateIntegrationAction({ environmentId, integrationData: notionIntegrationData });
toast.success(t("environments.integrations.integration_removed_successfully"));
setOpen(false);
} catch (error) {

View File

@@ -17,7 +17,6 @@ import { TSurvey } from "@formbricks/types/surveys/types";
import { getTextContent } from "@formbricks/types/surveys/validation";
import { createOrUpdateIntegrationAction } from "@/app/(app)/environments/[environmentId]/workspace/integrations/actions";
import SlackLogo from "@/images/slacklogo.png";
import { getFormattedErrorMessage } from "@/lib/utils/helper";
import { recallToHeadline } from "@/lib/utils/recall";
import { getElementsFromBlocks } from "@/modules/survey/lib/client-utils";
import { AdditionalIntegrationSettings } from "@/modules/ui/components/additional-integration-settings";
@@ -145,14 +144,7 @@ export const AddChannelMappingModal = ({
// create action
slackIntegrationData.config.data.push(integrationData);
}
const result = await createOrUpdateIntegrationAction({
environmentId,
integrationData: slackIntegrationData,
});
if (result?.serverError) {
toast.error(getFormattedErrorMessage(result));
return;
}
await createOrUpdateIntegrationAction({ environmentId, integrationData: slackIntegrationData });
if (selectedIntegration) {
toast.success(t("environments.integrations.integration_updated_successfully"));
} else {
@@ -189,14 +181,7 @@ export const AddChannelMappingModal = ({
slackIntegrationData.config.data.splice(selectedIntegration!.index, 1);
try {
setIsDeleting(true);
const result = await createOrUpdateIntegrationAction({
environmentId,
integrationData: slackIntegrationData,
});
if (result?.serverError) {
toast.error(getFormattedErrorMessage(result));
return;
}
await createOrUpdateIntegrationAction({ environmentId, integrationData: slackIntegrationData });
toast.success(t("environments.integrations.integration_removed_successfully"));
setOpen(false);
} catch (error) {

View File

@@ -0,0 +1,39 @@
"use client";
import { usePathname } from "next/navigation";
import { SecondaryNavigation } from "@/modules/ui/components/secondary-navigation";
interface UnifyConfigNavigationProps {
environmentId: string;
activeId?: string;
loading?: boolean;
}
export const UnifyConfigNavigation = ({
environmentId,
activeId: activeIdProp,
loading,
}: UnifyConfigNavigationProps) => {
const pathname = usePathname();
const activeId =
activeIdProp ??
(pathname?.includes("/unify/sources")
? "sources"
: pathname?.includes("/unify/knowledge")
? "knowledge"
: pathname?.includes("/unify/taxonomy")
? "taxonomy"
: "controls");
const baseHref = `/environments/${environmentId}/workspace/unify`;
const navigation = [
{ id: "controls", label: "Controls", href: `${baseHref}/controls` },
{ id: "sources", label: "Sources", href: `${baseHref}/sources` },
{ id: "knowledge", label: "Knowledge", href: `${baseHref}/knowledge` },
{ id: "taxonomy", label: "Taxonomy", href: `${baseHref}/taxonomy` },
];
return <SecondaryNavigation navigation={navigation} activeId={activeId} loading={loading} />;
};

View File

@@ -0,0 +1,90 @@
"use client";
import { useState } from "react";
import { SettingsCard } from "@/app/(app)/environments/[environmentId]/settings/components/SettingsCard";
import { Badge } from "@/modules/ui/components/badge";
import { Label } from "@/modules/ui/components/label";
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
import { PageHeader } from "@/modules/ui/components/page-header";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/modules/ui/components/select";
import { UnifyConfigNavigation } from "../../components/UnifyConfigNavigation";
// Common languages for the base language selector
const COMMON_LANGUAGES = [
{ code: "en", label: "English" },
{ code: "de", label: "German" },
{ code: "fr", label: "French" },
{ code: "es", label: "Spanish" },
{ code: "pt", label: "Portuguese" },
{ code: "it", label: "Italian" },
{ code: "nl", label: "Dutch" },
{ code: "pl", label: "Polish" },
{ code: "ru", label: "Russian" },
{ code: "ja", label: "Japanese" },
{ code: "ko", label: "Korean" },
{ code: "zh-Hans", label: "Chinese (Simplified)" },
{ code: "zh-Hant", label: "Chinese (Traditional)" },
{ code: "ar", label: "Arabic" },
{ code: "hi", label: "Hindi" },
{ code: "tr", label: "Turkish" },
{ code: "sv", label: "Swedish" },
{ code: "no", label: "Norwegian" },
{ code: "da", label: "Danish" },
{ code: "fi", label: "Finnish" },
];
interface ControlsSectionProps {
environmentId: string;
}
export function ControlsSection({ environmentId }: ControlsSectionProps) {
const [baseLanguage, setBaseLanguage] = useState("en");
return (
<PageContentWrapper>
<PageHeader pageTitle="Unify Feedback">
<UnifyConfigNavigation environmentId={environmentId} />
</PageHeader>
<div className="max-w-4xl">
<SettingsCard
title="Feedback Controls"
description="Configure how feedback is processed and consolidated across all sources.">
<div className="space-y-6">
{/* Base Language Setting */}
<div className="space-y-2">
<div className="flex items-center gap-2">
<Label htmlFor="baseLanguage">Base Language</Label>
<Badge text="AI" type="gray" size="tiny" />
</div>
<p className="text-sm text-slate-500">
All feedback will be consolidated and analyzed in this language. Feedback in other languages
will be automatically translated.
</p>
<div className="w-64">
<Select value={baseLanguage} onValueChange={setBaseLanguage}>
<SelectTrigger id="baseLanguage">
<SelectValue placeholder="Select a language" />
</SelectTrigger>
<SelectContent>
{COMMON_LANGUAGES.map((lang) => (
<SelectItem key={lang.code} value={lang.code}>
{lang.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
</SettingsCard>
</div>
</PageContentWrapper>
);
}

View File

@@ -0,0 +1 @@
export { ControlsSection } from "./ControlsSection";

View File

@@ -0,0 +1,10 @@
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
import { ControlsSection } from "./components";
export default async function UnifyControlsPage(props: { params: Promise<{ environmentId: string }> }) {
const params = await props.params;
await getEnvironmentAuth(params.environmentId);
return <ControlsSection environmentId={params.environmentId} />;
}

View File

@@ -0,0 +1,256 @@
"use client";
import { FileTextIcon, LinkIcon, PlusIcon, StickyNoteIcon } from "lucide-react";
import { useState } from "react";
import toast from "react-hot-toast";
import type { TAllowedFileExtension } from "@formbricks/types/storage";
import { cn } from "@/lib/cn";
import { handleFileUpload } from "@/modules/storage/file-upload";
import { Button } from "@/modules/ui/components/button";
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/modules/ui/components/dialog";
import { Uploader } from "@/modules/ui/components/file-input/components/uploader";
import { Input } from "@/modules/ui/components/input";
import { Label } from "@/modules/ui/components/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/modules/ui/components/tabs";
import type { KnowledgeItem } from "../types";
const DOC_EXTENSIONS: TAllowedFileExtension[] = ["pdf", "doc", "docx", "txt", "csv"];
const MAX_DOC_SIZE_MB = 5;
interface AddKnowledgeModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onAdd: (item: KnowledgeItem) => void;
environmentId: string;
isStorageConfigured: boolean;
}
export function AddKnowledgeModal({
open,
onOpenChange,
onAdd,
environmentId,
isStorageConfigured,
}: AddKnowledgeModalProps) {
const [linkUrl, setLinkUrl] = useState("");
const [linkTitle, setLinkTitle] = useState("");
const [noteContent, setNoteContent] = useState("");
const [uploadedDocUrl, setUploadedDocUrl] = useState<string | null>(null);
const [uploadedFileName, setUploadedFileName] = useState<string | null>(null);
const [isUploading, setIsUploading] = useState(false);
const resetForm = () => {
setLinkUrl("");
setLinkTitle("");
setNoteContent("");
setUploadedDocUrl(null);
setUploadedFileName(null);
};
const handleDocUpload = async (files: File[]) => {
if (!isStorageConfigured) {
toast.error("File storage is not configured.");
return;
}
const file = files[0];
if (!file) return;
setIsUploading(true);
setUploadedDocUrl(null);
setUploadedFileName(null);
const result = await handleFileUpload(file, environmentId, DOC_EXTENSIONS);
setIsUploading(false);
if (result.error) {
toast.error("Upload failed. Please try again.");
return;
}
setUploadedDocUrl(result.url);
setUploadedFileName(file.name);
toast.success("Document uploaded. Click Add to save.");
};
const handleAddLink = () => {
if (!linkUrl.trim()) {
toast.error("Please enter a URL.");
return;
}
const now = new Date();
onAdd({
id: crypto.randomUUID(),
type: "link",
title: linkTitle.trim() || undefined,
url: linkUrl.trim(),
size: linkUrl.trim().length * 100, // Simulated size for links
createdAt: now,
indexedAt: now, // Links are indexed immediately
});
resetForm();
onOpenChange(false);
toast.success("Link added.");
};
const handleAddNote = () => {
if (!noteContent.trim()) {
toast.error("Please enter some text.");
return;
}
const now = new Date();
onAdd({
id: crypto.randomUUID(),
type: "note",
content: noteContent.trim(),
size: new Blob([noteContent.trim()]).size,
createdAt: now,
indexedAt: now, // Notes are indexed immediately
});
resetForm();
onOpenChange(false);
toast.success("Note added.");
};
const handleAddFile = () => {
if (!uploadedDocUrl) {
toast.error("Please upload a document first.");
return;
}
const now = new Date();
onAdd({
id: crypto.randomUUID(),
type: "file",
title: uploadedFileName ?? undefined,
fileUrl: uploadedDocUrl,
fileName: uploadedFileName ?? undefined,
size: Math.floor(Math.random() * 500000) + 10000, // Simulated file size (10KB - 500KB)
createdAt: now,
indexedAt: undefined, // Files take time to index - will show as "Pending"
});
resetForm();
onOpenChange(false);
toast.success("Document added.");
};
const handleDrop = (e: React.DragEvent<HTMLLabelElement>) => {
e.preventDefault();
const files = Array.from(e.dataTransfer?.files ?? []);
if (files.length) handleDocUpload(files);
};
const handleDragOver = (e: React.DragEvent<HTMLLabelElement>) => {
e.preventDefault();
e.stopPropagation();
};
return (
<>
<Button onClick={() => onOpenChange(true)} size="sm">
Add knowledge
<PlusIcon className="ml-2 size-4" />
</Button>
<Dialog
open={open}
onOpenChange={(o) => {
if (!o) resetForm();
onOpenChange(o);
}}>
<DialogContent className="sm:max-w-lg" disableCloseOnOutsideClick>
<DialogHeader>
<PlusIcon className="size-5 text-slate-600" />
<DialogTitle>Add knowledge</DialogTitle>
<DialogDescription>Add knowledge via a link, document upload, or a text note.</DialogDescription>
</DialogHeader>
<DialogBody>
<Tabs defaultValue="link" className="w-full">
<TabsList width="fill" className="mb-4 w-full">
<TabsTrigger value="link" icon={<LinkIcon className="size-4" />}>
Link
</TabsTrigger>
<TabsTrigger value="upload" icon={<FileTextIcon className="size-4" />}>
Upload doc
</TabsTrigger>
<TabsTrigger value="note" icon={<StickyNoteIcon className="size-4" />}>
Note
</TabsTrigger>
</TabsList>
<TabsContent value="link" className="space-y-4">
<div className="space-y-2">
<Label htmlFor="link-title">Title (optional)</Label>
<Input
id="link-title"
placeholder="e.g. Product docs"
value={linkTitle}
onChange={(e) => setLinkTitle(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="link-url">URL</Label>
<Input
id="link-url"
type="url"
placeholder="https://..."
value={linkUrl}
onChange={(e) => setLinkUrl(e.target.value)}
/>
</div>
<Button type="button" onClick={handleAddLink} size="sm">
Add link
</Button>
</TabsContent>
<TabsContent value="upload" className="space-y-4">
<Uploader
id="knowledge-doc-modal"
name="knowledge-doc-modal"
uploaderClassName="h-32 w-full"
allowedFileExtensions={DOC_EXTENSIONS}
multiple={false}
handleUpload={handleDocUpload}
handleDrop={handleDrop}
handleDragOver={handleDragOver}
isStorageConfigured={isStorageConfigured}
/>
<p className="text-xs text-slate-500">PDF, Word, text, or CSV. Max {MAX_DOC_SIZE_MB} MB.</p>
{isUploading && <p className="text-sm text-slate-600">Uploading</p>}
{uploadedDocUrl && (
<p className="text-sm text-slate-700">
Ready: <span className="font-medium">{uploadedFileName ?? uploadedDocUrl}</span>
</p>
)}
<Button type="button" onClick={handleAddFile} size="sm" disabled={!uploadedDocUrl}>
Add document
</Button>
</TabsContent>
<TabsContent value="note" className="space-y-4">
<div className="space-y-2">
<Label htmlFor="knowledge-note-modal">Note</Label>
<textarea
id="knowledge-note-modal"
rows={5}
placeholder="Paste or type knowledge content here..."
className={cn(
"focus:border-brand-dark flex w-full rounded-md border border-slate-300 bg-transparent px-3 py-2 text-sm text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-slate-400 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
)}
value={noteContent}
onChange={(e) => setNoteContent(e.target.value)}
/>
</div>
<Button type="button" onClick={handleAddNote} size="sm">
Add note
</Button>
</TabsContent>
</Tabs>
</DialogBody>
</DialogContent>
</Dialog>
</>
);
}

View File

@@ -0,0 +1,47 @@
"use client";
import { useState } from "react";
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
import { PageHeader } from "@/modules/ui/components/page-header";
import { UnifyConfigNavigation } from "../../components/UnifyConfigNavigation";
import type { KnowledgeItem } from "../types";
import { AddKnowledgeModal } from "./AddKnowledgeModal";
import { KnowledgeTable } from "./KnowledgeTable";
interface KnowledgeSectionProps {
environmentId: string;
isStorageConfigured: boolean;
}
export function KnowledgeSection({ environmentId, isStorageConfigured }: KnowledgeSectionProps) {
const [items, setItems] = useState<KnowledgeItem[]>([]);
const [modalOpen, setModalOpen] = useState(false);
const handleDeleteItem = (itemId: string) => {
setItems((prev) => prev.filter((item) => item.id !== itemId));
};
return (
<PageContentWrapper>
<PageHeader
pageTitle="Unify Feedback"
cta={
<AddKnowledgeModal
open={modalOpen}
onOpenChange={setModalOpen}
onAdd={(item) => {
setItems((prev) => [...prev, item]);
setModalOpen(false);
}}
environmentId={environmentId}
isStorageConfigured={isStorageConfigured}
/>
}>
<UnifyConfigNavigation environmentId={environmentId} />
</PageHeader>
<div className="space-y-6">
<KnowledgeTable items={items} onDeleteItem={handleDeleteItem} />
</div>
</PageContentWrapper>
);
}

View File

@@ -0,0 +1,139 @@
"use client";
import { format, formatDistanceToNow } from "date-fns";
import { FileTextIcon, LinkIcon, MoreHorizontalIcon, StickyNoteIcon, TrashIcon } from "lucide-react";
import { useState } from "react";
import { Button } from "@/modules/ui/components/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/modules/ui/components/dropdown-menu";
import { type KnowledgeItem, formatFileSize } from "../types";
interface KnowledgeTableProps {
items: KnowledgeItem[];
onDeleteItem?: (itemId: string) => void;
}
function getTypeIcon(type: KnowledgeItem["type"]) {
switch (type) {
case "link":
return <LinkIcon className="size-4 text-slate-500" />;
case "file":
return <FileTextIcon className="size-4 text-slate-500" />;
case "note":
return <StickyNoteIcon className="size-4 text-slate-500" />;
default:
return <FileTextIcon className="size-4 text-slate-500" />;
}
}
function getTypeLabel(type: KnowledgeItem["type"]) {
switch (type) {
case "link":
return "Link";
case "file":
return "Document";
case "note":
return "Note";
default:
return type;
}
}
function getTitleOrPreview(item: KnowledgeItem): string {
if (item.title) return item.title;
if (item.type === "link" && item.url) return item.url;
if (item.type === "file" && item.fileName) return item.fileName;
if (item.type === "note" && item.content) {
return item.content.length > 60 ? `${item.content.slice(0, 60)}` : item.content;
}
return "—";
}
export function KnowledgeTable({ items, onDeleteItem }: KnowledgeTableProps) {
const [openMenuId, setOpenMenuId] = useState<string | null>(null);
return (
<div className="rounded-xl border border-slate-200 bg-white shadow-sm">
<div className="grid h-12 grid-cols-12 content-center border-b border-slate-200 text-left text-sm font-semibold text-slate-900">
<div className="col-span-5 pl-6">Name</div>
<div className="col-span-2 hidden text-center sm:block">Type</div>
<div className="col-span-2 hidden text-center sm:block">Size</div>
<div className="col-span-2 hidden text-center sm:block">Indexed At</div>
<div className="col-span-1 pr-6 text-right">Actions</div>
</div>
{items.length === 0 ? (
<p className="py-12 text-center text-sm text-slate-400">
No knowledge yet. Add a link, upload a document, or add a note.
</p>
) : (
<div className="divide-y divide-slate-100">
{items.map((item) => (
<div
key={item.id}
className="grid h-12 min-h-12 grid-cols-12 content-center p-2 text-left transition-colors ease-in-out hover:bg-slate-50">
{/* Name */}
<div className="col-span-5 flex items-center gap-3 pl-6">
{getTypeIcon(item.type)}
<div className="flex flex-col overflow-hidden">
<div className="truncate text-sm font-medium text-slate-900">{getTitleOrPreview(item)}</div>
{item.type === "link" && item.url && item.title && (
<div className="truncate text-xs text-slate-500">{item.url}</div>
)}
</div>
</div>
{/* Type */}
<div className="col-span-2 hidden items-center justify-center text-sm text-slate-600 sm:flex">
{getTypeLabel(item.type)}
</div>
{/* Size */}
<div className="col-span-2 hidden items-center justify-center text-sm text-slate-500 sm:flex">
{formatFileSize(item.size)}
</div>
{/* Indexed At */}
<div className="col-span-2 hidden items-center justify-center text-sm text-slate-500 sm:flex">
{item.indexedAt ? (
<span title={format(item.indexedAt, "PPpp")}>
{formatDistanceToNow(item.indexedAt, { addSuffix: true }).replace("about ", "")}
</span>
) : (
<span className="text-slate-400">Pending</span>
)}
</div>
{/* Actions */}
<div className="col-span-1 flex items-center justify-end pr-6">
<DropdownMenu
open={openMenuId === item.id}
onOpenChange={(open) => setOpenMenuId(open ? item.id : null)}>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8">
<MoreHorizontalIcon className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
className="text-red-600 focus:bg-red-50 focus:text-red-700"
onClick={() => {
onDeleteItem?.(item.id);
setOpenMenuId(null);
}}>
<TrashIcon className="mr-2 h-4 w-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,16 @@
import { IS_STORAGE_CONFIGURED } from "@/lib/constants";
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
import { KnowledgeSection } from "./components/KnowledgeSection";
export default async function UnifyKnowledgePage(props: { params: Promise<{ environmentId: string }> }) {
const params = await props.params;
await getEnvironmentAuth(params.environmentId);
return (
<KnowledgeSection
environmentId={params.environmentId}
isStorageConfigured={IS_STORAGE_CONFIGURED}
/>
);
}

View File

@@ -0,0 +1,22 @@
export type KnowledgeItemType = "link" | "note" | "file";
export interface KnowledgeItem {
id: string;
type: KnowledgeItemType;
title?: string;
url?: string;
content?: string;
fileUrl?: string;
fileName?: string;
size?: number; // Size in bytes
createdAt: Date;
indexedAt?: Date;
}
// Format file size to human readable string
export function formatFileSize(bytes?: number): string {
if (!bytes) return "—";
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

View File

@@ -0,0 +1,6 @@
import { redirect } from "next/navigation";
export default async function UnifyPage(props: { params: Promise<{ environmentId: string }> }) {
const params = await props.params;
redirect(`/environments/${params.environmentId}/workspace/unify/controls`);
}

View File

@@ -0,0 +1,396 @@
"use client";
import { PlusIcon, SparklesIcon } from "lucide-react";
import { useState } from "react";
import { Badge } from "@/modules/ui/components/badge";
import { Button } from "@/modules/ui/components/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/modules/ui/components/dialog";
import { Input } from "@/modules/ui/components/input";
import { Label } from "@/modules/ui/components/label";
import { CsvSourceUI } from "./csv-source-ui";
import { FormbricksSurveySelector } from "./formbricks-survey-selector";
import { MappingUI } from "./mapping-ui";
import { SourceTypeSelector } from "./source-type-selector";
import {
AI_SUGGESTED_MAPPINGS,
EMAIL_SOURCE_FIELDS,
FEEDBACK_RECORD_FIELDS,
MOCK_FORMBRICKS_SURVEYS,
SAMPLE_CSV_COLUMNS,
SAMPLE_WEBHOOK_PAYLOAD,
TCreateSourceStep,
TFieldMapping,
TSourceConnection,
TSourceField,
TSourceType,
parseCSVColumnsToFields,
parsePayloadToFields,
} from "./types";
interface CreateSourceModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onCreateSource: (source: TSourceConnection) => void;
}
function getDefaultSourceName(type: TSourceType): string {
switch (type) {
case "formbricks":
return "Formbricks Survey Connection";
case "webhook":
return "Webhook Connection";
case "email":
return "Email Connection";
case "csv":
return "CSV Import";
case "slack":
return "Slack Connection";
default:
return "New Source";
}
}
export function CreateSourceModal({ open, onOpenChange, onCreateSource }: CreateSourceModalProps) {
const [currentStep, setCurrentStep] = useState<TCreateSourceStep>("selectType");
const [selectedType, setSelectedType] = useState<TSourceType | null>(null);
const [sourceName, setSourceName] = useState("");
const [mappings, setMappings] = useState<TFieldMapping[]>([]);
const [sourceFields, setSourceFields] = useState<TSourceField[]>([]);
const [deriveFromAttachments, setDeriveFromAttachments] = useState(false);
// Formbricks-specific state
const [selectedSurveyId, setSelectedSurveyId] = useState<string | null>(null);
const [selectedQuestionIds, setSelectedQuestionIds] = useState<string[]>([]);
const resetForm = () => {
setCurrentStep("selectType");
setSelectedType(null);
setSourceName("");
setMappings([]);
setSourceFields([]);
setDeriveFromAttachments(false);
setSelectedSurveyId(null);
setSelectedQuestionIds([]);
};
const handleOpenChange = (newOpen: boolean) => {
if (!newOpen) {
resetForm();
}
onOpenChange(newOpen);
};
const handleNextStep = () => {
if (currentStep === "selectType" && selectedType && selectedType !== "slack") {
if (selectedType === "formbricks") {
// For Formbricks, use the survey name if selected
const selectedSurvey = MOCK_FORMBRICKS_SURVEYS.find((s) => s.id === selectedSurveyId);
setSourceName(
selectedSurvey ? `${selectedSurvey.name} Connection` : getDefaultSourceName(selectedType)
);
} else {
setSourceName(getDefaultSourceName(selectedType));
}
setCurrentStep("mapping");
}
};
// Formbricks handlers
const handleSurveySelect = (surveyId: string | null) => {
setSelectedSurveyId(surveyId);
};
const handleQuestionToggle = (questionId: string) => {
setSelectedQuestionIds((prev) =>
prev.includes(questionId) ? prev.filter((id) => id !== questionId) : [...prev, questionId]
);
};
const handleSelectAllQuestions = (surveyId: string) => {
const survey = MOCK_FORMBRICKS_SURVEYS.find((s) => s.id === surveyId);
if (survey) {
setSelectedQuestionIds(survey.questions.map((q) => q.id));
}
};
const handleDeselectAllQuestions = () => {
setSelectedQuestionIds([]);
};
const handleBack = () => {
if (currentStep === "mapping") {
setCurrentStep("selectType");
setMappings([]);
setSourceFields([]);
}
};
const handleCreateSource = () => {
if (!selectedType || !sourceName.trim()) return;
// Check if all required fields are mapped
const requiredFields = FEEDBACK_RECORD_FIELDS.filter((f) => f.required);
const allRequiredMapped = requiredFields.every((field) =>
mappings.some((m) => m.targetFieldId === field.id)
);
if (!allRequiredMapped) {
// For now, we'll allow creating without all required fields for POC
console.warn("Not all required fields are mapped");
}
const newSource: TSourceConnection = {
id: crypto.randomUUID(),
name: sourceName.trim(),
type: selectedType,
mappings,
createdAt: new Date(),
updatedAt: new Date(),
};
onCreateSource(newSource);
resetForm();
onOpenChange(false);
};
const requiredFields = FEEDBACK_RECORD_FIELDS.filter((f) => f.required);
const allRequiredMapped = requiredFields.every((field) =>
mappings.some((m) => m.targetFieldId === field.id && (m.sourceFieldId || m.staticValue))
);
// Formbricks validation - need survey and at least one question selected
const isFormbricksValid =
selectedType === "formbricks" && selectedSurveyId && selectedQuestionIds.length > 0;
// CSV validation - need sourceFields loaded (CSV uploaded or sample loaded)
const isCsvValid = selectedType === "csv" && sourceFields.length > 0;
const handleLoadSourceFields = () => {
if (!selectedType) return;
let fields: TSourceField[];
if (selectedType === "webhook") {
fields = parsePayloadToFields(SAMPLE_WEBHOOK_PAYLOAD);
} else if (selectedType === "email") {
fields = EMAIL_SOURCE_FIELDS;
} else if (selectedType === "csv") {
fields = parseCSVColumnsToFields(SAMPLE_CSV_COLUMNS);
} else {
fields = parsePayloadToFields(SAMPLE_WEBHOOK_PAYLOAD);
}
setSourceFields(fields);
};
const handleSuggestMapping = () => {
if (!selectedType) return;
const suggestions = AI_SUGGESTED_MAPPINGS[selectedType];
if (!suggestions) return;
const newMappings: TFieldMapping[] = [];
// Add field mappings from source fields
for (const sourceField of sourceFields) {
const suggestedTarget = suggestions.fieldMappings[sourceField.id];
if (suggestedTarget) {
const targetExists = FEEDBACK_RECORD_FIELDS.find((f) => f.id === suggestedTarget);
if (targetExists) {
newMappings.push({
sourceFieldId: sourceField.id,
targetFieldId: suggestedTarget,
});
}
}
}
// Add static value mappings
for (const [targetFieldId, staticValue] of Object.entries(suggestions.staticValues)) {
const targetExists = FEEDBACK_RECORD_FIELDS.find((f) => f.id === targetFieldId);
if (targetExists) {
if (!newMappings.some((m) => m.targetFieldId === targetFieldId)) {
newMappings.push({
targetFieldId,
staticValue,
});
}
}
}
setMappings(newMappings);
};
const getLoadButtonLabel = () => {
switch (selectedType) {
case "webhook":
return "Simulate webhook";
case "email":
return "Load email fields";
case "csv":
return "Load sample CSV";
default:
return "Load sample";
}
};
return (
<>
<Button onClick={() => onOpenChange(true)} size="sm">
Add source
<PlusIcon className="ml-2 h-4 w-4" />
</Button>
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="max-w-3xl">
<DialogHeader>
<DialogTitle>
{currentStep === "selectType"
? "Add Feedback Source"
: selectedType === "formbricks"
? "Select Survey & Questions"
: selectedType === "csv"
? "Import CSV Data"
: "Configure Mapping"}
</DialogTitle>
<DialogDescription>
{currentStep === "selectType"
? "Select the type of feedback source you want to connect."
: selectedType === "formbricks"
? "Choose which survey questions should create FeedbackRecords."
: selectedType === "csv"
? "Upload a CSV file or set up automated S3 imports."
: "Map source fields to Hub Feedback Record fields."}
</DialogDescription>
</DialogHeader>
<div className="py-4">
{currentStep === "selectType" ? (
<SourceTypeSelector selectedType={selectedType} onSelectType={setSelectedType} />
) : selectedType === "formbricks" ? (
/* Formbricks Survey Selector UI */
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="sourceName">Source Name</Label>
<Input
id="sourceName"
value={sourceName}
onChange={(e) => setSourceName(e.target.value)}
placeholder="Enter a name for this source"
/>
</div>
<div className="max-h-[50vh] overflow-y-auto rounded-lg border border-slate-200 bg-slate-50 p-4">
<FormbricksSurveySelector
selectedSurveyId={selectedSurveyId}
selectedQuestionIds={selectedQuestionIds}
onSurveySelect={handleSurveySelect}
onQuestionToggle={handleQuestionToggle}
onSelectAllQuestions={handleSelectAllQuestions}
onDeselectAllQuestions={handleDeselectAllQuestions}
/>
</div>
</div>
) : selectedType === "csv" ? (
/* CSV Upload & S3 Integration UI */
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="sourceName">Source Name</Label>
<Input
id="sourceName"
value={sourceName}
onChange={(e) => setSourceName(e.target.value)}
placeholder="Enter a name for this source"
/>
</div>
<div className="max-h-[55vh] overflow-y-auto rounded-lg border border-slate-200 bg-slate-50 p-4">
<CsvSourceUI
sourceFields={sourceFields}
mappings={mappings}
onMappingsChange={setMappings}
onSourceFieldsChange={setSourceFields}
onLoadSampleCSV={handleLoadSourceFields}
/>
</div>
</div>
) : (
/* Other source types (webhook, email) - Mapping UI */
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="sourceName">Source Name</Label>
<Input
id="sourceName"
value={sourceName}
onChange={(e) => setSourceName(e.target.value)}
placeholder="Enter a name for this source"
/>
</div>
{/* Action buttons above scrollable area */}
<div className="flex items-center justify-between">
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={handleLoadSourceFields}>
{getLoadButtonLabel()}
</Button>
{sourceFields.length > 0 && (
<Button variant="outline" size="sm" onClick={handleSuggestMapping} className="gap-2">
<SparklesIcon className="h-4 w-4 text-purple-500" />
Suggest mapping
<Badge text="AI" type="gray" size="tiny" className="ml-1" />
</Button>
)}
</div>
</div>
<div className="max-h-[50vh] overflow-y-auto rounded-lg border border-slate-200 bg-slate-50 p-4">
<MappingUI
sourceFields={sourceFields}
mappings={mappings}
onMappingsChange={setMappings}
sourceType={selectedType!}
deriveFromAttachments={deriveFromAttachments}
onDeriveFromAttachmentsChange={setDeriveFromAttachments}
/>
</div>
</div>
)}
</div>
<DialogFooter>
{currentStep === "mapping" && (
<Button variant="outline" onClick={handleBack}>
Back
</Button>
)}
{currentStep === "selectType" ? (
<Button onClick={handleNextStep} disabled={!selectedType || selectedType === "slack"}>
{selectedType === "formbricks"
? "Select questions"
: selectedType === "csv"
? "Configure import"
: "Create mapping"}
</Button>
) : (
<Button
onClick={handleCreateSource}
disabled={
!sourceName.trim() ||
(selectedType === "formbricks"
? !isFormbricksValid
: selectedType === "csv"
? !isCsvValid
: !allRequiredMapped)
}>
Setup connection
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}

View File

@@ -0,0 +1,327 @@
"use client";
import {
ArrowUpFromLineIcon,
CloudIcon,
CopyIcon,
FolderIcon,
RefreshCwIcon,
SettingsIcon,
} from "lucide-react";
import { useState } from "react";
import { Badge } from "@/modules/ui/components/badge";
import { Button } from "@/modules/ui/components/button";
import { Input } from "@/modules/ui/components/input";
import { Label } from "@/modules/ui/components/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/modules/ui/components/select";
import { Switch } from "@/modules/ui/components/switch";
import { MappingUI } from "./mapping-ui";
import { TFieldMapping, TSourceField } from "./types";
interface CsvSourceUIProps {
sourceFields: TSourceField[];
mappings: TFieldMapping[];
onMappingsChange: (mappings: TFieldMapping[]) => void;
onSourceFieldsChange: (fields: TSourceField[]) => void;
onLoadSampleCSV: () => void;
}
export function CsvSourceUI({
sourceFields,
mappings,
onMappingsChange,
onSourceFieldsChange,
onLoadSampleCSV,
}: CsvSourceUIProps) {
const [csvFile, setCsvFile] = useState<File | null>(null);
const [csvPreview, setCsvPreview] = useState<string[][]>([]);
const [showMapping, setShowMapping] = useState(false);
const [s3AutoSync, setS3AutoSync] = useState(false);
const [s3Copied, setS3Copied] = useState(false);
// Mock S3 bucket details
const s3BucketName = "formbricks-feedback-imports";
const s3Path = `s3://${s3BucketName}/feedback/incoming/`;
const handleCopyS3Path = () => {
navigator.clipboard.writeText(s3Path);
setS3Copied(true);
setTimeout(() => setS3Copied(false), 2000);
};
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target?.files?.[0];
if (file) {
processCSVFile(file);
}
};
const processCSVFile = (file: File) => {
if (!file.name.endsWith(".csv")) {
return;
}
setCsvFile(file);
const reader = new FileReader();
reader.onload = (e) => {
const csv = e.target?.result as string;
const lines = csv.split("\n").slice(0, 6); // Preview first 5 rows + header
const preview = lines.map((line) => line.split(",").map((cell) => cell.trim()));
setCsvPreview(preview);
// Extract columns and create source fields
if (preview.length > 0) {
const headers = preview[0];
const fields: TSourceField[] = headers.map((header) => ({
id: header,
name: header,
type: "string",
sampleValue: preview[1]?.[headers.indexOf(header)] || "",
}));
onSourceFieldsChange(fields);
setShowMapping(true);
}
};
reader.readAsText(file);
};
const handleDragOver = (e: React.DragEvent<HTMLLabelElement>) => {
e.preventDefault();
e.stopPropagation();
};
const handleDrop = (e: React.DragEvent<HTMLLabelElement>) => {
e.preventDefault();
e.stopPropagation();
const file = e.dataTransfer.files[0];
if (file) {
processCSVFile(file);
}
};
const handleLoadSample = () => {
onLoadSampleCSV();
setShowMapping(true);
};
// If mapping is shown, show the mapping UI
if (showMapping && sourceFields.length > 0) {
return (
<div className="space-y-4">
{/* File info bar */}
{csvFile && (
<div className="flex items-center justify-between rounded-lg border border-green-200 bg-green-50 px-4 py-2">
<div className="flex items-center gap-2">
<FolderIcon className="h-4 w-4 text-green-600" />
<span className="text-sm font-medium text-green-800">{csvFile.name}</span>
<Badge text={`${csvPreview.length - 1} rows`} type="success" size="tiny" />
</div>
<Button
variant="ghost"
size="sm"
onClick={() => {
setCsvFile(null);
setCsvPreview([]);
setShowMapping(false);
onSourceFieldsChange([]);
}}>
Change file
</Button>
</div>
)}
{/* CSV Preview Table */}
{csvPreview.length > 0 && (
<div className="overflow-hidden rounded-lg border border-slate-200">
<div className="overflow-x-auto">
<table className="min-w-full text-sm">
<thead className="bg-slate-50">
<tr>
{csvPreview[0]?.map((header, i) => (
<th key={i} className="px-3 py-2 text-left font-medium text-slate-700">
{header}
</th>
))}
</tr>
</thead>
<tbody>
{csvPreview.slice(1, 4).map((row, rowIndex) => (
<tr key={rowIndex} className="border-t border-slate-100">
{row.map((cell, cellIndex) => (
<td key={cellIndex} className="px-3 py-2 text-slate-600">
{cell || <span className="text-slate-300"></span>}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
{csvPreview.length > 4 && (
<div className="border-t border-slate-100 bg-slate-50 px-3 py-1.5 text-center text-xs text-slate-500">
Showing 3 of {csvPreview.length - 1} rows
</div>
)}
</div>
)}
{/* Mapping UI */}
<MappingUI
sourceFields={sourceFields}
mappings={mappings}
onMappingsChange={onMappingsChange}
sourceType="csv"
/>
</div>
);
}
// Upload and S3 setup UI
return (
<div className="space-y-6">
{/* Manual Upload Section */}
<div className="space-y-3">
<h4 className="text-sm font-medium text-slate-700">Upload CSV File</h4>
<div className="rounded-lg border-2 border-dashed border-slate-300 bg-slate-50 p-6">
<label
htmlFor="csv-file-upload"
className="flex cursor-pointer flex-col items-center justify-center"
onDragOver={handleDragOver}
onDrop={handleDrop}>
<ArrowUpFromLineIcon className="h-8 w-8 text-slate-400" />
<p className="mt-2 text-sm text-slate-600">
<span className="font-semibold">Click to upload</span> or drag and drop
</p>
<p className="mt-1 text-xs text-slate-400">CSV files only</p>
<input
type="file"
id="csv-file-upload"
accept=".csv"
className="hidden"
onChange={handleFileUpload}
/>
</label>
</div>
<div className="flex justify-between">
<Button variant="secondary" size="sm" onClick={handleLoadSample}>
Load sample CSV
</Button>
</div>
</div>
{/* Divider */}
<div className="flex items-center gap-4">
<div className="h-px flex-1 bg-slate-200" />
<span className="text-xs font-medium uppercase text-slate-400">or</span>
<div className="h-px flex-1 bg-slate-200" />
</div>
{/* S3 Integration Section */}
<div className="space-y-4">
<div className="flex items-center gap-2">
<CloudIcon className="h-5 w-5 text-slate-500" />
<h4 className="text-sm font-medium text-slate-700">S3 Bucket Integration</h4>
<Badge text="Automated" type="gray" size="tiny" />
</div>
<div className="rounded-lg border border-slate-200 bg-white p-4">
<p className="mb-4 text-sm text-slate-600">
Drop CSV files into your S3 bucket to automatically import feedback. Files are processed every 15
minutes.
</p>
{/* S3 Path Display */}
<div className="space-y-3">
<div className="space-y-1.5">
<Label className="text-xs">Drop zone path</Label>
<div className="flex items-center gap-2">
<code className="flex-1 rounded bg-slate-100 px-3 py-2 font-mono text-sm text-slate-700">
{s3Path}
</code>
<Button variant="outline" size="sm" onClick={handleCopyS3Path}>
<CopyIcon className="h-4 w-4" />
{s3Copied ? "Copied!" : "Copy"}
</Button>
</div>
</div>
{/* S3 Settings */}
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<Label className="text-xs">AWS Region</Label>
<Select defaultValue="eu-central-1">
<SelectTrigger className="bg-white">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="us-east-1">US East (N. Virginia)</SelectItem>
<SelectItem value="us-west-2">US West (Oregon)</SelectItem>
<SelectItem value="eu-central-1">EU (Frankfurt)</SelectItem>
<SelectItem value="eu-west-1">EU (Ireland)</SelectItem>
<SelectItem value="ap-southeast-1">Asia Pacific (Singapore)</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Processing interval</Label>
<Select defaultValue="15">
<SelectTrigger className="bg-white">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">Every 5 minutes</SelectItem>
<SelectItem value="15">Every 15 minutes</SelectItem>
<SelectItem value="30">Every 30 minutes</SelectItem>
<SelectItem value="60">Every hour</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{/* Auto-sync toggle */}
<div className="flex items-center justify-between rounded-lg border border-slate-200 bg-slate-50 p-3">
<div className="flex flex-col gap-0.5">
<span className="text-sm font-medium text-slate-900">Enable auto-sync</span>
<span className="text-xs text-slate-500">
Automatically process new files dropped in the bucket
</span>
</div>
<Switch checked={s3AutoSync} onCheckedChange={setS3AutoSync} />
</div>
{/* IAM Instructions */}
<div className="rounded-lg border border-amber-200 bg-amber-50 p-3">
<div className="flex items-start gap-2">
<SettingsIcon className="mt-0.5 h-4 w-4 text-amber-600" />
<div>
<p className="text-sm font-medium text-amber-800">IAM Configuration Required</p>
<p className="mt-1 text-xs text-amber-700">
Add the Formbricks IAM role to your S3 bucket policy to enable access.{" "}
<button type="button" className="font-medium underline hover:no-underline">
View setup guide
</button>
</p>
</div>
</div>
</div>
{/* Test Connection */}
<div className="flex justify-end">
<Button variant="outline" size="sm" className="gap-2">
<RefreshCwIcon className="h-4 w-4" />
Test connection
</Button>
</div>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,299 @@
"use client";
import {
FileSpreadsheetIcon,
GlobeIcon,
MailIcon,
MessageSquareIcon,
SparklesIcon,
WebhookIcon,
} from "lucide-react";
import { useEffect, useState } from "react";
import { Badge } from "@/modules/ui/components/badge";
import { Button } from "@/modules/ui/components/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/modules/ui/components/dialog";
import { Input } from "@/modules/ui/components/input";
import { Label } from "@/modules/ui/components/label";
import { MappingUI } from "./mapping-ui";
import {
AI_SUGGESTED_MAPPINGS,
EMAIL_SOURCE_FIELDS,
FEEDBACK_RECORD_FIELDS,
SAMPLE_CSV_COLUMNS,
SAMPLE_WEBHOOK_PAYLOAD,
TFieldMapping,
TSourceConnection,
TSourceField,
TSourceType,
parseCSVColumnsToFields,
parsePayloadToFields,
} from "./types";
interface EditSourceModalProps {
source: TSourceConnection | null;
open: boolean;
onOpenChange: (open: boolean) => void;
onUpdateSource: (source: TSourceConnection) => void;
onDeleteSource: (sourceId: string) => void;
}
function getSourceIcon(type: TSourceType) {
switch (type) {
case "formbricks":
return <GlobeIcon className="h-5 w-5 text-slate-500" />;
case "webhook":
return <WebhookIcon className="h-5 w-5 text-slate-500" />;
case "email":
return <MailIcon className="h-5 w-5 text-slate-500" />;
case "csv":
return <FileSpreadsheetIcon className="h-5 w-5 text-slate-500" />;
case "slack":
return <MessageSquareIcon className="h-5 w-5 text-slate-500" />;
default:
return <GlobeIcon className="h-5 w-5 text-slate-500" />;
}
}
function getSourceTypeLabel(type: TSourceType) {
switch (type) {
case "formbricks":
return "Formbricks Surveys";
case "webhook":
return "Webhook";
case "email":
return "Email";
case "csv":
return "CSV Import";
case "slack":
return "Slack Message";
default:
return type;
}
}
function getInitialSourceFields(type: TSourceType): TSourceField[] {
switch (type) {
case "webhook":
return parsePayloadToFields(SAMPLE_WEBHOOK_PAYLOAD);
case "email":
return EMAIL_SOURCE_FIELDS;
case "csv":
return parseCSVColumnsToFields(SAMPLE_CSV_COLUMNS);
default:
return [];
}
}
export function EditSourceModal({
source,
open,
onOpenChange,
onUpdateSource,
onDeleteSource,
}: EditSourceModalProps) {
const [sourceName, setSourceName] = useState("");
const [mappings, setMappings] = useState<TFieldMapping[]>([]);
const [sourceFields, setSourceFields] = useState<TSourceField[]>([]);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [deriveFromAttachments, setDeriveFromAttachments] = useState(false);
useEffect(() => {
if (source) {
setSourceName(source.name);
setMappings(source.mappings);
setSourceFields(getInitialSourceFields(source.type));
setDeriveFromAttachments(false);
}
}, [source]);
const resetForm = () => {
setSourceName("");
setMappings([]);
setSourceFields([]);
setShowDeleteConfirm(false);
setDeriveFromAttachments(false);
};
const handleOpenChange = (newOpen: boolean) => {
if (!newOpen) {
resetForm();
}
onOpenChange(newOpen);
};
const handleUpdateSource = () => {
if (!source || !sourceName.trim()) return;
const updatedSource: TSourceConnection = {
...source,
name: sourceName.trim(),
mappings,
updatedAt: new Date(),
};
onUpdateSource(updatedSource);
handleOpenChange(false);
};
const handleDeleteSource = () => {
if (!source) return;
onDeleteSource(source.id);
handleOpenChange(false);
};
const handleLoadSourceFields = () => {
if (!source) return;
let fields: TSourceField[];
if (source.type === "webhook") {
fields = parsePayloadToFields(SAMPLE_WEBHOOK_PAYLOAD);
} else if (source.type === "email") {
fields = EMAIL_SOURCE_FIELDS;
} else if (source.type === "csv") {
fields = parseCSVColumnsToFields(SAMPLE_CSV_COLUMNS);
} else {
fields = parsePayloadToFields(SAMPLE_WEBHOOK_PAYLOAD);
}
setSourceFields(fields);
};
const handleSuggestMapping = () => {
if (!source) return;
const suggestions = AI_SUGGESTED_MAPPINGS[source.type];
if (!suggestions) return;
const newMappings: TFieldMapping[] = [];
for (const sourceField of sourceFields) {
const suggestedTarget = suggestions.fieldMappings[sourceField.id];
if (suggestedTarget) {
const targetExists = FEEDBACK_RECORD_FIELDS.find((f) => f.id === suggestedTarget);
if (targetExists) {
newMappings.push({
sourceFieldId: sourceField.id,
targetFieldId: suggestedTarget,
});
}
}
}
for (const [targetFieldId, staticValue] of Object.entries(suggestions.staticValues)) {
const targetExists = FEEDBACK_RECORD_FIELDS.find((f) => f.id === targetFieldId);
if (targetExists) {
if (!newMappings.some((m) => m.targetFieldId === targetFieldId)) {
newMappings.push({
targetFieldId,
staticValue,
});
}
}
}
setMappings(newMappings);
};
const getLoadButtonLabel = () => {
switch (source?.type) {
case "webhook":
return "Simulate webhook";
case "email":
return "Load email fields";
case "csv":
return "Load sample CSV";
default:
return "Load sample";
}
};
if (!source) return null;
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="max-w-3xl">
<DialogHeader>
<DialogTitle>Edit Source Connection</DialogTitle>
<DialogDescription>Update the mapping configuration for this source.</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{/* Source Type Display */}
<div className="flex items-center gap-3 rounded-lg border border-slate-200 bg-slate-50 p-3">
{getSourceIcon(source.type)}
<div>
<p className="text-sm font-medium text-slate-900">{getSourceTypeLabel(source.type)}</p>
<p className="text-xs text-slate-500">Source type cannot be changed</p>
</div>
</div>
{/* Source Name */}
<div className="space-y-2">
<Label htmlFor="editSourceName">Source Name</Label>
<Input
id="editSourceName"
value={sourceName}
onChange={(e) => setSourceName(e.target.value)}
placeholder="Enter a name for this source"
/>
</div>
{/* Action buttons above scrollable area */}
<div className="flex items-center justify-between">
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={handleLoadSourceFields}>
{getLoadButtonLabel()}
</Button>
{sourceFields.length > 0 && (
<Button variant="outline" size="sm" onClick={handleSuggestMapping} className="gap-2">
<SparklesIcon className="h-4 w-4 text-purple-500" />
Suggest mapping
<Badge text="AI" type="gray" size="tiny" className="ml-1" />
</Button>
)}
</div>
</div>
{/* Mapping UI */}
<div className="max-h-[50vh] overflow-y-auto rounded-lg border border-slate-200 bg-slate-50 p-4">
<MappingUI
sourceFields={sourceFields}
mappings={mappings}
onMappingsChange={setMappings}
sourceType={source.type}
deriveFromAttachments={deriveFromAttachments}
onDeriveFromAttachmentsChange={setDeriveFromAttachments}
/>
</div>
</div>
<DialogFooter className="flex justify-between">
<div>
{showDeleteConfirm ? (
<div className="flex items-center gap-2">
<span className="text-sm text-red-600">Are you sure?</span>
<Button variant="destructive" size="sm" onClick={handleDeleteSource}>
Yes, delete
</Button>
<Button variant="outline" size="sm" onClick={() => setShowDeleteConfirm(false)}>
Cancel
</Button>
</div>
) : (
<Button variant="outline" onClick={() => setShowDeleteConfirm(true)}>
Delete source
</Button>
)}
</div>
<Button onClick={handleUpdateSource} disabled={!sourceName.trim()}>
Save changes
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,201 @@
"use client";
import {
CheckCircle2Icon,
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
CircleIcon,
FileTextIcon,
MessageSquareTextIcon,
StarIcon,
} from "lucide-react";
import { useState } from "react";
import { Badge } from "@/modules/ui/components/badge";
import {
MOCK_FORMBRICKS_SURVEYS,
TFormbricksSurvey,
TFormbricksSurveyQuestion,
getQuestionTypeLabel,
} from "./types";
interface FormbricksSurveySelectorProps {
selectedSurveyId: string | null;
selectedQuestionIds: string[];
onSurveySelect: (surveyId: string | null) => void;
onQuestionToggle: (questionId: string) => void;
onSelectAllQuestions: (surveyId: string) => void;
onDeselectAllQuestions: () => void;
}
function getQuestionIcon(type: TFormbricksSurveyQuestion["type"]) {
switch (type) {
case "openText":
return <MessageSquareTextIcon className="h-4 w-4 text-slate-500" />;
case "rating":
case "nps":
case "csat":
return <StarIcon className="h-4 w-4 text-amber-500" />;
default:
return <FileTextIcon className="h-4 w-4 text-slate-500" />;
}
}
function getStatusBadge(status: TFormbricksSurvey["status"]) {
switch (status) {
case "active":
return <Badge text="Active" type="success" size="tiny" />;
case "paused":
return <Badge text="Paused" type="warning" size="tiny" />;
case "draft":
return <Badge text="Draft" type="gray" size="tiny" />;
case "completed":
return <Badge text="Completed" type="gray" size="tiny" />;
default:
return null;
}
}
export function FormbricksSurveySelector({
selectedSurveyId,
selectedQuestionIds,
onSurveySelect,
onQuestionToggle,
onSelectAllQuestions,
onDeselectAllQuestions,
}: FormbricksSurveySelectorProps) {
const [expandedSurveyId, setExpandedSurveyId] = useState<string | null>(null);
const selectedSurvey = MOCK_FORMBRICKS_SURVEYS.find((s) => s.id === selectedSurveyId);
const handleSurveyClick = (survey: TFormbricksSurvey) => {
if (selectedSurveyId === survey.id) {
// Toggle expand/collapse if already selected
setExpandedSurveyId(expandedSurveyId === survey.id ? null : survey.id);
} else {
// Select the survey and expand it
onSurveySelect(survey.id);
onDeselectAllQuestions();
setExpandedSurveyId(survey.id);
}
};
const allQuestionsSelected =
selectedSurvey && selectedQuestionIds.length === selectedSurvey.questions.length;
return (
<div className="grid grid-cols-2 gap-6">
{/* Left: Survey List */}
<div className="space-y-3">
<h4 className="text-sm font-medium text-slate-700">Select Survey</h4>
<div className="space-y-2">
{MOCK_FORMBRICKS_SURVEYS.map((survey) => {
const isSelected = selectedSurveyId === survey.id;
const isExpanded = expandedSurveyId === survey.id;
return (
<div key={survey.id}>
<button
type="button"
onClick={() => handleSurveyClick(survey)}
className={`flex w-full items-center gap-3 rounded-lg border p-3 text-left transition-colors ${
isSelected
? "border-brand-dark bg-slate-50"
: "border-slate-200 bg-white hover:border-slate-300"
}`}>
<div className="flex h-8 w-8 items-center justify-center rounded-md bg-slate-100">
{isExpanded ? (
<ChevronDownIcon className="h-4 w-4 text-slate-600" />
) : (
<ChevronRightIcon className="h-4 w-4 text-slate-600" />
)}
</div>
<div className="flex-1">
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-slate-900">{survey.name}</span>
{getStatusBadge(survey.status)}
</div>
<p className="text-xs text-slate-500">
{survey.questions.length} questions · {survey.responseCount.toLocaleString()} responses
</p>
</div>
{isSelected && <CheckCircle2Icon className="text-brand-dark h-5 w-5" />}
</button>
</div>
);
})}
</div>
</div>
{/* Right: Question Selection */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<h4 className="text-sm font-medium text-slate-700">Select Questions</h4>
{selectedSurvey && (
<button
type="button"
onClick={() =>
allQuestionsSelected ? onDeselectAllQuestions() : onSelectAllQuestions(selectedSurvey.id)
}
className="text-xs text-slate-500 hover:text-slate-700">
{allQuestionsSelected ? "Deselect all" : "Select all"}
</button>
)}
</div>
{!selectedSurvey ? (
<div className="flex h-64 items-center justify-center rounded-lg border border-dashed border-slate-300 bg-slate-50">
<p className="text-sm text-slate-500">Select a survey to see its questions</p>
</div>
) : (
<div className="space-y-2">
{selectedSurvey.questions.map((question) => {
const isSelected = selectedQuestionIds.includes(question.id);
return (
<button
key={question.id}
type="button"
onClick={() => onQuestionToggle(question.id)}
className={`flex w-full items-center gap-3 rounded-lg border p-3 text-left transition-colors ${
isSelected
? "border-green-300 bg-green-50"
: "border-slate-200 bg-white hover:border-slate-300"
}`}>
<div
className={`flex h-5 w-5 items-center justify-center rounded ${
isSelected ? "bg-green-500 text-white" : "border border-slate-300 bg-white"
}`}>
{isSelected && <CheckIcon className="h-3 w-3" />}
</div>
<div className="flex items-center gap-2">{getQuestionIcon(question.type)}</div>
<div className="flex-1">
<p className="text-sm text-slate-900">{question.headline}</p>
<div className="flex items-center gap-2">
<span className="text-xs text-slate-500">{getQuestionTypeLabel(question.type)}</span>
{question.required && (
<span className="text-xs text-red-500">
<CircleIcon className="inline h-1.5 w-1.5 fill-current" /> Required
</span>
)}
</div>
</div>
</button>
);
})}
{selectedQuestionIds.length > 0 && (
<div className="mt-4 rounded-lg border border-blue-200 bg-blue-50 p-3">
<p className="text-xs text-blue-700">
<strong>{selectedQuestionIds.length}</strong> question
{selectedQuestionIds.length !== 1 ? "s" : ""} selected. Each response to these questions
will create a FeedbackRecord in the Hub.
</p>
</div>
)}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,10 @@
export { CreateSourceModal } from "./create-source-modal";
export { CsvSourceUI } from "./csv-source-ui";
export { EditSourceModal } from "./edit-source-modal";
export { FormbricksSurveySelector } from "./formbricks-survey-selector";
export { MappingUI } from "./mapping-ui";
export { SourcesSection } from "./sources-page-client";
export { SourcesTable } from "./sources-table";
export { SourcesTableDataRow } from "./sources-table-data-row";
export { SourceTypeSelector } from "./source-type-selector";
export * from "./types";

View File

@@ -0,0 +1,305 @@
"use client";
import { useDraggable, useDroppable } from "@dnd-kit/core";
import { ChevronDownIcon, GripVerticalIcon, PencilIcon, XIcon } from "lucide-react";
import { useState } from "react";
import { Input } from "@/modules/ui/components/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/modules/ui/components/select";
import { TFieldMapping, TSourceField, TTargetField } from "./types";
interface DraggableSourceFieldProps {
field: TSourceField;
isMapped: boolean;
}
export function DraggableSourceField({ field, isMapped }: DraggableSourceFieldProps) {
const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
id: field.id,
data: field,
});
const style = transform
? {
transform: `translate3d(${transform.x}px, ${transform.y}px, 0)`,
}
: undefined;
return (
<div
ref={setNodeRef}
style={style}
{...listeners}
{...attributes}
className={`flex cursor-grab items-center gap-2 rounded-md border p-2 text-sm transition-colors ${
isDragging
? "border-brand-dark bg-slate-100 opacity-50"
: isMapped
? "border-green-300 bg-green-50 text-green-800"
: "border-slate-200 bg-white hover:border-slate-300"
}`}>
<GripVerticalIcon className="h-4 w-4 text-slate-400" />
<div className="flex-1 truncate">
<span className="font-medium">{field.name}</span>
<span className="ml-2 text-xs text-slate-500">({field.type})</span>
</div>
{field.sampleValue && (
<span className="max-w-24 truncate text-xs text-slate-400">{field.sampleValue}</span>
)}
</div>
);
}
interface DroppableTargetFieldProps {
field: TTargetField;
mappedSourceField: TSourceField | null;
mapping: TFieldMapping | null;
onRemoveMapping: () => void;
onStaticValueChange: (value: string) => void;
isOver?: boolean;
}
export function DroppableTargetField({
field,
mappedSourceField,
mapping,
onRemoveMapping,
onStaticValueChange,
isOver,
}: DroppableTargetFieldProps) {
const { setNodeRef, isOver: isOverCurrent } = useDroppable({
id: field.id,
data: field,
});
const [isEditingStatic, setIsEditingStatic] = useState(false);
const [customValue, setCustomValue] = useState("");
const isActive = isOver || isOverCurrent;
const hasMapping = mappedSourceField || mapping?.staticValue;
// Handle enum field type - show dropdown
if (field.type === "enum" && field.enumValues) {
return (
<div
ref={setNodeRef}
className={`flex items-center gap-2 rounded-md border p-2 text-sm transition-colors ${
mapping?.staticValue ? "border-green-300 bg-green-50" : "border-dashed border-slate-300 bg-slate-50"
}`}>
<div className="flex flex-1 flex-col gap-1">
<div className="flex items-center gap-2">
<span className="font-medium text-slate-900">{field.name}</span>
{field.required && <span className="text-xs text-red-500">*</span>}
<span className="text-xs text-slate-400">(enum)</span>
</div>
<Select value={mapping?.staticValue || ""} onValueChange={onStaticValueChange}>
<SelectTrigger className="h-8 w-full bg-white">
<SelectValue placeholder="Select a value..." />
</SelectTrigger>
<SelectContent>
{field.enumValues.map((value) => (
<SelectItem key={value} value={value}>
{value}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
);
}
// Handle string fields - allow drag & drop OR static value
if (field.type === "string") {
return (
<div
ref={setNodeRef}
className={`flex items-center gap-2 rounded-md border p-2 text-sm transition-colors ${
isActive
? "border-brand-dark bg-slate-100"
: hasMapping
? "border-green-300 bg-green-50"
: "border-dashed border-slate-300 bg-slate-50"
}`}>
<div className="flex flex-1 flex-col gap-1">
<div className="flex items-center gap-2">
<span className="font-medium text-slate-900">{field.name}</span>
{field.required && <span className="text-xs text-red-500">*</span>}
</div>
{/* Show mapped source field */}
{mappedSourceField && !mapping?.staticValue && (
<div className="flex items-center gap-1">
<span className="text-xs text-green-700"> {mappedSourceField.name}</span>
<button
type="button"
onClick={onRemoveMapping}
className="ml-1 rounded p-0.5 hover:bg-green-100">
<XIcon className="h-3 w-3 text-green-600" />
</button>
</div>
)}
{/* Show static value */}
{mapping?.staticValue && !mappedSourceField && (
<div className="flex items-center gap-1">
<span className="rounded bg-blue-100 px-1.5 py-0.5 text-xs text-blue-700">
= "{mapping.staticValue}"
</span>
<button
type="button"
onClick={onRemoveMapping}
className="ml-1 rounded p-0.5 hover:bg-blue-100">
<XIcon className="h-3 w-3 text-blue-600" />
</button>
</div>
)}
{/* Show input for entering static value when editing */}
{isEditingStatic && !hasMapping && (
<div className="flex items-center gap-1">
<Input
type="text"
value={customValue}
onChange={(e) => setCustomValue(e.target.value)}
placeholder={
field.exampleStaticValues ? `e.g., ${field.exampleStaticValues[0]}` : "Enter value..."
}
className="h-7 text-xs"
autoFocus
onKeyDown={(e) => {
if (e.key === "Enter" && customValue.trim()) {
onStaticValueChange(customValue.trim());
setCustomValue("");
setIsEditingStatic(false);
}
if (e.key === "Escape") {
setCustomValue("");
setIsEditingStatic(false);
}
}}
/>
<button
type="button"
onClick={() => {
if (customValue.trim()) {
onStaticValueChange(customValue.trim());
setCustomValue("");
}
setIsEditingStatic(false);
}}
className="rounded p-1 text-slate-500 hover:bg-slate-200">
<ChevronDownIcon className="h-3 w-3" />
</button>
</div>
)}
{/* Show example values as quick select OR drop zone */}
{!hasMapping && !isEditingStatic && (
<div className="flex flex-wrap items-center gap-1">
<span className="text-xs text-slate-400">Drop field or</span>
<button
type="button"
onClick={() => setIsEditingStatic(true)}
className="flex items-center gap-1 rounded px-1 py-0.5 text-xs text-slate-500 hover:bg-slate-200">
<PencilIcon className="h-3 w-3" />
set value
</button>
{field.exampleStaticValues && field.exampleStaticValues.length > 0 && (
<>
<span className="text-xs text-slate-300">|</span>
{field.exampleStaticValues.slice(0, 3).map((val) => (
<button
key={val}
type="button"
onClick={() => onStaticValueChange(val)}
className="rounded bg-slate-100 px-1.5 py-0.5 text-xs text-slate-600 hover:bg-slate-200">
{val}
</button>
))}
</>
)}
</div>
)}
</div>
</div>
);
}
// Helper to get display label for static values
const getStaticValueLabel = (value: string) => {
if (value === "$now") return "Feedback date";
return value;
};
// Default behavior for other field types (timestamp, float64, boolean, jsonb, etc.)
const hasDefaultMapping = mappedSourceField || mapping?.staticValue;
return (
<div
ref={setNodeRef}
className={`flex items-center gap-2 rounded-md border p-2 text-sm transition-colors ${
isActive
? "border-brand-dark bg-slate-100"
: hasDefaultMapping
? "border-green-300 bg-green-50"
: "border-dashed border-slate-300 bg-slate-50"
}`}>
<div className="flex flex-1 flex-col">
<div className="flex items-center gap-2">
<span className="font-medium text-slate-900">{field.name}</span>
{field.required && <span className="text-xs text-red-500">*</span>}
<span className="text-xs text-slate-400">({field.type})</span>
</div>
{/* Show mapped source field */}
{mappedSourceField && !mapping?.staticValue && (
<div className="mt-1 flex items-center gap-1">
<span className="text-xs text-green-700"> {mappedSourceField.name}</span>
<button type="button" onClick={onRemoveMapping} className="ml-1 rounded p-0.5 hover:bg-green-100">
<XIcon className="h-3 w-3 text-green-600" />
</button>
</div>
)}
{/* Show static value */}
{mapping?.staticValue && !mappedSourceField && (
<div className="mt-1 flex items-center gap-1">
<span className="rounded bg-blue-100 px-1.5 py-0.5 text-xs text-blue-700">
= {getStaticValueLabel(mapping.staticValue)}
</span>
<button type="button" onClick={onRemoveMapping} className="ml-1 rounded p-0.5 hover:bg-blue-100">
<XIcon className="h-3 w-3 text-blue-600" />
</button>
</div>
)}
{/* Show drop zone with preset options */}
{!hasDefaultMapping && (
<div className="mt-1 flex flex-wrap items-center gap-1">
<span className="text-xs text-slate-400">Drop a field here</span>
{field.exampleStaticValues && field.exampleStaticValues.length > 0 && (
<>
<span className="text-xs text-slate-300">|</span>
{field.exampleStaticValues.map((val) => (
<button
key={val}
type="button"
onClick={() => onStaticValueChange(val)}
className="rounded bg-slate-100 px-1.5 py-0.5 text-xs text-slate-600 hover:bg-slate-200">
{getStaticValueLabel(val)}
</button>
))}
</>
)}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,232 @@
"use client";
import { DndContext, DragEndEvent, DragOverlay, DragStartEvent } from "@dnd-kit/core";
import { CopyIcon, MailIcon } from "lucide-react";
import { useMemo, useState } from "react";
import { Badge } from "@/modules/ui/components/badge";
import { Switch } from "@/modules/ui/components/switch";
import { DraggableSourceField, DroppableTargetField } from "./mapping-field";
import { FEEDBACK_RECORD_FIELDS, TFieldMapping, TSourceField, TSourceType } from "./types";
interface MappingUIProps {
sourceFields: TSourceField[];
mappings: TFieldMapping[];
onMappingsChange: (mappings: TFieldMapping[]) => void;
sourceType: TSourceType;
deriveFromAttachments?: boolean;
onDeriveFromAttachmentsChange?: (value: boolean) => void;
emailInboxId?: string;
}
export function MappingUI({
sourceFields,
mappings,
onMappingsChange,
sourceType,
deriveFromAttachments = false,
onDeriveFromAttachmentsChange,
emailInboxId,
}: MappingUIProps) {
const [activeId, setActiveId] = useState<string | null>(null);
const [emailCopied, setEmailCopied] = useState(false);
// Generate a stable random email ID if not provided
const generatedEmailId = useMemo(() => {
if (emailInboxId) return emailInboxId;
return `fb-${Math.random().toString(36).substring(2, 8)}`;
}, [emailInboxId]);
const inboxEmail = `${generatedEmailId}@inbox.formbricks.com`;
const handleCopyEmail = () => {
navigator.clipboard.writeText(inboxEmail);
setEmailCopied(true);
setTimeout(() => setEmailCopied(false), 2000);
};
const requiredFields = FEEDBACK_RECORD_FIELDS.filter((f) => f.required);
const optionalFields = FEEDBACK_RECORD_FIELDS.filter((f) => !f.required);
const handleDragStart = (event: DragStartEvent) => {
setActiveId(event.active.id as string);
};
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
setActiveId(null);
if (!over) return;
const sourceFieldId = active.id as string;
const targetFieldId = over.id as string;
// Check if this target already has a mapping
const existingMapping = mappings.find((m) => m.targetFieldId === targetFieldId);
if (existingMapping) {
// Remove the existing mapping first
const newMappings = mappings.filter((m) => m.targetFieldId !== targetFieldId);
onMappingsChange([...newMappings, { sourceFieldId, targetFieldId }]);
} else {
// Remove any existing mapping for this source field
const newMappings = mappings.filter((m) => m.sourceFieldId !== sourceFieldId);
onMappingsChange([...newMappings, { sourceFieldId, targetFieldId }]);
}
};
const handleRemoveMapping = (targetFieldId: string) => {
onMappingsChange(mappings.filter((m) => m.targetFieldId !== targetFieldId));
};
const handleStaticValueChange = (targetFieldId: string, staticValue: string) => {
// Remove any existing mapping for this target field
const newMappings = mappings.filter((m) => m.targetFieldId !== targetFieldId);
// Add new static value mapping
onMappingsChange([...newMappings, { targetFieldId, staticValue }]);
};
const getSourceFieldById = (id: string) => sourceFields.find((f) => f.id === id);
const getMappingForTarget = (targetFieldId: string) => {
return mappings.find((m) => m.targetFieldId === targetFieldId) ?? null;
};
const getMappedSourceField = (targetFieldId: string) => {
const mapping = getMappingForTarget(targetFieldId);
return mapping?.sourceFieldId ? getSourceFieldById(mapping.sourceFieldId) : null;
};
const isSourceFieldMapped = (sourceFieldId: string) =>
mappings.some((m) => m.sourceFieldId === sourceFieldId);
const activeField = activeId ? getSourceFieldById(activeId) : null;
const getSourceTypeLabel = () => {
switch (sourceType) {
case "webhook":
return "Webhook Payload";
case "email":
return "Email Fields";
case "csv":
return "CSV Columns";
default:
return "Source Fields";
}
};
return (
<DndContext onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
{/* Email inbox address display */}
{sourceType === "email" && (
<div className="mb-4 rounded-lg border border-blue-200 bg-blue-50 p-4">
<div className="flex items-start gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-blue-100">
<MailIcon className="h-5 w-5 text-blue-600" />
</div>
<div className="flex-1">
<p className="text-sm font-medium text-slate-900">Your feedback inbox</p>
<p className="mt-0.5 text-xs text-slate-500">
Forward emails to this address to capture feedback automatically
</p>
<div className="mt-2 flex items-center gap-2">
<code className="rounded bg-white px-2 py-1 font-mono text-sm text-blue-700">
{inboxEmail}
</code>
<button
type="button"
onClick={handleCopyEmail}
className="flex items-center gap-1 rounded px-2 py-1 text-xs text-blue-600 hover:bg-blue-100">
<CopyIcon className="h-3 w-3" />
{emailCopied ? "Copied!" : "Copy"}
</button>
</div>
</div>
</div>
</div>
)}
<div className="grid grid-cols-2 gap-6">
{/* Source Fields Panel */}
<div className="space-y-3">
<h4 className="text-sm font-medium text-slate-700">{getSourceTypeLabel()}</h4>
{sourceFields.length === 0 ? (
<div className="flex h-64 items-center justify-center rounded-lg border border-dashed border-slate-300 bg-slate-50">
<p className="text-sm text-slate-500">
{sourceType === "webhook"
? "Click 'Simulate webhook' to load sample fields"
: sourceType === "email"
? "Click 'Load email fields' to see available fields"
: sourceType === "csv"
? "Click 'Load sample CSV' to see columns"
: "No source fields loaded yet"}
</p>
</div>
) : (
<div className="space-y-2">
{sourceFields.map((field) => (
<DraggableSourceField key={field.id} field={field} isMapped={isSourceFieldMapped(field.id)} />
))}
</div>
)}
{/* Email-specific options */}
{sourceType === "email" && onDeriveFromAttachmentsChange && (
<div className="mt-4 flex items-center justify-between rounded-lg border border-slate-200 bg-white p-3">
<div className="flex flex-col gap-0.5">
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-slate-900">Derive context from attachments</span>
<Badge text="AI" type="gray" size="tiny" />
</div>
<span className="text-xs text-slate-500">
Extract additional context from email attachments using AI
</span>
</div>
<Switch checked={deriveFromAttachments} onCheckedChange={onDeriveFromAttachmentsChange} />
</div>
)}
</div>
{/* Target Fields Panel */}
<div className="space-y-3">
<h4 className="text-sm font-medium text-slate-700">Hub Feedback Record Fields</h4>
{/* Required Fields */}
<div className="space-y-2">
<p className="text-xs font-medium uppercase tracking-wide text-slate-500">Required</p>
{requiredFields.map((field) => (
<DroppableTargetField
key={field.id}
field={field}
mappedSourceField={getMappedSourceField(field.id) ?? null}
mapping={getMappingForTarget(field.id)}
onRemoveMapping={() => handleRemoveMapping(field.id)}
onStaticValueChange={(value) => handleStaticValueChange(field.id, value)}
/>
))}
</div>
{/* Optional Fields */}
<div className="mt-4 space-y-2">
<p className="text-xs font-medium uppercase tracking-wide text-slate-500">Optional</p>
{optionalFields.map((field) => (
<DroppableTargetField
key={field.id}
field={field}
mappedSourceField={getMappedSourceField(field.id) ?? null}
mapping={getMappingForTarget(field.id)}
onRemoveMapping={() => handleRemoveMapping(field.id)}
onStaticValueChange={(value) => handleStaticValueChange(field.id, value)}
/>
))}
</div>
</div>
</div>
<DragOverlay>
{activeField ? (
<div className="border-brand-dark rounded-md border bg-white p-2 text-sm shadow-lg">
<span className="font-medium">{activeField.name}</span>
<span className="ml-2 text-xs text-slate-500">({activeField.type})</span>
</div>
) : null}
</DragOverlay>
</DndContext>
);
}

View File

@@ -0,0 +1,51 @@
"use client";
import { Badge } from "@/modules/ui/components/badge";
import { SOURCE_OPTIONS, TSourceType } from "./types";
interface SourceTypeSelectorProps {
selectedType: TSourceType | null;
onSelectType: (type: TSourceType) => void;
}
export function SourceTypeSelector({ selectedType, onSelectType }: SourceTypeSelectorProps) {
return (
<div className="space-y-3">
<p className="text-sm text-slate-600">Select the type of feedback source you want to connect:</p>
<div className="space-y-2">
{SOURCE_OPTIONS.map((option) => (
<button
key={option.id}
type="button"
disabled={option.disabled}
onClick={() => onSelectType(option.id)}
className={`flex w-full items-center justify-between rounded-lg border p-4 text-left transition-colors ${
selectedType === option.id
? "border-brand-dark bg-slate-50"
: option.disabled
? "cursor-not-allowed border-slate-200 bg-slate-50 opacity-60"
: "border-slate-200 hover:border-slate-300 hover:bg-slate-50"
}`}>
<div className="flex-1">
<div className="flex items-center gap-2">
<span className="font-medium text-slate-900">{option.name}</span>
{option.badge && <Badge text={option.badge.text} type={option.badge.type} size="tiny" />}
</div>
<p className="mt-1 text-sm text-slate-500">{option.description}</p>
</div>
<div
className={`ml-4 h-5 w-5 rounded-full border-2 ${
selectedType === option.id ? "border-brand-dark bg-brand-dark" : "border-slate-300"
}`}>
{selectedType === option.id && (
<div className="flex h-full w-full items-center justify-center">
<div className="h-2 w-2 rounded-full bg-white" />
</div>
)}
</div>
</button>
))}
</div>
</div>
);
}

View File

@@ -0,0 +1,64 @@
"use client";
import { useState } from "react";
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
import { PageHeader } from "@/modules/ui/components/page-header";
import { UnifyConfigNavigation } from "../../components/UnifyConfigNavigation";
import { CreateSourceModal } from "./create-source-modal";
import { EditSourceModal } from "./edit-source-modal";
import { SourcesTable } from "./sources-table";
import { TSourceConnection } from "./types";
interface SourcesSectionProps {
environmentId: string;
}
export function SourcesSection({ environmentId }: SourcesSectionProps) {
const [sources, setSources] = useState<TSourceConnection[]>([]);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
const [editingSource, setEditingSource] = useState<TSourceConnection | null>(null);
const handleCreateSource = (source: TSourceConnection) => {
setSources((prev) => [...prev, source]);
};
const handleUpdateSource = (updatedSource: TSourceConnection) => {
setSources((prev) => prev.map((s) => (s.id === updatedSource.id ? updatedSource : s)));
};
const handleDeleteSource = (sourceId: string) => {
setSources((prev) => prev.filter((s) => s.id !== sourceId));
};
const handleSourceClick = (source: TSourceConnection) => {
setEditingSource(source);
};
return (
<PageContentWrapper>
<PageHeader
pageTitle="Unify Feedback"
cta={
<CreateSourceModal
open={isCreateModalOpen}
onOpenChange={setIsCreateModalOpen}
onCreateSource={handleCreateSource}
/>
}>
<UnifyConfigNavigation environmentId={environmentId} />
</PageHeader>
<div className="space-y-6">
<SourcesTable sources={sources} onSourceClick={handleSourceClick} />
</div>
<EditSourceModal
source={editingSource}
open={editingSource !== null}
onOpenChange={(open) => !open && setEditingSource(null)}
onUpdateSource={handleUpdateSource}
onDeleteSource={handleDeleteSource}
/>
</PageContentWrapper>
);
}

View File

@@ -0,0 +1,87 @@
"use client";
import { formatDistanceToNow } from "date-fns";
import { FileSpreadsheetIcon, GlobeIcon, MailIcon, MessageSquareIcon, WebhookIcon } from "lucide-react";
import { TSourceType } from "./types";
interface SourcesTableDataRowProps {
id: string;
name: string;
type: TSourceType;
mappingsCount: number;
createdAt: Date;
onClick: () => void;
}
function getSourceIcon(type: TSourceType) {
switch (type) {
case "formbricks":
return <GlobeIcon className="h-4 w-4 text-slate-500" />;
case "webhook":
return <WebhookIcon className="h-4 w-4 text-slate-500" />;
case "email":
return <MailIcon className="h-4 w-4 text-slate-500" />;
case "csv":
return <FileSpreadsheetIcon className="h-4 w-4 text-slate-500" />;
case "slack":
return <MessageSquareIcon className="h-4 w-4 text-slate-500" />;
default:
return <GlobeIcon className="h-4 w-4 text-slate-500" />;
}
}
function getSourceTypeLabel(type: TSourceType) {
switch (type) {
case "formbricks":
return "Formbricks";
case "webhook":
return "Webhook";
case "email":
return "Email";
case "csv":
return "CSV";
case "slack":
return "Slack";
default:
return type;
}
}
export function SourcesTableDataRow({
id,
name,
type,
mappingsCount,
createdAt,
onClick,
}: SourcesTableDataRowProps) {
return (
<div
key={id}
role="button"
tabIndex={0}
className="grid h-12 min-h-12 cursor-pointer grid-cols-12 content-center p-2 text-left transition-colors ease-in-out hover:bg-slate-50"
onClick={onClick}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
onClick();
}
}}>
<div className="col-span-1 flex items-center pl-4">
<div className="flex items-center gap-2">
{getSourceIcon(type)}
<span className="hidden text-xs text-slate-500 sm:inline">{getSourceTypeLabel(type)}</span>
</div>
</div>
<div className="col-span-6 flex items-center">
<span className="truncate font-medium text-slate-900">{name}</span>
</div>
<div className="col-span-2 hidden items-center justify-center text-sm text-slate-600 sm:flex">
{mappingsCount} {mappingsCount === 1 ? "field" : "fields"}
</div>
<div className="col-span-3 hidden items-center justify-end pr-4 text-sm text-slate-500 sm:flex">
{formatDistanceToNow(createdAt, { addSuffix: true })}
</div>
</div>
);
}

View File

@@ -0,0 +1,41 @@
"use client";
import { SourcesTableDataRow } from "./sources-table-data-row";
import { TSourceConnection } from "./types";
interface SourcesTableProps {
sources: TSourceConnection[];
onSourceClick: (source: TSourceConnection) => void;
}
export function SourcesTable({ sources, onSourceClick }: SourcesTableProps) {
return (
<div className="rounded-xl border border-slate-200 bg-white shadow-sm">
<div className="grid h-12 grid-cols-12 content-center border-b border-slate-200 text-left text-sm font-semibold text-slate-900">
<div className="col-span-1 pl-6">Type</div>
<div className="col-span-6">Name</div>
<div className="col-span-2 hidden text-center sm:block">Mappings</div>
<div className="col-span-3 hidden pr-6 text-right sm:block">Created</div>
</div>
{sources.length === 0 ? (
<div className="flex h-32 items-center justify-center">
<p className="text-sm text-slate-500">No sources connected yet. Add a source to get started.</p>
</div>
) : (
<div className="divide-y divide-slate-100">
{sources.map((source) => (
<SourcesTableDataRow
key={source.id}
id={source.id}
name={source.name}
type={source.type}
mappingsCount={source.mappings.length}
createdAt={source.createdAt}
onClick={() => onSourceClick(source)}
/>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,543 @@
// Source types for the feedback source connections
export type TSourceType = "formbricks" | "webhook" | "email" | "csv" | "slack";
export interface TSourceOption {
id: TSourceType;
name: string;
description: string;
disabled: boolean;
badge?: {
text: string;
type: "success" | "gray" | "warning";
};
}
export const SOURCE_OPTIONS: TSourceOption[] = [
{
id: "formbricks",
name: "Formbricks Surveys",
description: "Connect feedback from your Formbricks surveys",
disabled: false,
},
{
id: "webhook",
name: "Webhook",
description: "Receive feedback via webhook with custom mapping",
disabled: false,
},
{
id: "email",
name: "Email",
description: "Import feedback from email with custom mapping",
disabled: false,
},
{
id: "csv",
name: "CSV Import",
description: "Import feedback from CSV files",
disabled: false,
},
{
id: "slack",
name: "Slack Message",
description: "Connect feedback from Slack channels",
disabled: true,
badge: {
text: "Coming soon",
type: "gray",
},
},
];
// Formbricks Survey types for survey selection
export interface TFormbricksSurveyQuestion {
id: string;
type: "openText" | "rating" | "nps" | "csat" | "multipleChoice" | "checkbox" | "date";
headline: string;
required: boolean;
}
export interface TFormbricksSurvey {
id: string;
name: string;
status: "draft" | "active" | "paused" | "completed";
responseCount: number;
questions: TFormbricksSurveyQuestion[];
createdAt: Date;
}
// Mock surveys for POC
export const MOCK_FORMBRICKS_SURVEYS: TFormbricksSurvey[] = [
{
id: "survey_nps_q1",
name: "Q1 2024 NPS Survey",
status: "active",
responseCount: 1247,
createdAt: new Date("2024-01-15"),
questions: [
{ id: "q_nps", type: "nps", headline: "How likely are you to recommend us?", required: true },
{
id: "q_reason",
type: "openText",
headline: "What's the main reason for your score?",
required: false,
},
{
id: "q_improve",
type: "openText",
headline: "What could we do to improve?",
required: false,
},
],
},
{
id: "survey_product_feedback",
name: "Product Feedback Survey",
status: "active",
responseCount: 523,
createdAt: new Date("2024-02-01"),
questions: [
{
id: "q_satisfaction",
type: "rating",
headline: "How satisfied are you with the product?",
required: true,
},
{
id: "q_features",
type: "multipleChoice",
headline: "Which features do you use most?",
required: true,
},
{
id: "q_missing",
type: "openText",
headline: "What features are you missing?",
required: false,
},
{ id: "q_feedback", type: "openText", headline: "Any other feedback?", required: false },
],
},
{
id: "survey_onboarding",
name: "Onboarding Experience",
status: "active",
responseCount: 89,
createdAt: new Date("2024-03-10"),
questions: [
{ id: "q_easy", type: "csat", headline: "How easy was the onboarding process?", required: true },
{
id: "q_time",
type: "multipleChoice",
headline: "How long did onboarding take?",
required: true,
},
{
id: "q_help",
type: "checkbox",
headline: "Which resources did you find helpful?",
required: false,
},
{
id: "q_suggestions",
type: "openText",
headline: "Any suggestions for improvement?",
required: false,
},
],
},
{
id: "survey_support",
name: "Support Satisfaction",
status: "paused",
responseCount: 312,
createdAt: new Date("2024-01-20"),
questions: [
{
id: "q_support_rating",
type: "rating",
headline: "How would you rate your support experience?",
required: true,
},
{
id: "q_resolved",
type: "multipleChoice",
headline: "Was your issue resolved?",
required: true,
},
{ id: "q_comments", type: "openText", headline: "Additional comments", required: false },
],
},
];
// Helper to get question type label
export function getQuestionTypeLabel(type: TFormbricksSurveyQuestion["type"]): string {
switch (type) {
case "openText":
return "Open Text";
case "rating":
return "Rating";
case "nps":
return "NPS";
case "csat":
return "CSAT";
case "multipleChoice":
return "Multiple Choice";
case "checkbox":
return "Checkbox";
case "date":
return "Date";
default:
return type;
}
}
// Helper to map question type to FeedbackRecord field_type
export function questionTypeToFieldType(type: TFormbricksSurveyQuestion["type"]): TFeedbackRecordFieldType {
switch (type) {
case "openText":
return "text";
case "rating":
return "rating";
case "nps":
return "nps";
case "csat":
return "csat";
case "multipleChoice":
case "checkbox":
return "categorical";
case "date":
return "date";
default:
return "text";
}
}
// Field mapping types - supports both source field mapping and static values
export interface TFieldMapping {
targetFieldId: string;
// Either map from a source field OR set a static value
sourceFieldId?: string;
staticValue?: string;
}
export interface TSourceConnection {
id: string;
name: string;
type: TSourceType;
mappings: TFieldMapping[];
createdAt: Date;
updatedAt: Date;
}
// FeedbackRecord field types (enum values for field_type)
export type TFeedbackRecordFieldType =
| "text"
| "categorical"
| "nps"
| "csat"
| "ces"
| "rating"
| "number"
| "boolean"
| "date";
// Field types for the Hub schema
export type TTargetFieldType = "string" | "enum" | "timestamp" | "float64" | "boolean" | "jsonb" | "string[]";
export interface TTargetField {
id: string;
name: string;
type: TTargetFieldType;
required: boolean;
description: string;
// For enum fields, the possible values
enumValues?: string[];
// For string fields, example static values that could be set
exampleStaticValues?: string[];
}
export interface TSourceField {
id: string;
name: string;
type: string;
sampleValue?: string;
}
// Enum values for field_type
export const FIELD_TYPE_ENUM_VALUES: TFeedbackRecordFieldType[] = [
"text",
"categorical",
"nps",
"csat",
"ces",
"rating",
"number",
"boolean",
"date",
];
// Target fields based on the FeedbackRecord schema
export const FEEDBACK_RECORD_FIELDS: TTargetField[] = [
// Required fields
{
id: "collected_at",
name: "Collected At",
type: "timestamp",
required: true,
description: "When the feedback was originally collected",
exampleStaticValues: ["$now"],
},
{
id: "source_type",
name: "Source Type",
type: "string",
required: true,
description: "Type of source (e.g., survey, review, support)",
exampleStaticValues: ["survey", "review", "support", "email", "qualtrics", "typeform", "intercom"],
},
{
id: "field_id",
name: "Field ID",
type: "string",
required: true,
description: "Unique question/field identifier",
},
{
id: "field_type",
name: "Field Type",
type: "enum",
required: true,
description: "Data type (text, nps, csat, rating, etc.)",
enumValues: FIELD_TYPE_ENUM_VALUES,
},
// Optional fields
{
id: "tenant_id",
name: "Tenant ID",
type: "string",
required: false,
description: "Tenant/organization identifier for multi-tenant deployments",
},
{
id: "response_id",
name: "Response ID",
type: "string",
required: false,
description: "Groups multiple answers from a single submission",
},
{
id: "source_id",
name: "Source ID",
type: "string",
required: false,
description: "Reference to survey/form/ticket/review ID",
},
{
id: "source_name",
name: "Source Name",
type: "string",
required: false,
description: "Human-readable source name for display",
exampleStaticValues: ["Product Feedback", "Customer Support", "NPS Survey", "Qualtrics Import"],
},
{
id: "field_label",
name: "Field Label",
type: "string",
required: false,
description: "Question text or field label for display",
},
{
id: "value_text",
name: "Value (Text)",
type: "string",
required: false,
description: "Text responses (feedback, comments, open-ended answers)",
},
{
id: "value_number",
name: "Value (Number)",
type: "float64",
required: false,
description: "Numeric responses (ratings, scores, NPS, CSAT)",
},
{
id: "value_boolean",
name: "Value (Boolean)",
type: "boolean",
required: false,
description: "Yes/no responses",
},
{
id: "value_date",
name: "Value (Date)",
type: "timestamp",
required: false,
description: "Date/datetime responses",
},
{
id: "metadata",
name: "Metadata",
type: "jsonb",
required: false,
description: "Flexible context (device, location, campaign, custom fields)",
},
{
id: "language",
name: "Language",
type: "string",
required: false,
description: "ISO 639-1 language code (e.g., en, de, fr)",
exampleStaticValues: ["en", "de", "fr", "es", "pt", "ja", "zh"],
},
{
id: "user_identifier",
name: "User Identifier",
type: "string",
required: false,
description: "Anonymous user ID for tracking (hashed, never PII)",
},
];
// Sample webhook payload for testing
export const SAMPLE_WEBHOOK_PAYLOAD = {
id: "resp_12345",
timestamp: "2024-01-15T10:30:00Z",
survey_id: "survey_abc",
survey_name: "Product Feedback Survey",
question_id: "q1",
question_text: "How satisfied are you with our product?",
answer_type: "rating",
answer_value: 4,
user_id: "user_xyz",
metadata: {
device: "mobile",
browser: "Safari",
},
};
// Email source fields (simplified)
export const EMAIL_SOURCE_FIELDS: TSourceField[] = [
{ id: "subject", name: "Subject", type: "string", sampleValue: "Feature Request: Dark Mode" },
{
id: "body",
name: "Body (Text)",
type: "string",
sampleValue: "I would love to see a dark mode option...",
},
];
// CSV sample columns
export const SAMPLE_CSV_COLUMNS = "timestamp,customer_id,rating,feedback_text,category";
// Helper function to parse payload to source fields
export function parsePayloadToFields(payload: Record<string, unknown>): TSourceField[] {
const fields: TSourceField[] = [];
function extractFields(obj: Record<string, unknown>, prefix = ""): void {
for (const [key, value] of Object.entries(obj)) {
const fieldId = prefix ? `${prefix}.${key}` : key;
const fieldName = prefix ? `${prefix}.${key}` : key;
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
extractFields(value as Record<string, unknown>, fieldId);
} else {
let type = "string";
if (typeof value === "number") type = "number";
if (typeof value === "boolean") type = "boolean";
if (Array.isArray(value)) type = "array";
fields.push({
id: fieldId,
name: fieldName,
type,
sampleValue: String(value),
});
}
}
}
extractFields(payload);
return fields;
}
// Helper function to parse CSV columns to source fields
export function parseCSVColumnsToFields(columns: string): TSourceField[] {
return columns.split(",").map((col) => {
const trimmedCol = col.trim();
return {
id: trimmedCol,
name: trimmedCol,
type: "string",
sampleValue: `Sample ${trimmedCol}`,
};
});
}
// AI suggested mappings for different source types
// Maps source field IDs to target field IDs
export interface TAISuggestedMapping {
// Maps source field ID -> target field ID
fieldMappings: Record<string, string>;
// Static values to set on target fields
staticValues: Record<string, string>;
}
export const AI_SUGGESTED_MAPPINGS: Record<TSourceType, TAISuggestedMapping> = {
webhook: {
fieldMappings: {
timestamp: "collected_at",
survey_id: "source_id",
survey_name: "source_name",
question_id: "field_id",
question_text: "field_label",
answer_value: "value_number",
user_id: "user_identifier",
},
staticValues: {
source_type: "survey",
field_type: "rating",
},
},
email: {
fieldMappings: {
subject: "field_label",
body: "value_text",
},
staticValues: {
collected_at: "$now",
source_type: "email",
field_type: "text",
},
},
csv: {
fieldMappings: {
timestamp: "collected_at",
customer_id: "user_identifier",
rating: "value_number",
feedback_text: "value_text",
category: "field_label",
},
staticValues: {
source_type: "survey",
field_type: "rating",
},
},
formbricks: {
fieldMappings: {},
staticValues: {
source_type: "survey",
},
},
slack: {
fieldMappings: {},
staticValues: {
source_type: "support",
field_type: "text",
},
},
};
// Modal step types
export type TCreateSourceStep = "selectType" | "mapping";

View File

@@ -0,0 +1,10 @@
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
import { SourcesSection } from "./components/sources-page-client";
export default async function UnifySourcesPage(props: { params: Promise<{ environmentId: string }> }) {
const params = await props.params;
await getEnvironmentAuth(params.environmentId);
return <SourcesSection environmentId={params.environmentId} />;
}

View File

@@ -0,0 +1,94 @@
"use client";
import { useState } from "react";
import toast from "react-hot-toast";
import { Button } from "@/modules/ui/components/button";
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/modules/ui/components/dialog";
import { Input } from "@/modules/ui/components/input";
import { Label } from "@/modules/ui/components/label";
export type AddKeywordModalLevel = "L1" | "L2" | "L3";
interface AddKeywordModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
level: AddKeywordModalLevel;
parentName?: string;
onConfirm: (name: string) => void;
}
export function AddKeywordModal({
open,
onOpenChange,
level,
parentName,
onConfirm,
}: AddKeywordModalProps) {
const [name, setName] = useState("");
const handleClose = (nextOpen: boolean) => {
if (!nextOpen) setName("");
onOpenChange(nextOpen);
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const trimmed = name.trim();
if (!trimmed) {
toast.error("Please enter a keyword name.");
return;
}
onConfirm(trimmed);
setName("");
onOpenChange(false);
toast.success("Keyword added (demo).");
};
const title =
level === "L1" ? "Add L1 keyword" : level === "L2" ? "Add L2 keyword" : "Add L3 keyword";
const description =
level === "L1"
? "Add a new top-level keyword."
: parentName
? `Add a new ${level} keyword under "${parentName}".`
: `Add a new ${level} keyword.`;
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit}>
<DialogBody>
<div className="space-y-2">
<Label htmlFor="keyword-name">Keyword name</Label>
<Input
id="keyword-name"
placeholder="e.g. New category"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full"
/>
</div>
</DialogBody>
<DialogFooter className="m-2">
<Button type="button" variant="outline" onClick={() => handleClose(false)}>
Cancel
</Button>
<Button type="submit">Add keyword</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,174 @@
"use client";
import {
ChevronRightIcon,
LightbulbIcon,
MessageCircleIcon,
TriangleAlertIcon,
WrenchIcon,
} from "lucide-react";
import { useState } from "react";
import { cn } from "@/lib/cn";
import { Input } from "@/modules/ui/components/input";
import { H4, Small } from "@/modules/ui/components/typography";
import type { TaxonomyDetail, TaxonomyThemeItem } from "../types";
const THEME_COLORS: Record<string, string> = {
red: "bg-red-400",
orange: "bg-orange-400",
yellow: "bg-amber-400",
green: "bg-emerald-500",
slate: "bg-slate-400",
};;
function getThemeIcon(icon?: TaxonomyThemeItem["icon"]) {
switch (icon) {
case "warning":
return <TriangleAlertIcon className="size-4 text-amber-500" />;
case "wrench":
return <WrenchIcon className="size-4 text-slate-500" />;
case "message-circle":
return <MessageCircleIcon className="size-4 text-slate-500" />;
case "lightbulb":
return <LightbulbIcon className="size-4 text-amber-500" />;
default:
return <MessageCircleIcon className="size-4 text-slate-400" />;
}
}
interface ThemeItemRowProps {
item: TaxonomyThemeItem;
depth?: number;
themeSearch: string;
}
function ThemeItemRow({ item, depth = 0, themeSearch }: ThemeItemRowProps) {
const [expanded, setExpanded] = useState(depth === 0 && (item.children?.length ?? 0) > 0);
const hasChildren = item.children && item.children.length > 0;
const labelLower = item.label.toLowerCase();
const matchesSearch =
!themeSearch.trim() || labelLower.includes(themeSearch.trim().toLowerCase());
const childMatches =
hasChildren &&
item.children!.some((c) =>
c.label.toLowerCase().includes(themeSearch.trim().toLowerCase())
);
const show = matchesSearch || childMatches;
if (!show) return null;
return (
<div className="flex flex-col">
<div
className={cn(
"flex items-center gap-2 py-1.5 text-sm",
depth === 0 ? "font-medium text-slate-800" : "text-slate-600"
)}
style={{ paddingLeft: depth * 16 + 4 }}>
<button
type="button"
onClick={() => hasChildren && setExpanded(!expanded)}
className="flex shrink-0 items-center justify-center text-slate-400 hover:text-slate-600">
{hasChildren ? (
<ChevronRightIcon
className={cn("size-4 transition-transform", expanded && "rotate-90")}
/>
) : (
<span className="w-4" />
)}
</button>
{getThemeIcon(item.icon)}
<span className="min-w-0 flex-1 truncate">{item.label}</span>
<Small color="muted" className="shrink-0">
{item.count}
</Small>
</div>
{hasChildren && expanded && (
<div className="border-l border-slate-200 pl-2">
{item.children!.map((child) => (
<ThemeItemRow
key={child.id}
item={child}
depth={depth + 1}
themeSearch={themeSearch}
/>
))}
</div>
)}
</div>
);
}
interface TaxonomyDetailPanelProps {
detail: TaxonomyDetail | null;
}
export function TaxonomyDetailPanel({ detail }: TaxonomyDetailPanelProps) {
const [themeSearch, setThemeSearch] = useState("");
if (!detail) {
return (
<div className="flex flex-1 flex-col rounded-xl border border-slate-200 bg-white shadow-sm">
<div className="flex flex-1 flex-col items-center justify-center p-8 text-center">
<Small color="muted">Select a Level 3 keyword to view details.</Small>
</div>
</div>
);
}
const totalThemes = detail.themes.reduce((s, t) => s + t.count, 0);
return (
<div className="flex flex-1 flex-col overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm">
<div className="flex flex-col gap-5 overflow-y-auto p-4">
<div className="border-b border-slate-200 pb-4">
<H4 className="mb-1">{detail.keywordName}</H4>
<div className="flex items-center gap-2">
<Small color="muted">{detail.count} responses</Small>
<button
type="button"
className="text-sm font-medium text-slate-600 underline-offset-2 hover:underline">
View all
</button>
</div>
</div>
<div>
<H4 className="mb-1 text-sm">Description</H4>
<Small color="muted" className="leading-relaxed">
{detail.description}
</Small>
</div>
<div>
<div className="mb-2 flex items-center justify-between gap-2">
<H4 className="text-sm">{detail.themes.length} themes</H4>
<div className="flex h-2 flex-1 max-w-[120px] overflow-hidden rounded-full bg-slate-100">
{detail.themes.map((t) => (
<div
key={t.id}
className={cn(THEME_COLORS[t.color] ?? "bg-slate-400")}
style={{
width: totalThemes ? `${(t.count / totalThemes) * 100}%` : "0%",
}}
title={t.label}
/>
))}
</div>
</div>
<Input
placeholder="Search themes"
value={themeSearch}
onChange={(e) => setThemeSearch(e.target.value)}
className="mb-3 h-9 text-sm"
/>
<div className="space-y-0.5">
{detail.themeItems.map((item) => (
<ThemeItemRow key={item.id} item={item} themeSearch={themeSearch} />
))}
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,54 @@
"use client";
import { cn } from "@/lib/cn";
import { formatCount } from "../lib/mock-data";
import type { TaxonomyKeyword } from "../types";
import { Button } from "@/modules/ui/components/button";
interface TaxonomyKeywordColumnProps {
title: string;
keywords: TaxonomyKeyword[];
selectedId: string | null;
onSelect: (id: string) => void;
addButtonLabel?: string;
onAdd?: () => void;
}
export function TaxonomyKeywordColumn({
title,
keywords,
selectedId,
onSelect,
addButtonLabel,
onAdd,
}: TaxonomyKeywordColumnProps) {
return (
<div className="flex flex-col rounded-xl border border-slate-200 bg-white shadow-sm">
<div className="border-b border-slate-200 px-4 py-3">
<h3 className="text-sm font-semibold text-slate-900">{title}</h3>
</div>
<div className="flex min-h-[320px] flex-1 flex-col overflow-y-auto">
{keywords.map((kw) => (
<button
key={kw.id}
type="button"
onClick={() => onSelect(kw.id)}
className={cn(
"grid w-full grid-cols-[1fr,auto] content-center gap-3 border-b border-slate-100 px-4 py-3 text-left transition-colors last:border-b-0",
selectedId === kw.id ? "bg-slate-50" : "hover:bg-slate-50"
)}>
<span className="min-w-0 truncate text-sm font-medium text-slate-800">{kw.name}</span>
<span className="text-sm text-slate-500">{formatCount(kw.count)}</span>
</button>
))}
{addButtonLabel && (
<div className="border-t border-slate-200 p-2">
<Button type="button" variant="outline" size="sm" className="w-full" onClick={onAdd}>
+ {addButtonLabel}
</Button>
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,178 @@
"use client";
import { useMemo, useState } from "react";
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
import { PageHeader } from "@/modules/ui/components/page-header";
import { Input } from "@/modules/ui/components/input";
import { UnifyConfigNavigation } from "../../components/UnifyConfigNavigation";
import { getDetailForL3, getL2Keywords, getL3Keywords, MOCK_LEVEL1_KEYWORDS } from "../lib/mock-data";
import type { TaxonomyKeyword } from "../types";
import { AddKeywordModal } from "./AddKeywordModal";
import { TaxonomyDetailPanel } from "./TaxonomyDetailPanel";
import { TaxonomyKeywordColumn } from "./TaxonomyKeywordColumn";
interface TaxonomySectionProps {
environmentId: string;
}
export function TaxonomySection({ environmentId }: TaxonomySectionProps) {
const [searchQuery, setSearchQuery] = useState("");
const [selectedL1Id, setSelectedL1Id] = useState<string | null>("l1-1");
const [selectedL2Id, setSelectedL2Id] = useState<string | null>("l2-1a");
const [selectedL3Id, setSelectedL3Id] = useState<string | null>("l3-1a");
const [addKeywordModalOpen, setAddKeywordModalOpen] = useState(false);
const [addKeywordModalLevel, setAddKeywordModalLevel] = useState<"L1" | "L2" | "L3">("L1");
const [customL1Keywords, setCustomL1Keywords] = useState<TaxonomyKeyword[]>([]);
const [customL2Keywords, setCustomL2Keywords] = useState<TaxonomyKeyword[]>([]);
const [customL3Keywords, setCustomL3Keywords] = useState<TaxonomyKeyword[]>([]);
const l2Keywords = useMemo(() => {
const fromMock = selectedL1Id ? getL2Keywords(selectedL1Id) : [];
const custom = customL2Keywords.filter((k) => k.parentId === selectedL1Id);
return [...fromMock, ...custom];
}, [selectedL1Id, customL2Keywords]);
const l3Keywords = useMemo(() => {
const fromMock = selectedL2Id ? getL3Keywords(selectedL2Id) : [];
const custom = customL3Keywords.filter((k) => k.parentId === selectedL2Id);
return [...fromMock, ...custom];
}, [selectedL2Id, customL3Keywords]);
const detail = useMemo(
() => (selectedL3Id ? getDetailForL3(selectedL3Id) : null),
[selectedL3Id]
);
const l1Keywords = useMemo(
() => [...MOCK_LEVEL1_KEYWORDS, ...customL1Keywords],
[customL1Keywords]
);
const filterKeywords = (list: TaxonomyKeyword[], q: string) => {
if (!q.trim()) return list;
const lower = q.trim().toLowerCase();
return list.filter((k) => k.name.toLowerCase().includes(lower));
};
const filteredL1 = useMemo(
() => filterKeywords(l1Keywords, searchQuery),
[l1Keywords, searchQuery]
);
const filteredL2 = useMemo(() => filterKeywords(l2Keywords, searchQuery), [l2Keywords, searchQuery]);
const filteredL3 = useMemo(() => filterKeywords(l3Keywords, searchQuery), [l3Keywords, searchQuery]);
const selectedL1Name = useMemo(
() => l1Keywords.find((k) => k.id === selectedL1Id)?.name,
[l1Keywords, selectedL1Id]
);
const selectedL2Name = useMemo(
() => l2Keywords.find((k) => k.id === selectedL2Id)?.name,
[l2Keywords, selectedL2Id]
);
const addKeywordParentName =
addKeywordModalLevel === "L2" ? selectedL1Name : addKeywordModalLevel === "L3" ? selectedL2Name : undefined;
const handleAddKeyword = (name: string) => {
if (addKeywordModalLevel === "L1") {
const id = `custom-l1-${crypto.randomUUID()}`;
setCustomL1Keywords((prev) => [...prev, { id, name, count: 0 }]);
setSelectedL1Id(id);
setSelectedL2Id(null);
setSelectedL3Id(null);
} else if (addKeywordModalLevel === "L2" && selectedL1Id) {
const id = `custom-l2-${crypto.randomUUID()}`;
setCustomL2Keywords((prev) => [
...prev,
{ id, name, count: 0, parentId: selectedL1Id },
]);
setSelectedL2Id(id);
setSelectedL3Id(null);
} else if (addKeywordModalLevel === "L3" && selectedL2Id) {
const id = `custom-l3-${crypto.randomUUID()}`;
setCustomL3Keywords((prev) => [
...prev,
{ id, name, count: 0, parentId: selectedL2Id },
]);
setSelectedL3Id(id);
}
};
return (
<PageContentWrapper>
<PageHeader pageTitle="Unify Feedback">
<UnifyConfigNavigation environmentId={environmentId} />
</PageHeader>
<div className="space-y-4">
<div className="flex items-center gap-3">
<Input
placeholder="Find in taxonomy..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="max-w-md"
/>
</div>
<div className="grid grid-cols-1 gap-4 lg:grid-cols-12">
<div className="lg:col-span-3">
<TaxonomyKeywordColumn
title={`Level 1 Keywords (${filteredL1.length})`}
keywords={filteredL1}
selectedId={selectedL1Id}
onSelect={(id) => {
setSelectedL1Id(id);
setSelectedL2Id(null);
setSelectedL3Id(null);
}}
addButtonLabel="Add L1 Keyword"
onAdd={() => {
setAddKeywordModalLevel("L1");
setAddKeywordModalOpen(true);
}}
/>
</div>
<div className="lg:col-span-3">
<TaxonomyKeywordColumn
title={`Level 2 Keywords (${filteredL2.length})`}
keywords={filteredL2}
selectedId={selectedL2Id}
onSelect={(id) => {
setSelectedL2Id(id);
setSelectedL3Id(null);
}}
addButtonLabel="Add L2 Keyword"
onAdd={() => {
setAddKeywordModalLevel("L2");
setAddKeywordModalOpen(true);
}}
/>
</div>
<div className="lg:col-span-3">
<TaxonomyKeywordColumn
title={`Level 3 Keywords (${filteredL3.length})`}
keywords={filteredL3}
selectedId={selectedL3Id}
onSelect={setSelectedL3Id}
addButtonLabel="Add L3 Keyword"
onAdd={() => {
setAddKeywordModalLevel("L3");
setAddKeywordModalOpen(true);
}}
/>
</div>
<div className="min-h-[400px] lg:col-span-3">
<TaxonomyDetailPanel detail={detail} />
</div>
</div>
</div>
<AddKeywordModal
open={addKeywordModalOpen}
onOpenChange={setAddKeywordModalOpen}
level={addKeywordModalLevel}
parentName={addKeywordParentName}
onConfirm={handleAddKeyword}
/>
</PageContentWrapper>
);
}

View File

@@ -0,0 +1,175 @@
import type { TaxonomyDetail, TaxonomyKeyword, TaxonomyThemeItem } from "../types";
export const MOCK_LEVEL1_KEYWORDS: TaxonomyKeyword[] = [
{ id: "l1-1", name: "Dashboard", count: 12400 },
{ id: "l1-2", name: "Usability", count: 8200 },
{ id: "l1-3", name: "Performance", count: 5600 },
{ id: "l1-4", name: "Miscellaneous", count: 3100 },
];
export const MOCK_LEVEL2_KEYWORDS: Record<string, TaxonomyKeyword[]> = {
"l1-1": [
{ id: "l2-1a", name: "Survey overview", count: 5200, parentId: "l1-1" },
{ id: "l2-2a", name: "Response metrics", count: 3800, parentId: "l1-1" },
{ id: "l2-3a", name: "Analytics & reports", count: 2400, parentId: "l1-1" },
{ id: "l2-4a", name: "Widgets & embedding", count: 800, parentId: "l1-1" },
{ id: "l2-5a", name: "Not specified", count: 200, parentId: "l1-1" },
],
"l1-2": [
{ id: "l2-1b", name: "Survey builder", count: 3200, parentId: "l1-2" },
{ id: "l2-2b", name: "Question types", count: 2100, parentId: "l1-2" },
{ id: "l2-3b", name: "Logic & branching", count: 1400, parentId: "l1-2" },
{ id: "l2-4b", name: "Styling & theming", count: 900, parentId: "l1-2" },
{ id: "l2-5b", name: "Not specified", count: 600, parentId: "l1-2" },
],
"l1-3": [
{ id: "l2-1c", name: "Load time & speed", count: 2200, parentId: "l1-3" },
{ id: "l2-2c", name: "Survey rendering", count: 1600, parentId: "l1-3" },
{ id: "l2-3c", name: "SDK & integration", count: 1100, parentId: "l1-3" },
{ id: "l2-4c", name: "API & data sync", count: 500, parentId: "l1-3" },
{ id: "l2-5c", name: "Not specified", count: 200, parentId: "l1-3" },
],
"l1-4": [
{ id: "l2-1d", name: "Feature requests", count: 1500, parentId: "l1-4" },
{ id: "l2-2d", name: "Bug reports", count: 900, parentId: "l1-4" },
{ id: "l2-3d", name: "Documentation", count: 400, parentId: "l1-4" },
{ id: "l2-4d", name: "Not specified", count: 300, parentId: "l1-4" },
],
};
export const MOCK_LEVEL3_KEYWORDS: Record<string, TaxonomyKeyword[]> = {
"l2-1a": [
{ id: "l3-1a", name: "In-app surveys", count: 2800, parentId: "l2-1a" },
{ id: "l3-2a", name: "Link surveys", count: 1600, parentId: "l2-1a" },
{ id: "l3-3a", name: "Response summary", count: 600, parentId: "l2-1a" },
{ id: "l3-4a", name: "Not specified", count: 200, parentId: "l2-1a" },
],
"l2-2a": [
{ id: "l3-5a", name: "Completion rate", count: 1800, parentId: "l2-2a" },
{ id: "l3-6a", name: "Drop-off points", count: 1200, parentId: "l2-2a" },
{ id: "l3-7a", name: "Response distribution", count: 800, parentId: "l2-2a" },
],
"l2-1b": [
{ id: "l3-1b", name: "Drag & drop editor", count: 1400, parentId: "l2-1b" },
{ id: "l3-2b", name: "Question configuration", count: 900, parentId: "l2-1b" },
{ id: "l3-3b", name: "Multi-language surveys", count: 500, parentId: "l2-1b" },
{ id: "l3-4b", name: "Not specified", count: 400, parentId: "l2-1b" },
],
"l2-2b": [
{ id: "l3-5b", name: "Open text & NPS", count: 1100, parentId: "l2-2b" },
{ id: "l3-6b", name: "Multiple choice & rating", count: 600, parentId: "l2-2b" },
{ id: "l3-7b", name: "File upload & date picker", count: 400, parentId: "l2-2b" },
],
"l2-1c": [
{ id: "l3-1c", name: "Widget initialization", count: 900, parentId: "l2-1c" },
{ id: "l3-2c", name: "Survey load delay", count: 700, parentId: "l2-1c" },
{ id: "l3-3c", name: "Bundle size impact", count: 600, parentId: "l2-1c" },
],
"l2-1d": [
{ id: "l3-1d", name: "New question types", count: 600, parentId: "l2-1d" },
{ id: "l3-2d", name: "Integrations & webhooks", count: 500, parentId: "l2-1d" },
{ id: "l3-3d", name: "Export & reporting", count: 400, parentId: "l2-1d" },
],
};
export function getL2Keywords(parentL1Id: string): TaxonomyKeyword[] {
return MOCK_LEVEL2_KEYWORDS[parentL1Id] ?? [];
}
export function getL3Keywords(parentL2Id: string): TaxonomyKeyword[] {
return MOCK_LEVEL3_KEYWORDS[parentL2Id] ?? [];
}
export const MOCK_DETAIL_L3: Record<string, TaxonomyDetail> = {
"l3-1a": {
keywordId: "l3-1a",
keywordName: "In-app surveys",
count: 2800,
description:
"Feedback collected directly inside your product. Formbricks in-app surveys are triggered by actions (e.g. page view, click) and can be shown as modal, full-width, or inline widgets.",
themes: [
{ id: "t1", label: "Issues", count: 1200, color: "red" },
{ id: "t2", label: "Ideas", count: 900, color: "orange" },
{ id: "t3", label: "Questions", count: 500, color: "yellow" },
{ id: "t4", label: "Other", count: 200, color: "green" },
],
themeItems: [
{
id: "ti-1",
label: "Survey not showing on trigger",
count: 420,
icon: "warning",
children: [
{ id: "ti-1-1", label: "Wrong environment or survey ID", count: 200 },
{ id: "ti-1-2", label: "Trigger conditions not met", count: 150 },
{ id: "ti-1-3", label: "SDK not loaded in time", count: 70 },
],
},
{ id: "ti-2", label: "Positioning and placement", count: 310, icon: "wrench" },
{ id: "ti-3", label: "Request for more trigger types", count: 280, icon: "lightbulb" },
{ id: "ti-4", label: "Miscellaneous in-app feedback", count: 190, icon: "message-circle" },
],
},
"l3-1b": {
keywordId: "l3-1b",
keywordName: "Drag & drop editor",
count: 1400,
description:
"The Formbricks survey builder lets you add and reorder questions with drag and drop, configure question settings, and preview surveys before publishing.",
themes: [
{ id: "t1", label: "Issues", count: 600, color: "red" },
{ id: "t2", label: "Ideas", count: 500, color: "orange" },
{ id: "t3", label: "Questions", count: 250, color: "yellow" },
{ id: "t4", label: "Other", count: 50, color: "green" },
],
themeItems: [
{ id: "ti-1", label: "Reordering fails with many questions", count: 220, icon: "warning" },
{ id: "ti-2", label: "Request for keyboard shortcuts", count: 180, icon: "lightbulb" },
{ id: "ti-3", label: "Undo / redo in editor", count: 150, icon: "lightbulb" },
{ id: "ti-4", label: "Miscellaneous builder feedback", count: 100, icon: "message-circle" },
],
},
"l3-1c": {
keywordId: "l3-1c",
keywordName: "Widget initialization",
count: 900,
description:
"How quickly the Formbricks widget loads and becomes ready to display surveys. Includes script load time, SDK init, and first-paint for survey UI.",
themes: [
{ id: "t1", label: "Issues", count: 550, color: "red" },
{ id: "t2", label: "Ideas", count: 250, color: "orange" },
{ id: "t3", label: "Questions", count: 100, color: "yellow" },
{ id: "t4", label: "Other", count: 0, color: "green" },
],
themeItems: [
{ id: "ti-1", label: "Slow init on mobile networks", count: 280, icon: "warning" },
{ id: "ti-2", label: "Blocking main thread", count: 180, icon: "warning" },
{ id: "ti-3", label: "Lazy-load SDK suggestion", count: 120, icon: "lightbulb" },
],
},
"l3-1d": {
keywordId: "l3-1d",
keywordName: "New question types",
count: 600,
description:
"Requests for additional question types in Formbricks surveys (e.g. matrix, ranking, sliders, image choice) to capture different kinds of feedback.",
themes: [
{ id: "t1", label: "Ideas", count: 450, color: "orange" },
{ id: "t2", label: "Questions", count: 100, color: "yellow" },
{ id: "t3", label: "Other", count: 50, color: "green" },
],
themeItems: [
{ id: "ti-1", label: "Matrix / grid question", count: 180, icon: "lightbulb" },
{ id: "ti-2", label: "Ranking question type", count: 120, icon: "lightbulb" },
{ id: "ti-3", label: "Slider and scale variants", count: 90, icon: "lightbulb" },
],
},
};
export function getDetailForL3(keywordId: string): TaxonomyDetail | null {
return MOCK_DETAIL_L3[keywordId] ?? null;
}
export function formatCount(n: number): string {
return n.toLocaleString();
}

View File

@@ -0,0 +1,10 @@
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
import { TaxonomySection } from "./components/TaxonomySection";
export default async function UnifyTaxonomyPage(props: { params: Promise<{ environmentId: string }> }) {
const params = await props.params;
await getEnvironmentAuth(params.environmentId);
return <TaxonomySection environmentId={params.environmentId} />;
}

View File

@@ -0,0 +1,30 @@
export interface TaxonomyKeyword {
id: string;
name: string;
count: number;
parentId?: string;
}
export interface TaxonomyTheme {
id: string;
label: string;
count: number;
color: "red" | "orange" | "yellow" | "green" | "slate";
}
export interface TaxonomyThemeItem {
id: string;
label: string;
count: number;
icon?: "warning" | "wrench" | "message-circle" | "lightbulb";
children?: TaxonomyThemeItem[];
}
export interface TaxonomyDetail {
keywordId: string;
keywordName: string;
count: number;
description: string;
themes: TaxonomyTheme[];
themeItems: TaxonomyThemeItem[];
}

View File

@@ -21,7 +21,6 @@ import { getElementsFromBlocks } from "@/lib/survey/utils";
import { getFormattedDateTimeString } from "@/lib/utils/datetime";
import { parseRecallInfo } from "@/lib/utils/recall";
import { truncateText } from "@/lib/utils/strings";
import { resolveStorageUrlAuto } from "@/modules/storage/utils";
const convertMetaObjectToString = (metadata: TResponseMeta): string => {
let result: string[] = [];
@@ -257,16 +256,10 @@ const processElementResponse = (
const selectedChoiceIds = responseValue as string[];
return element.choices
.filter((choice) => selectedChoiceIds.includes(choice.id))
.map((choice) => resolveStorageUrlAuto(choice.imageUrl))
.map((choice) => choice.imageUrl)
.join("\n");
}
if (element.type === TSurveyElementTypeEnum.FileUpload && Array.isArray(responseValue)) {
return responseValue
.map((url) => (typeof url === "string" ? resolveStorageUrlAuto(url) : url))
.join("; ");
}
return processResponseData(responseValue);
};
@@ -375,7 +368,7 @@ const buildNotionPayloadProperties = (
responses[resp] = (pictureElement as any)?.choices
.filter((choice) => selectedChoiceIds.includes(choice.id))
.map((choice) => resolveStorageUrlAuto(choice.imageUrl));
.map((choice) => choice.imageUrl);
}
});

View File

@@ -18,7 +18,6 @@ import { convertDatesInObject } from "@/lib/time";
import { queueAuditEvent } from "@/modules/ee/audit-logs/lib/handler";
import { TAuditStatus, UNKNOWN_DATA } from "@/modules/ee/audit-logs/types/audit-log";
import { sendResponseFinishedEmail } from "@/modules/email";
import { resolveStorageUrlsInObject } from "@/modules/storage/utils";
import { sendFollowUpsForResponse } from "@/modules/survey/follow-ups/lib/follow-ups";
import { FollowUpSendError } from "@/modules/survey/follow-ups/types/follow-up";
import { handleIntegrations } from "./lib/handleIntegrations";
@@ -31,10 +30,7 @@ export const POST = async (request: Request) => {
}
const jsonInput = await request.json();
const convertedJsonInput = convertDatesInObject(
jsonInput,
new Set(["contactAttributes", "variables", "data", "meta"])
);
const convertedJsonInput = convertDatesInObject(jsonInput);
const inputValidation = ZPipelineInput.safeParse(convertedJsonInput);
@@ -96,15 +92,12 @@ export const POST = async (request: Request) => {
]);
};
const resolvedResponseData = resolveStorageUrlsInObject(response.data);
const webhookPromises = webhooks.map((webhook) => {
const body = JSON.stringify({
webhookId: webhook.id,
event,
data: {
...response,
data: resolvedResponseData,
survey: {
title: survey.name,
type: survey.type,

View File

@@ -1,6 +1,4 @@
import { google } from "googleapis";
import { getServerSession } from "next-auth";
import { TIntegrationGoogleSheetsConfig } from "@formbricks/types/integration/google-sheet";
import { responses } from "@/app/lib/api/response";
import {
GOOGLE_SHEETS_CLIENT_ID,
@@ -8,29 +6,18 @@ import {
GOOGLE_SHEETS_REDIRECT_URL,
WEBAPP_URL,
} from "@/lib/constants";
import { hasUserEnvironmentAccess } from "@/lib/environment/auth";
import { createOrUpdateIntegration, getIntegrationByType } from "@/lib/integration/service";
import { authOptions } from "@/modules/auth/lib/authOptions";
import { createOrUpdateIntegration } from "@/lib/integration/service";
export const GET = async (req: Request) => {
const url = new URL(req.url);
const environmentId = url.searchParams.get("state");
const code = url.searchParams.get("code");
const url = req.url;
const queryParams = new URLSearchParams(url.split("?")[1]); // Split the URL and get the query parameters
const environmentId = queryParams.get("state"); // Get the value of the 'state' parameter
const code = queryParams.get("code");
if (!environmentId) {
return responses.badRequestResponse("Invalid environmentId");
}
const session = await getServerSession(authOptions);
if (!session) {
return responses.notAuthenticatedResponse();
}
const canUserAccessEnvironment = await hasUserEnvironmentAccess(session.user.id, environmentId);
if (!canUserAccessEnvironment) {
return responses.unauthorizedResponse();
}
if (code && typeof code !== "string") {
return responses.badRequestResponse("`code` must be a string");
}
@@ -43,39 +30,33 @@ export const GET = async (req: Request) => {
if (!redirect_uri) return responses.internalServerErrorResponse("Google redirect url is missing");
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uri);
if (!code) {
return Response.redirect(
`${WEBAPP_URL}/environments/${environmentId}/workspace/integrations/google-sheets`
);
let key;
let userEmail;
if (code) {
const token = await oAuth2Client.getToken(code);
key = token.res?.data;
// Set credentials using the provided token
oAuth2Client.setCredentials({
access_token: key.access_token,
});
// Fetch user's email
const oauth2 = google.oauth2({
auth: oAuth2Client,
version: "v2",
});
const userInfo = await oauth2.userinfo.get();
userEmail = userInfo.data.email;
}
const token = await oAuth2Client.getToken(code);
const key = token.res?.data;
if (!key) {
return Response.redirect(
`${WEBAPP_URL}/environments/${environmentId}/workspace/integrations/google-sheets`
);
}
oAuth2Client.setCredentials({ access_token: key.access_token });
const oauth2 = google.oauth2({ auth: oAuth2Client, version: "v2" });
const userInfo = await oauth2.userinfo.get();
const userEmail = userInfo.data.email;
if (!userEmail) {
return responses.internalServerErrorResponse("Failed to get user email");
}
const integrationType = "googleSheets" as const;
const existingIntegration = await getIntegrationByType(environmentId, integrationType);
const existingConfig = existingIntegration?.config as TIntegrationGoogleSheetsConfig;
const googleSheetIntegration = {
type: integrationType,
type: "googleSheets" as "googleSheets",
environment: environmentId,
config: {
key,
data: existingConfig?.data ?? [],
data: [],
email: userEmail,
},
};

View File

@@ -0,0 +1,180 @@
// Deprecated: This api route is deprecated now and will be removed in the future.
// Deprecated: This is currently only being used for the older react native SDKs. Please upgrade to the latest SDKs.
import { NextRequest, userAgent } from "next/server";
import { prisma } from "@formbricks/database";
import { logger } from "@formbricks/logger";
import { TJsPeopleUserIdInput, ZJsPeopleUserIdInput } from "@formbricks/types/js";
import { TSurvey } from "@formbricks/types/surveys/types";
import { getContactByUserId } from "@/app/api/v1/client/[environmentId]/app/sync/lib/contact";
import { getSyncSurveys } from "@/app/api/v1/client/[environmentId]/app/sync/lib/survey";
import { replaceAttributeRecall } from "@/app/api/v1/client/[environmentId]/app/sync/lib/utils";
import { responses } from "@/app/lib/api/response";
import { transformErrorToDetails } from "@/app/lib/api/validator";
import { withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
import { getActionClasses } from "@/lib/actionClass/service";
import { IS_FORMBRICKS_CLOUD } from "@/lib/constants";
import { getEnvironment, updateEnvironment } from "@/lib/environment/service";
import {
getMonthlyOrganizationResponseCount,
getOrganizationByEnvironmentId,
} from "@/lib/organization/service";
import { getProjectByEnvironmentId } from "@/lib/project/service";
import { COLOR_DEFAULTS } from "@/lib/styling/constants";
const validateInput = (
environmentId: string,
userId: string
): { isValid: true; data: TJsPeopleUserIdInput } | { isValid: false; error: Response } => {
const inputValidation = ZJsPeopleUserIdInput.safeParse({ environmentId, userId });
if (!inputValidation.success) {
return {
isValid: false,
error: responses.badRequestResponse(
"Fields are missing or incorrectly formatted",
transformErrorToDetails(inputValidation.error),
true
),
};
}
return { isValid: true, data: inputValidation.data };
};
const checkResponseLimit = async (environmentId: string): Promise<boolean> => {
if (!IS_FORMBRICKS_CLOUD) return false;
const organization = await getOrganizationByEnvironmentId(environmentId);
if (!organization) {
logger.error({ environmentId }, "Organization does not exist");
// fail closed if the organization does not exist
return true;
}
const currentResponseCount = await getMonthlyOrganizationResponseCount(organization.id);
const monthlyResponseLimit = organization.billing.limits.monthly.responses;
const isLimitReached = monthlyResponseLimit !== null && currentResponseCount >= monthlyResponseLimit;
return isLimitReached;
};
export const OPTIONS = async (): Promise<Response> => {
return responses.successResponse({}, true);
};
export const GET = withV1ApiWrapper({
handler: async ({
req,
props,
}: {
req: NextRequest;
props: { params: Promise<{ environmentId: string; userId: string }> };
}) => {
const params = await props.params;
try {
const { device } = userAgent(req);
// validate using zod
const validation = validateInput(params.environmentId, params.userId);
if (!validation.isValid) {
return { response: validation.error };
}
const { environmentId, userId } = validation.data;
const environment = await getEnvironment(environmentId);
if (!environment) {
throw new Error("Environment does not exist");
}
const project = await getProjectByEnvironmentId(environmentId);
if (!project) {
throw new Error("Project not found");
}
if (!environment.appSetupCompleted) {
await updateEnvironment(environment.id, { appSetupCompleted: true });
}
// check organization subscriptions and response limits
const isAppSurveyResponseLimitReached = await checkResponseLimit(environmentId);
let contact = await getContactByUserId(environmentId, userId);
if (!contact) {
contact = await prisma.contact.create({
data: {
attributes: {
create: {
attributeKey: {
connect: {
key_environmentId: {
key: "userId",
environmentId,
},
},
},
value: userId,
},
},
environment: { connect: { id: environmentId } },
},
select: {
id: true,
attributes: { select: { attributeKey: { select: { key: true } }, value: true } },
},
});
}
const contactAttributes = contact.attributes.reduce((acc, attribute) => {
acc[attribute.attributeKey.key] = attribute.value;
return acc;
}, {}) as Record<string, string>;
const [surveys, actionClasses] = await Promise.all([
getSyncSurveys(
environmentId,
contact.id,
contactAttributes,
device.type === "mobile" ? "phone" : "desktop"
),
getActionClasses(environmentId),
]);
const updatedProject: any = {
...project,
brandColor: project.styling.brandColor?.light ?? COLOR_DEFAULTS.brandColor,
...(project.styling.highlightBorderColor?.light && {
highlightBorderColor: project.styling.highlightBorderColor.light,
}),
};
const language = contactAttributes["language"];
// Scenario 1: Multi language and updated trigger action classes supported.
// Use the surveys as they are.
let transformedSurveys: TSurvey[] = surveys;
// creating state object
let state = {
surveys: !isAppSurveyResponseLimitReached
? transformedSurveys.map((survey) => replaceAttributeRecall(survey, contactAttributes))
: [],
actionClasses,
language,
project: updatedProject,
};
return {
response: responses.successResponse({ ...state }, true),
};
} catch (error) {
logger.error({ error, url: req.url }, "Error in GET /api/v1/client/[environmentId]/app/sync/[userId]");
return {
response: responses.internalServerErrorResponse(
"Unable to handle the request: " + error.message,
true
),
};
}
},
});

View File

@@ -0,0 +1,83 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { prisma } from "@formbricks/database";
import { TContact } from "@/modules/ee/contacts/types/contact";
import { getContactByUserId } from "./contact";
// Mock prisma
vi.mock("@formbricks/database", () => ({
prisma: {
contact: {
findFirst: vi.fn(),
},
},
}));
const environmentId = "test-environment-id";
const userId = "test-user-id";
const contactId = "test-contact-id";
const contactMock: Partial<TContact> & {
attributes: { value: string; attributeKey: { key: string } }[];
} = {
id: contactId,
attributes: [
{ attributeKey: { key: "userId" }, value: userId },
{ attributeKey: { key: "email" }, value: "test@example.com" },
],
};
describe("getContactByUserId", () => {
afterEach(() => {
vi.resetAllMocks();
});
test("should return contact if found", async () => {
vi.mocked(prisma.contact.findFirst).mockResolvedValue(contactMock as any);
const contact = await getContactByUserId(environmentId, userId);
expect(prisma.contact.findFirst).toHaveBeenCalledWith({
where: {
attributes: {
some: {
attributeKey: {
key: "userId",
environmentId,
},
value: userId,
},
},
},
select: {
id: true,
attributes: { select: { attributeKey: { select: { key: true } }, value: true } },
},
});
expect(contact).toEqual(contactMock);
});
test("should return null if contact not found", async () => {
vi.mocked(prisma.contact.findFirst).mockResolvedValue(null);
const contact = await getContactByUserId(environmentId, userId);
expect(prisma.contact.findFirst).toHaveBeenCalledWith({
where: {
attributes: {
some: {
attributeKey: {
key: "userId",
environmentId,
},
value: userId,
},
},
},
select: {
id: true,
attributes: { select: { attributeKey: { select: { key: true } }, value: true } },
},
});
expect(contact).toBeNull();
});
});

View File

@@ -0,0 +1,42 @@
import "server-only";
import { cache as reactCache } from "react";
import { prisma } from "@formbricks/database";
export const getContactByUserId = reactCache(
async (
environmentId: string,
userId: string
): Promise<{
attributes: {
value: string;
attributeKey: {
key: string;
};
}[];
id: string;
} | null> => {
const contact = await prisma.contact.findFirst({
where: {
attributes: {
some: {
attributeKey: {
key: "userId",
environmentId,
},
value: userId,
},
},
},
select: {
id: true,
attributes: { select: { attributeKey: { select: { key: true } }, value: true } },
},
});
if (!contact) {
return null;
}
return contact;
}
);

View File

@@ -0,0 +1,323 @@
import { Prisma } from "@prisma/client";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { prisma } from "@formbricks/database";
import { logger } from "@formbricks/logger";
import { DatabaseError } from "@formbricks/types/errors";
import { TProject } from "@formbricks/types/project";
import { TSegment } from "@formbricks/types/segment";
import { TSurvey } from "@formbricks/types/surveys/types";
import { getProjectByEnvironmentId } from "@/lib/project/service";
import { getSurveys } from "@/lib/survey/service";
import { anySurveyHasFilters } from "@/lib/survey/utils";
import { diffInDays } from "@/lib/utils/datetime";
import { evaluateSegment } from "@/modules/ee/contacts/segments/lib/segments";
import { getSyncSurveys } from "./survey";
vi.mock("@/lib/project/service", () => ({
getProjectByEnvironmentId: vi.fn(),
}));
vi.mock("@/lib/survey/service", () => ({
getSurveys: vi.fn(),
}));
vi.mock("@/lib/survey/utils", () => ({
anySurveyHasFilters: vi.fn(),
}));
vi.mock("@/lib/utils/datetime", () => ({
diffInDays: vi.fn(),
}));
vi.mock("@/lib/utils/validate", () => ({
validateInputs: vi.fn(),
}));
vi.mock("@/modules/ee/contacts/segments/lib/segments", () => ({
evaluateSegment: vi.fn(),
}));
vi.mock("@formbricks/database", () => ({
prisma: {
display: {
findMany: vi.fn(),
},
response: {
findMany: vi.fn(),
},
},
}));
vi.mock("@formbricks/logger", () => ({
logger: {
error: vi.fn(),
},
}));
const environmentId = "test-env-id";
const contactId = "test-contact-id";
const contactAttributes = { userId: "user1", email: "test@example.com" };
const deviceType = "desktop";
const mockProject = {
id: "proj1",
name: "Test Project",
createdAt: new Date(),
updatedAt: new Date(),
organizationId: "org1",
environments: [],
recontactDays: 10,
inAppSurveyBranding: true,
linkSurveyBranding: true,
placement: "bottomRight",
clickOutsideClose: true,
darkOverlay: false,
languages: [],
} as unknown as TProject;
const baseSurvey: TSurvey = {
id: "survey1",
createdAt: new Date(),
updatedAt: new Date(),
name: "Test Survey 1",
environmentId: environmentId,
type: "app",
status: "inProgress",
questions: [],
displayOption: "displayOnce",
recontactDays: null,
autoClose: null,
delay: 0,
displayPercentage: null,
autoComplete: null,
segment: null,
surveyClosedMessage: null,
singleUse: null,
styling: null,
pin: null,
displayLimit: null,
welcomeCard: { enabled: false } as TSurvey["welcomeCard"],
endings: [],
triggers: [],
languages: [],
variables: [],
hiddenFields: { enabled: false },
createdBy: null,
isSingleResponsePerEmailEnabled: false,
isVerifyEmailEnabled: false,
projectOverwrites: null,
showLanguageSwitch: false,
isBackButtonHidden: false,
followUps: [],
recaptcha: { enabled: false, threshold: 0.5 },
};
// Helper function to create mock display objects
const createMockDisplay = (id: string, surveyId: string, contactId: string, createdAt?: Date) => ({
id,
createdAt: createdAt || new Date(),
updatedAt: new Date(),
surveyId,
contactId,
responseId: null,
status: null,
});
// Helper function to create mock response objects
const createMockResponse = (id: string, surveyId: string, contactId: string, createdAt?: Date) => ({
id,
createdAt: createdAt || new Date(),
updatedAt: new Date(),
finished: false,
surveyId,
contactId,
endingId: null,
data: {},
variables: {},
ttc: {},
meta: {},
contactAttributes: null,
singleUseId: null,
language: null,
displayId: null,
});
describe("getSyncSurveys", () => {
beforeEach(() => {
vi.mocked(getProjectByEnvironmentId).mockResolvedValue(mockProject);
vi.mocked(prisma.display.findMany).mockResolvedValue([]);
vi.mocked(prisma.response.findMany).mockResolvedValue([]);
vi.mocked(anySurveyHasFilters).mockReturnValue(false);
vi.mocked(evaluateSegment).mockResolvedValue(true);
vi.mocked(diffInDays).mockReturnValue(100); // Assume enough days passed
});
afterEach(() => {
vi.resetAllMocks();
});
test("should throw error if product not found", async () => {
vi.mocked(getProjectByEnvironmentId).mockResolvedValue(null);
await expect(getSyncSurveys(environmentId, contactId, contactAttributes, deviceType)).rejects.toThrow(
"Project not found"
);
});
test("should return empty array if no surveys found", async () => {
vi.mocked(getSurveys).mockResolvedValue([]);
const result = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result).toEqual([]);
});
test("should return empty array if no 'app' type surveys in progress", async () => {
const surveys: TSurvey[] = [
{ ...baseSurvey, id: "s1", type: "link", status: "inProgress" },
{ ...baseSurvey, id: "s2", type: "app", status: "paused" },
];
vi.mocked(getSurveys).mockResolvedValue(surveys);
const result = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result).toEqual([]);
});
test("should filter by displayOption 'displayOnce'", async () => {
const surveys: TSurvey[] = [{ ...baseSurvey, id: "s1", displayOption: "displayOnce" }];
vi.mocked(getSurveys).mockResolvedValue(surveys);
vi.mocked(prisma.display.findMany).mockResolvedValue([createMockDisplay("d1", "s1", contactId)]); // Already displayed
const result = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result).toEqual([]);
vi.mocked(prisma.display.findMany).mockResolvedValue([]); // Not displayed yet
const result2 = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result2).toEqual(surveys);
});
test("should filter by displayOption 'displayMultiple'", async () => {
const surveys: TSurvey[] = [{ ...baseSurvey, id: "s1", displayOption: "displayMultiple" }];
vi.mocked(getSurveys).mockResolvedValue(surveys);
vi.mocked(prisma.response.findMany).mockResolvedValue([createMockResponse("r1", "s1", contactId)]); // Already responded
const result = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result).toEqual([]);
vi.mocked(prisma.response.findMany).mockResolvedValue([]); // Not responded yet
const result2 = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result2).toEqual(surveys);
});
test("should filter by displayOption 'displaySome'", async () => {
const surveys: TSurvey[] = [{ ...baseSurvey, id: "s1", displayOption: "displaySome", displayLimit: 2 }];
vi.mocked(getSurveys).mockResolvedValue(surveys);
vi.mocked(prisma.display.findMany).mockResolvedValue([
createMockDisplay("d1", "s1", contactId),
createMockDisplay("d2", "s1", contactId),
]); // Display limit reached
const result = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result).toEqual([]);
vi.mocked(prisma.display.findMany).mockResolvedValue([createMockDisplay("d1", "s1", contactId)]); // Within limit
const result2 = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result2).toEqual(surveys);
// Test with response already submitted
vi.mocked(prisma.response.findMany).mockResolvedValue([createMockResponse("r1", "s1", contactId)]);
const result3 = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result3).toEqual([]);
});
test("should not filter by displayOption 'respondMultiple'", async () => {
const surveys: TSurvey[] = [{ ...baseSurvey, id: "s1", displayOption: "respondMultiple" }];
vi.mocked(getSurveys).mockResolvedValue(surveys);
vi.mocked(prisma.display.findMany).mockResolvedValue([createMockDisplay("d1", "s1", contactId)]);
vi.mocked(prisma.response.findMany).mockResolvedValue([createMockResponse("r1", "s1", contactId)]);
const result = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result).toEqual(surveys);
});
test("should filter by product recontactDays if survey recontactDays is null", async () => {
const surveys: TSurvey[] = [{ ...baseSurvey, id: "s1", recontactDays: null }];
vi.mocked(getSurveys).mockResolvedValue(surveys);
const displayDate = new Date();
vi.mocked(prisma.display.findMany).mockResolvedValue([
createMockDisplay("d1", "s2", contactId, displayDate), // Display for another survey
]);
vi.mocked(diffInDays).mockReturnValue(5); // Not enough days passed (product.recontactDays = 10)
const result = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result).toEqual([]);
expect(diffInDays).toHaveBeenCalledWith(expect.any(Date), displayDate);
vi.mocked(diffInDays).mockReturnValue(15); // Enough days passed
const result2 = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result2).toEqual(surveys);
});
test("should return surveys if no segment filters exist", async () => {
const surveys: TSurvey[] = [{ ...baseSurvey, id: "s1" }];
vi.mocked(getSurveys).mockResolvedValue(surveys);
vi.mocked(anySurveyHasFilters).mockReturnValue(false);
const result = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result).toEqual(surveys);
expect(evaluateSegment).not.toHaveBeenCalled();
});
test("should evaluate segment filters if they exist", async () => {
const segment = { id: "seg1", filters: [{}] } as TSegment; // Mock filter structure
const surveys: TSurvey[] = [{ ...baseSurvey, id: "s1", segment }];
vi.mocked(getSurveys).mockResolvedValue(surveys);
vi.mocked(anySurveyHasFilters).mockReturnValue(true);
// Case 1: Segment evaluation matches
vi.mocked(evaluateSegment).mockResolvedValue(true);
const result1 = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result1).toEqual(surveys);
expect(evaluateSegment).toHaveBeenCalledWith(
{
attributes: contactAttributes,
deviceType,
environmentId,
contactId,
userId: contactAttributes.userId,
},
segment.filters
);
// Case 2: Segment evaluation does not match
vi.mocked(evaluateSegment).mockResolvedValue(false);
const result2 = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result2).toEqual([]);
});
test("should handle Prisma errors", async () => {
const prismaError = new Prisma.PrismaClientKnownRequestError("Test Prisma Error", {
code: "P2025",
clientVersion: "test",
});
vi.mocked(getSurveys).mockRejectedValue(prismaError);
await expect(getSyncSurveys(environmentId, contactId, contactAttributes, deviceType)).rejects.toThrow(
DatabaseError
);
expect(logger.error).toHaveBeenCalledWith(prismaError);
});
test("should handle general errors", async () => {
const generalError = new Error("Something went wrong");
vi.mocked(getSurveys).mockRejectedValue(generalError);
await expect(getSyncSurveys(environmentId, contactId, contactAttributes, deviceType)).rejects.toThrow(
generalError
);
});
test("should throw ResourceNotFoundError if resolved surveys are null after filtering", async () => {
const segment = { id: "seg1", filters: [{}] } as TSegment; // Mock filter structure
const surveys: TSurvey[] = [{ ...baseSurvey, id: "s1", segment }];
vi.mocked(getSurveys).mockResolvedValue(surveys);
vi.mocked(anySurveyHasFilters).mockReturnValue(true);
vi.mocked(evaluateSegment).mockResolvedValue(false); // Ensure all surveys are filtered out
// This scenario is tricky to force directly as the code checks `if (!surveys)` before returning.
// However, if `Promise.all` somehow resolved to null/undefined (highly unlikely), it should throw.
// We can simulate this by mocking `Promise.all` if needed, but the current code structure makes this hard to test.
// Let's assume the filter logic works correctly and test the intended path.
const result = await getSyncSurveys(environmentId, contactId, contactAttributes, deviceType);
expect(result).toEqual([]); // Expect empty array, not an error in this case.
});
});

View File

@@ -0,0 +1,148 @@
import "server-only";
import { Prisma } from "@prisma/client";
import { cache as reactCache } from "react";
import { prisma } from "@formbricks/database";
import { logger } from "@formbricks/logger";
import { ZId } from "@formbricks/types/common";
import { DatabaseError, ResourceNotFoundError } from "@formbricks/types/errors";
import { TSurvey } from "@formbricks/types/surveys/types";
import { getProjectByEnvironmentId } from "@/lib/project/service";
import { getSurveys } from "@/lib/survey/service";
import { anySurveyHasFilters } from "@/lib/survey/utils";
import { diffInDays } from "@/lib/utils/datetime";
import { validateInputs } from "@/lib/utils/validate";
import { evaluateSegment } from "@/modules/ee/contacts/segments/lib/segments";
export const getSyncSurveys = reactCache(
async (
environmentId: string,
contactId: string,
contactAttributes: Record<string, string | number>,
deviceType: "phone" | "desktop" = "desktop"
): Promise<TSurvey[]> => {
validateInputs([environmentId, ZId]);
try {
const project = await getProjectByEnvironmentId(environmentId);
if (!project) {
throw new Error("Project not found");
}
let surveys = await getSurveys(environmentId);
// filtered surveys for running and web
surveys = surveys.filter((survey) => survey.status === "inProgress" && survey.type === "app");
// if no surveys are left, return an empty array
if (surveys.length === 0) {
return [];
}
const displays = await prisma.display.findMany({
where: {
contactId,
},
});
const responses = await prisma.response.findMany({
where: {
contactId,
},
});
// filter surveys that meet the displayOption criteria
surveys = surveys.filter((survey) => {
switch (survey.displayOption) {
case "respondMultiple":
return true;
case "displayOnce":
return displays.filter((display) => display.surveyId === survey.id).length === 0;
case "displayMultiple":
if (!responses) return true;
else {
return responses.filter((response) => response.surveyId === survey.id).length === 0;
}
case "displaySome":
if (survey.displayLimit === null) {
return true;
}
if (responses && responses.filter((response) => response.surveyId === survey.id).length !== 0) {
return false;
}
return displays.filter((display) => display.surveyId === survey.id).length < survey.displayLimit;
default:
throw Error("Invalid displayOption");
}
});
const latestDisplay = displays[0];
// filter surveys that meet the recontactDays criteria
surveys = surveys.filter((survey) => {
if (!latestDisplay) {
return true;
} else if (survey.recontactDays !== null) {
const lastDisplaySurvey = displays.filter((display) => display.surveyId === survey.id)[0];
if (!lastDisplaySurvey) {
return true;
}
return diffInDays(new Date(), new Date(lastDisplaySurvey.createdAt)) >= survey.recontactDays;
} else if (project.recontactDays !== null) {
return diffInDays(new Date(), new Date(latestDisplay.createdAt)) >= project.recontactDays;
} else {
return true;
}
});
// if no surveys are left, return an empty array
if (surveys.length === 0) {
return [];
}
// if no surveys have segment filters, return the surveys
if (!anySurveyHasFilters(surveys)) {
return surveys;
}
// the surveys now have segment filters, so we need to evaluate them
const surveyPromises = surveys.map(async (survey) => {
const { segment } = survey;
// if the survey has no segment, or the segment has no filters, we return the survey
if (!segment || !segment.filters?.length) {
return survey;
}
// Evaluate the segment filters
const result = await evaluateSegment(
{
attributes: contactAttributes ?? {},
deviceType,
environmentId,
contactId,
userId: String(contactAttributes.userId),
},
segment.filters
);
return result ? survey : null;
});
const resolvedSurveys = await Promise.all(surveyPromises);
surveys = resolvedSurveys.filter((survey) => !!survey) as TSurvey[];
if (!surveys) {
throw new ResourceNotFoundError("Survey", environmentId);
}
return surveys;
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
logger.error(error);
throw new DatabaseError(error.message);
}
throw error;
}
}
);

View File

@@ -0,0 +1,245 @@
import { describe, expect, test, vi } from "vitest";
import { TAttributes } from "@formbricks/types/attributes";
import { TLanguage } from "@formbricks/types/project";
import {
TSurvey,
TSurveyEnding,
TSurveyQuestion,
TSurveyQuestionTypeEnum,
} from "@formbricks/types/surveys/types";
import { parseRecallInfo } from "@/lib/utils/recall";
import { replaceAttributeRecall } from "./utils";
vi.mock("@/lib/utils/recall", () => ({
parseRecallInfo: vi.fn((text, attributes) => {
const recallPattern = /recall:([a-zA-Z0-9_-]+)/;
const match = text.match(recallPattern);
if (match && match[1]) {
const recallKey = match[1];
const attributeValue = attributes[recallKey];
if (attributeValue !== undefined) {
return text.replace(recallPattern, `parsed-${attributeValue}`);
}
}
return text; // Return original text if no match or attribute not found
}),
}));
const baseSurvey: TSurvey = {
id: "survey1",
createdAt: new Date(),
updatedAt: new Date(),
name: "Test Survey",
environmentId: "env1",
type: "app",
status: "inProgress",
questions: [],
endings: [],
welcomeCard: { enabled: false } as TSurvey["welcomeCard"],
languages: [
{ language: { id: "lang1", code: "en" } as unknown as TLanguage, default: true, enabled: true },
],
triggers: [],
recontactDays: null,
displayLimit: null,
singleUse: null,
styling: null,
surveyClosedMessage: null,
hiddenFields: { enabled: false },
variables: [],
createdBy: null,
isSingleResponsePerEmailEnabled: false,
isVerifyEmailEnabled: false,
projectOverwrites: null,
showLanguageSwitch: false,
isBackButtonHidden: false,
followUps: [],
recaptcha: { enabled: false, threshold: 0.5 },
displayOption: "displayOnce",
autoClose: null,
delay: 0,
displayPercentage: null,
autoComplete: null,
segment: null,
pin: null,
metadata: {},
};
const attributes: TAttributes = {
name: "John Doe",
email: "john.doe@example.com",
plan: "premium",
};
describe("replaceAttributeRecall", () => {
test("should replace recall info in question headlines and subheaders", () => {
const surveyWithRecall: TSurvey = {
...baseSurvey,
questions: [
{
id: "q1",
type: TSurveyQuestionTypeEnum.OpenText,
headline: { default: "Hello recall:name!" },
subheader: { default: "Your email is recall:email" },
required: true,
buttonLabel: { default: "Next" },
placeholder: { default: "Type here..." },
longAnswer: false,
logic: [],
} as unknown as TSurveyQuestion,
],
};
const result = replaceAttributeRecall(surveyWithRecall, attributes);
expect(result.questions[0].headline.default).toBe("Hello parsed-John Doe!");
expect(result.questions[0].subheader?.default).toBe("Your email is parsed-john.doe@example.com");
expect(vi.mocked(parseRecallInfo)).toHaveBeenCalledWith("Hello recall:name!", attributes);
expect(vi.mocked(parseRecallInfo)).toHaveBeenCalledWith("Your email is recall:email", attributes);
});
test("should replace recall info in welcome card headline", () => {
const surveyWithRecall: TSurvey = {
...baseSurvey,
welcomeCard: {
enabled: true,
headline: { default: "Welcome, recall:name!" },
subheader: { default: "<p>Some content</p>" },
buttonLabel: { default: "Start" },
timeToFinish: false,
showResponseCount: false,
},
};
const result = replaceAttributeRecall(surveyWithRecall, attributes);
expect(result.welcomeCard.headline?.default).toBe("Welcome, parsed-John Doe!");
expect(vi.mocked(parseRecallInfo)).toHaveBeenCalledWith("Welcome, recall:name!", attributes);
});
test("should replace recall info in end screen headlines and subheaders", () => {
const surveyWithRecall: TSurvey = {
...baseSurvey,
endings: [
{
type: "endScreen",
headline: { default: "Thank you, recall:name!" },
subheader: { default: "Your plan: recall:plan" },
buttonLabel: { default: "Finish" },
buttonLink: "https://example.com",
} as unknown as TSurveyEnding,
],
};
const result = replaceAttributeRecall(surveyWithRecall, attributes);
expect(result.endings[0].type).toBe("endScreen");
if (result.endings[0].type === "endScreen") {
expect(result.endings[0].headline?.default).toBe("Thank you, parsed-John Doe!");
expect(result.endings[0].subheader?.default).toBe("Your plan: parsed-premium");
expect(vi.mocked(parseRecallInfo)).toHaveBeenCalledWith("Thank you, recall:name!", attributes);
expect(vi.mocked(parseRecallInfo)).toHaveBeenCalledWith("Your plan: recall:plan", attributes);
}
});
test("should handle multiple languages", () => {
const surveyMultiLang: TSurvey = {
...baseSurvey,
languages: [
{ language: { id: "lang1", code: "en" } as unknown as TLanguage, default: true, enabled: true },
{ language: { id: "lang2", code: "es" } as unknown as TLanguage, default: false, enabled: true },
],
questions: [
{
id: "q1",
type: TSurveyQuestionTypeEnum.OpenText,
headline: { default: "Hello recall:name!", es: "Hola recall:name!" },
required: true,
buttonLabel: { default: "Next", es: "Siguiente" },
placeholder: { default: "Type here...", es: "Escribe aquí..." },
longAnswer: false,
logic: [],
} as unknown as TSurveyQuestion,
],
};
const result = replaceAttributeRecall(surveyMultiLang, attributes);
expect(result.questions[0].headline.default).toBe("Hello parsed-John Doe!");
expect(result.questions[0].headline.es).toBe("Hola parsed-John Doe!");
expect(vi.mocked(parseRecallInfo)).toHaveBeenCalledWith("Hello recall:name!", attributes);
expect(vi.mocked(parseRecallInfo)).toHaveBeenCalledWith("Hola recall:name!", attributes);
});
test("should not replace if recall key is not in attributes", () => {
const surveyWithRecall: TSurvey = {
...baseSurvey,
questions: [
{
id: "q1",
type: TSurveyQuestionTypeEnum.OpenText,
headline: { default: "Your company: recall:company" },
required: true,
buttonLabel: { default: "Next" },
placeholder: { default: "Type here..." },
longAnswer: false,
logic: [],
} as unknown as TSurveyQuestion,
],
};
const result = replaceAttributeRecall(surveyWithRecall, attributes);
expect(result.questions[0].headline.default).toBe("Your company: recall:company");
expect(vi.mocked(parseRecallInfo)).toHaveBeenCalledWith("Your company: recall:company", attributes);
});
test("should handle surveys with no recall information", async () => {
const surveyNoRecall: TSurvey = {
...baseSurvey,
questions: [
{
id: "q1",
type: TSurveyQuestionTypeEnum.OpenText,
headline: { default: "Just a regular question" },
required: true,
buttonLabel: { default: "Next" },
placeholder: { default: "Type here..." },
longAnswer: false,
logic: [],
} as unknown as TSurveyQuestion,
],
welcomeCard: {
enabled: true,
headline: { default: "Welcome!" },
subheader: { default: "<p>Some content</p>" },
buttonLabel: { default: "Start" },
timeToFinish: false,
showResponseCount: false,
},
endings: [
{
type: "endScreen",
headline: { default: "Thank you!" },
buttonLabel: { default: "Finish" },
} as unknown as TSurveyEnding,
],
};
const parseRecallInfoSpy = vi.spyOn(await import("@/lib/utils/recall"), "parseRecallInfo");
const result = replaceAttributeRecall(surveyNoRecall, attributes);
expect(result).toEqual(surveyNoRecall); // Should be unchanged
expect(parseRecallInfoSpy).not.toHaveBeenCalled();
parseRecallInfoSpy.mockRestore();
});
test("should handle surveys with empty questions, endings, or disabled welcome card", async () => {
const surveyEmpty: TSurvey = {
...baseSurvey,
questions: [],
endings: [],
welcomeCard: { enabled: false } as TSurvey["welcomeCard"],
};
const parseRecallInfoSpy = vi.spyOn(await import("@/lib/utils/recall"), "parseRecallInfo");
const result = replaceAttributeRecall(surveyEmpty, attributes);
expect(result).toEqual(surveyEmpty);
expect(parseRecallInfoSpy).not.toHaveBeenCalled();
parseRecallInfoSpy.mockRestore();
});
});

View File

@@ -0,0 +1,55 @@
import { TAttributes } from "@formbricks/types/attributes";
import { TSurvey } from "@formbricks/types/surveys/types";
import { parseRecallInfo } from "@/lib/utils/recall";
export const replaceAttributeRecall = (survey: TSurvey, attributes: TAttributes): TSurvey => {
const surveyTemp = structuredClone(survey);
const languages = surveyTemp.languages
.map((surveyLanguage) => {
if (surveyLanguage.default) {
return "default";
}
if (surveyLanguage.enabled) {
return surveyLanguage.language.code;
}
return null;
})
.filter((language): language is string => language !== null);
surveyTemp.questions.forEach((question) => {
languages.forEach((language) => {
if (question.headline[language]?.includes("recall:")) {
question.headline[language] = parseRecallInfo(question.headline[language], attributes);
}
if (question.subheader && question.subheader[language]?.includes("recall:")) {
question.subheader[language] = parseRecallInfo(question.subheader[language], attributes);
}
});
});
if (surveyTemp.welcomeCard.enabled && surveyTemp.welcomeCard.headline) {
languages.forEach((language) => {
if (surveyTemp.welcomeCard.headline && surveyTemp.welcomeCard.headline[language]?.includes("recall:")) {
surveyTemp.welcomeCard.headline[language] = parseRecallInfo(
surveyTemp.welcomeCard.headline[language],
attributes
);
}
});
}
surveyTemp.endings.forEach((ending) => {
if (ending.type === "endScreen") {
languages.forEach((language) => {
if (ending.headline && ending.headline[language]?.includes("recall:")) {
ending.headline[language] = parseRecallInfo(ending.headline[language], attributes);
if (ending.subheader && ending.subheader[language]?.includes("recall:")) {
ending.subheader[language] = parseRecallInfo(ending.subheader[language], attributes);
}
}
});
}
});
return surveyTemp;
};

View File

@@ -0,0 +1,6 @@
import {
OPTIONS,
PUT,
} from "@/modules/ee/contacts/api/v1/client/[environmentId]/contacts/[userId]/attributes/route";
export { OPTIONS, PUT };

View File

@@ -1,314 +0,0 @@
import { Prisma } from "@prisma/client";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { prisma } from "@formbricks/database";
import { logger } from "@formbricks/logger";
import { DatabaseError, ResourceNotFoundError } from "@formbricks/types/errors";
import { getEnvironmentStateData } from "./data";
// Mock dependencies
vi.mock("@formbricks/database", () => ({
prisma: {
environment: {
findUnique: vi.fn(),
},
},
}));
vi.mock("@formbricks/logger", () => ({
logger: {
error: vi.fn(),
},
}));
vi.mock("@/modules/survey/lib/utils", () => ({
transformPrismaSurvey: vi.fn((survey) => survey),
}));
const environmentId = "cjld2cjxh0000qzrmn831i7rn";
const mockEnvironmentData = {
id: environmentId,
type: "production",
appSetupCompleted: true,
project: {
id: "project-123",
recontactDays: 30,
clickOutsideClose: true,
overlay: "none",
placement: "bottomRight",
inAppSurveyBranding: true,
styling: { allowStyleOverwrite: false },
organization: {
id: "org-123",
billing: {
plan: "free",
limits: { monthly: { responses: 100 } },
},
},
},
actionClasses: [
{
id: "action-1",
type: "code",
name: "Test Action",
key: "test-action",
noCodeConfig: null,
},
],
surveys: [
{
id: "survey-1",
name: "Test Survey",
type: "app",
status: "inProgress",
welcomeCard: { enabled: false },
questions: [],
blocks: null,
variables: [],
showLanguageSwitch: false,
languages: [],
endings: [],
autoClose: null,
styling: null,
recaptcha: { enabled: false },
segment: null,
recontactDays: null,
displayLimit: null,
displayOption: "displayOnce",
hiddenFields: { enabled: false },
isBackButtonHidden: false,
triggers: [],
displayPercentage: null,
delay: 0,
projectOverwrites: null,
},
],
};
describe("getEnvironmentStateData", () => {
beforeEach(() => {
vi.resetAllMocks();
});
afterEach(() => {
vi.resetAllMocks();
});
test("should return environment state data when environment exists", async () => {
vi.mocked(prisma.environment.findUnique).mockResolvedValue(mockEnvironmentData as never);
const result = await getEnvironmentStateData(environmentId);
expect(result).toEqual({
environment: {
id: environmentId,
type: "production",
appSetupCompleted: true,
project: {
id: "project-123",
recontactDays: 30,
clickOutsideClose: true,
overlay: "none",
placement: "bottomRight",
inAppSurveyBranding: true,
styling: { allowStyleOverwrite: false },
},
},
organization: {
id: "org-123",
billing: {
plan: "free",
limits: { monthly: { responses: 100 } },
},
},
surveys: mockEnvironmentData.surveys,
actionClasses: mockEnvironmentData.actionClasses,
});
expect(prisma.environment.findUnique).toHaveBeenCalledWith({
where: { id: environmentId },
select: expect.objectContaining({
id: true,
type: true,
appSetupCompleted: true,
project: expect.any(Object),
actionClasses: expect.any(Object),
surveys: expect.any(Object),
}),
});
});
test("should throw ResourceNotFoundError when environment is not found", async () => {
vi.mocked(prisma.environment.findUnique).mockResolvedValue(null);
await expect(getEnvironmentStateData(environmentId)).rejects.toThrow(ResourceNotFoundError);
await expect(getEnvironmentStateData(environmentId)).rejects.toThrow("environment");
});
test("should throw ResourceNotFoundError when project is not found", async () => {
vi.mocked(prisma.environment.findUnique).mockResolvedValue({
...mockEnvironmentData,
project: null,
} as never);
await expect(getEnvironmentStateData(environmentId)).rejects.toThrow(ResourceNotFoundError);
});
test("should throw ResourceNotFoundError when organization is not found", async () => {
vi.mocked(prisma.environment.findUnique).mockResolvedValue({
...mockEnvironmentData,
project: {
...mockEnvironmentData.project,
organization: null,
},
} as never);
await expect(getEnvironmentStateData(environmentId)).rejects.toThrow(ResourceNotFoundError);
});
test("should throw DatabaseError on Prisma database errors", async () => {
const prismaError = new Prisma.PrismaClientKnownRequestError("Connection failed", {
code: "P2024",
clientVersion: "5.0.0",
});
vi.mocked(prisma.environment.findUnique).mockRejectedValue(prismaError);
await expect(getEnvironmentStateData(environmentId)).rejects.toThrow(DatabaseError);
expect(logger.error).toHaveBeenCalled();
});
test("should rethrow unexpected errors", async () => {
const unexpectedError = new Error("Unexpected error");
vi.mocked(prisma.environment.findUnique).mockRejectedValue(unexpectedError);
await expect(getEnvironmentStateData(environmentId)).rejects.toThrow("Unexpected error");
expect(logger.error).toHaveBeenCalled();
});
test("should handle empty surveys array", async () => {
vi.mocked(prisma.environment.findUnique).mockResolvedValue({
...mockEnvironmentData,
surveys: [],
} as never);
const result = await getEnvironmentStateData(environmentId);
expect(result.surveys).toEqual([]);
});
test("should handle empty actionClasses array", async () => {
vi.mocked(prisma.environment.findUnique).mockResolvedValue({
...mockEnvironmentData,
actionClasses: [],
} as never);
const result = await getEnvironmentStateData(environmentId);
expect(result.actionClasses).toEqual([]);
});
test("should transform surveys using transformPrismaSurvey", async () => {
const multipleSurveys = [
...mockEnvironmentData.surveys,
{
...mockEnvironmentData.surveys[0],
id: "survey-2",
name: "Second Survey",
},
];
vi.mocked(prisma.environment.findUnique).mockResolvedValue({
...mockEnvironmentData,
surveys: multipleSurveys,
} as never);
const result = await getEnvironmentStateData(environmentId);
expect(result.surveys).toHaveLength(2);
});
test("should correctly map project properties to environment.project", async () => {
const customProject = {
...mockEnvironmentData.project,
recontactDays: 14,
clickOutsideClose: false,
overlay: "dark",
placement: "center",
inAppSurveyBranding: false,
styling: { allowStyleOverwrite: true, brandColor: "#ff0000" },
};
vi.mocked(prisma.environment.findUnique).mockResolvedValue({
...mockEnvironmentData,
project: customProject,
} as never);
const result = await getEnvironmentStateData(environmentId);
expect(result.environment.project).toEqual({
id: "project-123",
recontactDays: 14,
clickOutsideClose: false,
overlay: "dark",
placement: "center",
inAppSurveyBranding: false,
styling: { allowStyleOverwrite: true, brandColor: "#ff0000" },
});
});
test("should validate environmentId input", async () => {
// Invalid CUID should throw validation error
await expect(getEnvironmentStateData("invalid-id")).rejects.toThrow();
});
test("should handle different environment types", async () => {
vi.mocked(prisma.environment.findUnique).mockResolvedValue({
...mockEnvironmentData,
type: "development",
} as never);
const result = await getEnvironmentStateData(environmentId);
expect(result.environment.type).toBe("development");
});
test("should handle appSetupCompleted false", async () => {
vi.mocked(prisma.environment.findUnique).mockResolvedValue({
...mockEnvironmentData,
appSetupCompleted: false,
} as never);
const result = await getEnvironmentStateData(environmentId);
expect(result.environment.appSetupCompleted).toBe(false);
});
test("should correctly extract organization billing data", async () => {
const customBilling = {
plan: "enterprise",
stripeCustomerId: "cus_123",
limits: {
monthly: { responses: 10000, miu: 50000 },
projects: 100,
},
};
vi.mocked(prisma.environment.findUnique).mockResolvedValue({
...mockEnvironmentData,
project: {
...mockEnvironmentData.project,
organization: {
id: "org-enterprise",
billing: customBilling,
},
},
} as never);
const result = await getEnvironmentStateData(environmentId);
expect(result.organization).toEqual({
id: "org-enterprise",
billing: customBilling,
});
});
});

View File

@@ -10,7 +10,6 @@ import {
TJsEnvironmentStateSurvey,
} from "@formbricks/types/js";
import { validateInputs } from "@/lib/utils/validate";
import { resolveStorageUrlsInObject } from "@/modules/storage/utils";
import { transformPrismaSurvey } from "@/modules/survey/lib/utils";
/**
@@ -55,7 +54,7 @@ export const getEnvironmentStateData = async (environmentId: string): Promise<En
id: true,
recontactDays: true,
clickOutsideClose: true,
overlay: true,
darkOverlay: true,
placement: true,
inAppSurveyBranding: true,
styling: true,
@@ -175,17 +174,17 @@ export const getEnvironmentStateData = async (environmentId: string): Promise<En
id: environmentData.project.id,
recontactDays: environmentData.project.recontactDays,
clickOutsideClose: environmentData.project.clickOutsideClose,
overlay: environmentData.project.overlay,
darkOverlay: environmentData.project.darkOverlay,
placement: environmentData.project.placement,
inAppSurveyBranding: environmentData.project.inAppSurveyBranding,
styling: resolveStorageUrlsInObject(environmentData.project.styling),
styling: environmentData.project.styling,
},
},
organization: {
id: environmentData.project.organization.id,
billing: environmentData.project.organization.billing,
},
surveys: resolveStorageUrlsInObject(transformedSurveys),
surveys: transformedSurveys,
actionClasses: environmentData.actionClasses as TJsEnvironmentStateActionClass[],
};
} catch (error) {

View File

@@ -58,7 +58,7 @@ const mockProject: TJsEnvironmentStateProject = {
inAppSurveyBranding: true,
placement: "bottomRight",
clickOutsideClose: true,
overlay: "none",
darkOverlay: false,
styling: {
allowStyleOverwrite: false,
},

View File

@@ -0,0 +1,6 @@
import {
GET,
OPTIONS,
} from "@/modules/ee/contacts/api/v1/client/[environmentId]/identify/contacts/[userId]/route";
export { GET, OPTIONS };

View File

@@ -1,15 +1,13 @@
import { NextRequest } from "next/server";
import { logger } from "@formbricks/logger";
import { DatabaseError, InvalidInputError, ResourceNotFoundError } from "@formbricks/types/errors";
import { TResponse, TResponseUpdateInput, ZResponseUpdateInput } from "@formbricks/types/responses";
import { TSurvey } from "@formbricks/types/surveys/types";
import { ZResponseUpdateInput } from "@formbricks/types/responses";
import { responses } from "@/app/lib/api/response";
import { transformErrorToDetails } from "@/app/lib/api/validator";
import { withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
import { sendToPipeline } from "@/app/lib/pipelines";
import { getResponse } from "@/lib/response/service";
import { getSurvey } from "@/lib/survey/service";
import { formatValidationErrorsForV1Api, validateResponseData } from "@/modules/api/lib/validation";
import { validateOtherOptionLengthForMultipleChoice } from "@/modules/api/v2/lib/element";
import { createQuotaFullObject } from "@/modules/ee/quotas/lib/helpers";
import { validateFileUploads } from "@/modules/storage/utils";
@@ -33,35 +31,6 @@ const handleDatabaseError = (error: Error, url: string, endpoint: string, respon
return responses.internalServerErrorResponse("Unknown error occurred", true);
};
const validateResponse = (
response: TResponse,
survey: TSurvey,
responseUpdateInput: TResponseUpdateInput
) => {
// Validate response data against validation rules
const mergedData = {
...response.data,
...responseUpdateInput.data,
};
const validationErrors = validateResponseData(
survey.blocks,
mergedData,
responseUpdateInput.language ?? response.language ?? "en",
survey.questions
);
if (validationErrors) {
return {
response: responses.badRequestResponse(
"Validation failed",
formatValidationErrorsForV1Api(validationErrors),
true
),
};
}
};
export const PUT = withV1ApiWrapper({
handler: async ({
req,
@@ -144,11 +113,6 @@ export const PUT = withV1ApiWrapper({
};
}
const validationResult = validateResponse(response, survey, inputValidation.data);
if (validationResult) {
return validationResult;
}
// update response with quota evaluation
let updatedResponse;
try {

View File

@@ -6,14 +6,12 @@ import { ZEnvironmentId } from "@formbricks/types/environment";
import { InvalidInputError } from "@formbricks/types/errors";
import { TResponseWithQuotaFull } from "@formbricks/types/quota";
import { TResponseInput, ZResponseInput } from "@formbricks/types/responses";
import { TSurvey } from "@formbricks/types/surveys/types";
import { responses } from "@/app/lib/api/response";
import { transformErrorToDetails } from "@/app/lib/api/validator";
import { withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
import { sendToPipeline } from "@/app/lib/pipelines";
import { getSurvey } from "@/lib/survey/service";
import { getClientIpFromHeaders } from "@/lib/utils/client-ip";
import { formatValidationErrorsForV1Api, validateResponseData } from "@/modules/api/lib/validation";
import { getIsContactsEnabled } from "@/modules/ee/license-check/lib/utils";
import { createQuotaFullObject } from "@/modules/ee/quotas/lib/helpers";
import { validateFileUploads } from "@/modules/storage/utils";
@@ -35,26 +33,6 @@ export const OPTIONS = async (): Promise<Response> => {
);
};
const validateResponse = (responseInputData: TResponseInput, survey: TSurvey) => {
// Validate response data against validation rules
const validationErrors = validateResponseData(
survey.blocks,
responseInputData.data,
responseInputData.language ?? "en",
survey.questions
);
if (validationErrors) {
return {
response: responses.badRequestResponse(
"Validation failed",
formatValidationErrorsForV1Api(validationErrors),
true
),
};
}
};
export const POST = withV1ApiWrapper({
handler: async ({ req, props }: { req: NextRequest; props: Context }) => {
const params = await props.params;
@@ -145,11 +123,6 @@ export const POST = withV1ApiWrapper({
};
}
const validationResult = validateResponse(responseInputData, survey);
if (validationResult) {
return validationResult;
}
let response: TResponseWithQuotaFull;
try {
const meta: TResponseInput["meta"] = {

View File

@@ -1,4 +1,4 @@
import { ImageResponse } from "next/og";
import { ImageResponse } from "@vercel/og";
import { NextRequest } from "next/server";
export const GET = async (req: NextRequest) => {

View File

@@ -1,7 +1,7 @@
import { NextRequest } from "next/server";
import { TIntegrationNotionConfigData, TIntegrationNotionInput } from "@formbricks/types/integration/notion";
import { responses } from "@/app/lib/api/response";
import { TSessionAuthentication, withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
import { withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
import {
ENCRYPTION_KEY,
NOTION_OAUTH_CLIENT_ID,
@@ -10,17 +10,10 @@ import {
WEBAPP_URL,
} from "@/lib/constants";
import { symmetricEncrypt } from "@/lib/crypto";
import { hasUserEnvironmentAccess } from "@/lib/environment/auth";
import { createOrUpdateIntegration, getIntegrationByType } from "@/lib/integration/service";
export const GET = withV1ApiWrapper({
handler: async ({
req,
authentication,
}: {
req: NextRequest;
authentication: NonNullable<TSessionAuthentication>;
}) => {
handler: async ({ req }: { req: NextRequest }) => {
const url = req.url;
const queryParams = new URLSearchParams(url.split("?")[1]); // Split the URL and get the query parameters
const environmentId = queryParams.get("state"); // Get the value of the 'state' parameter
@@ -33,13 +26,6 @@ export const GET = withV1ApiWrapper({
};
}
const canUserAccessEnvironment = await hasUserEnvironmentAccess(authentication.user.id, environmentId);
if (!canUserAccessEnvironment) {
return {
response: responses.unauthorizedResponse(),
};
}
if (code && typeof code !== "string") {
return {
response: responses.badRequestResponse("`code` must be a string"),

View File

@@ -5,19 +5,12 @@ import {
TIntegrationSlackCredential,
} from "@formbricks/types/integration/slack";
import { responses } from "@/app/lib/api/response";
import { TSessionAuthentication, withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
import { SLACK_CLIENT_ID, SLACK_CLIENT_SECRET, SLACK_REDIRECT_URI, WEBAPP_URL } from "@/lib/constants";
import { hasUserEnvironmentAccess } from "@/lib/environment/auth";
import { withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
import { SLACK_CLIENT_ID, SLACK_CLIENT_SECRET, WEBAPP_URL } from "@/lib/constants";
import { createOrUpdateIntegration, getIntegrationByType } from "@/lib/integration/service";
export const GET = withV1ApiWrapper({
handler: async ({
req,
authentication,
}: {
req: NextRequest;
authentication: NonNullable<TSessionAuthentication>;
}) => {
handler: async ({ req }: { req: NextRequest }) => {
const url = req.url;
const queryParams = new URLSearchParams(url.split("?")[1]); // Split the URL and get the query parameters
const environmentId = queryParams.get("state"); // Get the value of the 'state' parameter
@@ -30,13 +23,6 @@ export const GET = withV1ApiWrapper({
};
}
const canUserAccessEnvironment = await hasUserEnvironmentAccess(authentication.user.id, environmentId);
if (!canUserAccessEnvironment) {
return {
response: responses.unauthorizedResponse(),
};
}
if (code && typeof code !== "string") {
return {
response: responses.badRequestResponse("`code` must be a string"),
@@ -56,7 +42,6 @@ export const GET = withV1ApiWrapper({
code,
client_id: SLACK_CLIENT_ID,
client_secret: SLACK_CLIENT_SECRET,
redirect_uri: SLACK_REDIRECT_URI,
};
const formBody: string[] = [];
for (const property in formData) {

View File

@@ -8,9 +8,12 @@ import { TApiAuditLog, TApiKeyAuthentication, withV1ApiWrapper } from "@/app/lib
import { sendToPipeline } from "@/app/lib/pipelines";
import { deleteResponse, getResponse } from "@/lib/response/service";
import { getSurvey } from "@/lib/survey/service";
import { formatValidationErrorsForV1Api, validateResponseData } from "@/modules/api/lib/validation";
import {
formatValidationErrorsForV1Api,
validateResponseData,
} from "@/modules/api/v2/management/responses/lib/validation";
import { hasPermission } from "@/modules/organization/settings/api-keys/lib/utils";
import { resolveStorageUrlsInObject, validateFileUploads } from "@/modules/storage/utils";
import { validateFileUploads } from "@/modules/storage/utils";
import { updateResponseWithQuotaEvaluation } from "./lib/response";
async function fetchAndAuthorizeResponse(
@@ -57,10 +60,7 @@ export const GET = withV1ApiWrapper({
}
return {
response: responses.successResponse({
...result.response,
data: resolveStorageUrlsInObject(result.response.data),
}),
response: responses.successResponse(result.response),
};
} catch (error) {
return {
@@ -192,7 +192,7 @@ export const PUT = withV1ApiWrapper({
}
return {
response: responses.successResponse({ ...updated, data: resolveStorageUrlsInObject(updated.data) }),
response: responses.successResponse(updated),
};
} catch (error) {
return {

View File

@@ -7,9 +7,12 @@ import { transformErrorToDetails } from "@/app/lib/api/validator";
import { TApiAuditLog, TApiKeyAuthentication, withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
import { sendToPipeline } from "@/app/lib/pipelines";
import { getSurvey } from "@/lib/survey/service";
import { formatValidationErrorsForV1Api, validateResponseData } from "@/modules/api/lib/validation";
import {
formatValidationErrorsForV1Api,
validateResponseData,
} from "@/modules/api/v2/management/responses/lib/validation";
import { hasPermission } from "@/modules/organization/settings/api-keys/lib/utils";
import { resolveStorageUrlsInObject, validateFileUploads } from "@/modules/storage/utils";
import { validateFileUploads } from "@/modules/storage/utils";
import {
createResponseWithQuotaEvaluation,
getResponses,
@@ -54,9 +57,7 @@ export const GET = withV1ApiWrapper({
allResponses.push(...environmentResponses);
}
return {
response: responses.successResponse(
allResponses.map((r) => ({ ...r, data: resolveStorageUrlsInObject(r.data) }))
),
response: responses.successResponse(allResponses),
};
} catch (error) {
if (error instanceof DatabaseError) {

View File

@@ -16,7 +16,6 @@ import { TApiAuditLog, TApiKeyAuthentication, withV1ApiWrapper } from "@/app/lib
import { getOrganizationByEnvironmentId } from "@/lib/organization/service";
import { getSurvey, updateSurvey } from "@/lib/survey/service";
import { hasPermission } from "@/modules/organization/settings/api-keys/lib/utils";
import { resolveStorageUrlsInObject } from "@/modules/storage/utils";
const fetchAndAuthorizeSurvey = async (
surveyId: string,
@@ -59,18 +58,16 @@ export const GET = withV1ApiWrapper({
if (shouldTransformToQuestions) {
return {
response: responses.successResponse(
resolveStorageUrlsInObject({
...result.survey,
questions: transformBlocksToQuestions(result.survey.blocks, result.survey.endings),
blocks: [],
})
),
response: responses.successResponse({
...result.survey,
questions: transformBlocksToQuestions(result.survey.blocks, result.survey.endings),
blocks: [],
}),
};
}
return {
response: responses.successResponse(resolveStorageUrlsInObject(result.survey)),
response: responses.successResponse(result.survey),
};
} catch (error) {
return {
@@ -205,12 +202,12 @@ export const PUT = withV1ApiWrapper({
};
return {
response: responses.successResponse(resolveStorageUrlsInObject(surveyWithQuestions)),
response: responses.successResponse(surveyWithQuestions),
};
}
return {
response: responses.successResponse(resolveStorageUrlsInObject(updatedSurvey)),
response: responses.successResponse(updatedSurvey),
};
} catch (error) {
return {

View File

@@ -14,7 +14,6 @@ import { TApiAuditLog, TApiKeyAuthentication, withV1ApiWrapper } from "@/app/lib
import { getOrganizationByEnvironmentId } from "@/lib/organization/service";
import { createSurvey } from "@/lib/survey/service";
import { hasPermission } from "@/modules/organization/settings/api-keys/lib/utils";
import { resolveStorageUrlsInObject } from "@/modules/storage/utils";
import { getSurveys } from "./lib/surveys";
export const GET = withV1ApiWrapper({
@@ -56,7 +55,7 @@ export const GET = withV1ApiWrapper({
});
return {
response: responses.successResponse(resolveStorageUrlsInObject(surveysWithQuestions)),
response: responses.successResponse(surveysWithQuestions),
};
} catch (error) {
if (error instanceof DatabaseError) {

View File

@@ -0,0 +1,6 @@
import {
OPTIONS,
PUT,
} from "@/modules/ee/contacts/api/v1/client/[environmentId]/contacts/[userId]/attributes/route";
export { OPTIONS, PUT };

View File

@@ -0,0 +1,6 @@
import {
GET,
OPTIONS,
} from "@/modules/ee/contacts/api/v1/client/[environmentId]/identify/contacts/[userId]/route";
export { GET, OPTIONS };

View File

@@ -11,7 +11,6 @@ import { sendToPipeline } from "@/app/lib/pipelines";
import { getSurvey } from "@/lib/survey/service";
import { getElementsFromBlocks } from "@/lib/survey/utils";
import { getClientIpFromHeaders } from "@/lib/utils/client-ip";
import { formatValidationErrorsForV1Api, validateResponseData } from "@/modules/api/lib/validation";
import { validateOtherOptionLengthForMultipleChoice } from "@/modules/api/v2/lib/element";
import { getIsContactsEnabled } from "@/modules/ee/license-check/lib/utils";
import { createQuotaFullObject } from "@/modules/ee/quotas/lib/helpers";
@@ -107,22 +106,6 @@ export const POST = async (request: Request, context: Context): Promise<Response
);
}
// Validate response data against validation rules
const validationErrors = validateResponseData(
survey.blocks,
responseInputData.data,
responseInputData.language ?? "en",
survey.questions
);
if (validationErrors) {
return responses.badRequestResponse(
"Validation failed",
formatValidationErrorsForV1Api(validationErrors),
true
);
}
let response: TResponseWithQuotaFull;
try {
const meta: TResponseInputV2["meta"] = {

View File

@@ -3,9 +3,8 @@
// Error components must be Client components
import * as Sentry from "@sentry/nextjs";
import { TFunction } from "i18next";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { type ClientErrorType, getClientErrorData, isExpectedError } from "@formbricks/types/errors";
import { type ClientErrorType, getClientErrorData } from "@formbricks/types/errors";
import { Button } from "@/modules/ui/components/button";
import { ErrorComponent } from "@/modules/ui/components/error-component";
@@ -31,13 +30,11 @@ const ErrorBoundary = ({ error, reset }: { error: Error; reset: () => void }) =>
const errorData = getClientErrorData(error);
const { title, description } = getErrorMessages(errorData.type, t);
useEffect(() => {
if (process.env.NODE_ENV === "development") {
console.error(error.message);
} else if (!isExpectedError(error)) {
Sentry.captureException(error);
}
}, [error]);
if (process.env.NODE_ENV === "development") {
console.error(error.message);
} else {
Sentry.captureException(error);
}
return (
<div className="flex h-full w-full flex-col items-center justify-center">

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