mirror of
https://github.com/formbricks/formbricks.git
synced 2026-03-12 11:35:10 -05:00
Compare commits
1 Commits
4.8.0-rc.1
...
cursor/inp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ebc2c4110 |
@@ -150,8 +150,6 @@ NOTION_OAUTH_CLIENT_ID=
|
||||
NOTION_OAUTH_CLIENT_SECRET=
|
||||
|
||||
# Stripe Billing Variables
|
||||
STRIPE_PRICING_TABLE_ID=
|
||||
STRIPE_PUBLISHABLE_KEY=
|
||||
STRIPE_SECRET_KEY=
|
||||
STRIPE_WEBHOOK_SECRET=
|
||||
|
||||
@@ -232,4 +230,4 @@ REDIS_URL=redis://localhost:6379
|
||||
|
||||
|
||||
# Lingo.dev API key for translation generation
|
||||
LINGODOTDEV_API_KEY=your_api_key_here
|
||||
LINGODOTDEV_API_KEY=your_api_key_here
|
||||
@@ -285,14 +285,12 @@ runs:
|
||||
encryption_key=${{ env.DUMMY_ENCRYPTION_KEY }}
|
||||
redis_url=${{ env.DUMMY_REDIS_URL }}
|
||||
sentry_auth_token=${{ env.SENTRY_AUTH_TOKEN }}
|
||||
posthog_key=${{ env.POSTHOG_KEY }}
|
||||
env:
|
||||
DEPOT_PROJECT_TOKEN: ${{ env.DEPOT_PROJECT_TOKEN }}
|
||||
DUMMY_DATABASE_URL: ${{ env.DUMMY_DATABASE_URL }}
|
||||
DUMMY_ENCRYPTION_KEY: ${{ env.DUMMY_ENCRYPTION_KEY }}
|
||||
DUMMY_REDIS_URL: ${{ env.DUMMY_REDIS_URL }}
|
||||
SENTRY_AUTH_TOKEN: ${{ env.SENTRY_AUTH_TOKEN }}
|
||||
POSTHOG_KEY: ${{ env.POSTHOG_KEY }}
|
||||
|
||||
- name: Sign GHCR image (GHCR only)
|
||||
if: ${{ inputs.registry_type == 'ghcr' && (github.event_name == 'workflow_call' || github.event_name == 'release' || github.event_name == 'workflow_dispatch') }}
|
||||
|
||||
1
.github/workflows/build-and-push-ecr.yml
vendored
1
.github/workflows/build-and-push-ecr.yml
vendored
@@ -92,4 +92,3 @@ jobs:
|
||||
DUMMY_ENCRYPTION_KEY: ${{ secrets.DUMMY_ENCRYPTION_KEY }}
|
||||
DUMMY_REDIS_URL: ${{ secrets.DUMMY_REDIS_URL }}
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}
|
||||
|
||||
@@ -12,18 +12,18 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@chromatic-com/storybook": "^5.0.1",
|
||||
"@storybook/addon-a11y": "10.2.17",
|
||||
"@storybook/addon-links": "10.2.17",
|
||||
"@storybook/addon-onboarding": "10.2.17",
|
||||
"@storybook/react-vite": "10.2.17",
|
||||
"@typescript-eslint/eslint-plugin": "8.57.0",
|
||||
"@storybook/addon-a11y": "10.2.15",
|
||||
"@storybook/addon-links": "10.2.15",
|
||||
"@storybook/addon-onboarding": "10.2.15",
|
||||
"@storybook/react-vite": "10.2.15",
|
||||
"@typescript-eslint/eslint-plugin": "8.56.1",
|
||||
"@tailwindcss/vite": "4.2.1",
|
||||
"@typescript-eslint/parser": "8.57.0",
|
||||
"@typescript-eslint/parser": "8.56.1",
|
||||
"@vitejs/plugin-react": "5.1.4",
|
||||
"eslint-plugin-react-refresh": "0.4.26",
|
||||
"eslint-plugin-storybook": "10.2.17",
|
||||
"storybook": "10.2.17",
|
||||
"eslint-plugin-storybook": "10.2.14",
|
||||
"storybook": "10.2.15",
|
||||
"vite": "7.3.1",
|
||||
"@storybook/addon-docs": "10.2.17"
|
||||
"@storybook/addon-docs": "10.2.15"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ FROM node:24-alpine3.23 AS base
|
||||
FROM base AS installer
|
||||
|
||||
# Enable corepack and prepare pnpm
|
||||
RUN npm install --ignore-scripts -g corepack@latest
|
||||
RUN npm install --ignore-scripts -g corepack@latest
|
||||
RUN corepack enable
|
||||
RUN corepack prepare pnpm@10.28.2 --activate
|
||||
|
||||
@@ -67,7 +67,6 @@ RUN --mount=type=secret,id=database_url \
|
||||
--mount=type=secret,id=encryption_key \
|
||||
--mount=type=secret,id=redis_url \
|
||||
--mount=type=secret,id=sentry_auth_token \
|
||||
--mount=type=secret,id=posthog_key \
|
||||
/tmp/read-secrets.sh pnpm build --filter=@formbricks/web...
|
||||
|
||||
#
|
||||
@@ -75,10 +74,9 @@ RUN --mount=type=secret,id=database_url \
|
||||
#
|
||||
FROM base AS runner
|
||||
|
||||
# Upgrade Alpine system packages to pick up security patches, update npm to latest, then create user
|
||||
# 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 apk update && apk upgrade --no-cache \
|
||||
&& npm install --ignore-scripts -g npm@latest \
|
||||
RUN npm install --ignore-scripts -g npm@latest \
|
||||
&& addgroup -S nextjs \
|
||||
&& adduser -S -u 1001 -G nextjs nextjs
|
||||
|
||||
@@ -122,11 +120,8 @@ RUN chown -R nextjs:nextjs ./node_modules/.prisma && chmod -R 755 ./node_modules
|
||||
COPY --from=installer /app/node_modules/@paralleldrive/cuid2 ./node_modules/@paralleldrive/cuid2
|
||||
RUN chmod -R 755 ./node_modules/@paralleldrive/cuid2
|
||||
|
||||
# Runtime migrations import uuid v7 from the database package, so copy the
|
||||
# database package's resolved install instead of the repo-root hoisted version.
|
||||
COPY --from=installer /app/packages/database/node_modules/uuid ./node_modules/uuid
|
||||
RUN chmod -R 755 ./node_modules/uuid \
|
||||
&& node --input-type=module -e "import('uuid').then((module) => { if (typeof module.v7 !== 'function') throw new Error('uuid v7 missing in runtime image'); })"
|
||||
COPY --from=installer /app/node_modules/uuid ./node_modules/uuid
|
||||
RUN chmod -R 755 ./node_modules/uuid
|
||||
|
||||
COPY --from=installer /app/node_modules/@noble/hashes ./node_modules/@noble/hashes
|
||||
RUN chmod -R 755 ./node_modules/@noble/hashes
|
||||
@@ -169,4 +164,4 @@ RUN mkdir -p /home/nextjs/apps/web/uploads/ && \
|
||||
VOLUME /home/nextjs/apps/web/uploads/
|
||||
VOLUME /home/nextjs/apps/web/saml-connection
|
||||
|
||||
CMD ["/home/nextjs/start.sh"]
|
||||
CMD ["/home/nextjs/start.sh"]
|
||||
@@ -4,10 +4,7 @@ import { AuthorizationError } from "@formbricks/types/errors";
|
||||
import { hasUserEnvironmentAccess } from "@/lib/environment/auth";
|
||||
import { authOptions } from "@/modules/auth/lib/authOptions";
|
||||
|
||||
const OnboardingLayout = async (props: {
|
||||
params: Promise<{ environmentId: string }>;
|
||||
children: React.ReactNode;
|
||||
}) => {
|
||||
const OnboardingLayout = async (props) => {
|
||||
const params = await props.params;
|
||||
|
||||
const { children } = props;
|
||||
|
||||
@@ -2,7 +2,6 @@ import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import { TProject } from "@formbricks/types/project";
|
||||
import { TSurveyElementTypeEnum } from "@formbricks/types/surveys/constants";
|
||||
import { TXMTemplate } from "@formbricks/types/templates";
|
||||
import { replacePresetPlaceholders } from "./utils";
|
||||
|
||||
@@ -40,13 +39,13 @@ const mockTemplate: TXMTemplate = {
|
||||
elements: [
|
||||
{
|
||||
id: "q1",
|
||||
type: "openText" as TSurveyElementTypeEnum.OpenText,
|
||||
type: "openText" as const,
|
||||
inputType: "text" as const,
|
||||
headline: { default: "$[projectName] Question" },
|
||||
subheader: { default: "" },
|
||||
required: false,
|
||||
placeholder: { default: "" },
|
||||
charLimit: { enabled: true, max: 1000 },
|
||||
charLimit: 1000,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -14,7 +14,7 @@ describe("xm-templates", () => {
|
||||
});
|
||||
|
||||
test("getXMSurveyDefault returns default survey template", () => {
|
||||
const tMock = vi.fn((key: string) => key) as unknown as TFunction;
|
||||
const tMock = vi.fn((key) => key) as TFunction;
|
||||
const result = getXMSurveyDefault(tMock);
|
||||
|
||||
expect(result).toEqual({
|
||||
@@ -29,7 +29,7 @@ describe("xm-templates", () => {
|
||||
});
|
||||
|
||||
test("getXMTemplates returns all templates", () => {
|
||||
const tMock = vi.fn((key: string) => key) as unknown as TFunction;
|
||||
const tMock = vi.fn((key) => key) as TFunction;
|
||||
const result = getXMTemplates(tMock);
|
||||
|
||||
expect(result).toHaveLength(6);
|
||||
@@ -44,7 +44,7 @@ describe("xm-templates", () => {
|
||||
test("getXMTemplates handles errors gracefully", async () => {
|
||||
const tMock = vi.fn(() => {
|
||||
throw new Error("Test error");
|
||||
}) as unknown as TFunction;
|
||||
}) as TFunction;
|
||||
|
||||
const result = getXMTemplates(tMock);
|
||||
|
||||
|
||||
@@ -19,8 +19,8 @@ describe("getTeamsByOrganizationId", () => {
|
||||
|
||||
test("returns mapped teams", async () => {
|
||||
const mockTeams = [
|
||||
{ id: "t1", name: "Team 1", createdAt: new Date(), updatedAt: new Date(), organizationId: "org1" },
|
||||
{ id: "t2", name: "Team 2", createdAt: new Date(), updatedAt: new Date(), organizationId: "org1" },
|
||||
{ id: "t1", name: "Team 1" },
|
||||
{ id: "t2", name: "Team 2" },
|
||||
];
|
||||
vi.mocked(prisma.team.findMany).mockResolvedValueOnce(mockTeams);
|
||||
const result = await getTeamsByOrganizationId("org1");
|
||||
|
||||
@@ -22,10 +22,12 @@ export const getTeamsByOrganizationId = reactCache(
|
||||
},
|
||||
});
|
||||
|
||||
return teams.map((team: TOrganizationTeam) => ({
|
||||
const projectTeams = teams.map((team) => ({
|
||||
id: team.id,
|
||||
name: team.name,
|
||||
}));
|
||||
|
||||
return projectTeams;
|
||||
} catch (error) {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
throw new DatabaseError(error.message);
|
||||
|
||||
@@ -5,10 +5,7 @@ import { getMembershipByUserIdOrganizationId } from "@/lib/membership/service";
|
||||
import { getUserProjects } from "@/lib/project/service";
|
||||
import { authOptions } from "@/modules/auth/lib/authOptions";
|
||||
|
||||
const LandingLayout = async (props: {
|
||||
params: Promise<{ organizationId: string }>;
|
||||
children: React.ReactNode;
|
||||
}) => {
|
||||
const LandingLayout = async (props) => {
|
||||
const params = await props.params;
|
||||
|
||||
const { children } = props;
|
||||
|
||||
@@ -10,7 +10,7 @@ import { getIsMultiOrgEnabled } from "@/modules/ee/license-check/lib/utils";
|
||||
import { getOrganizationAuth } from "@/modules/organization/lib/utils";
|
||||
import { Header } from "@/modules/ui/components/header";
|
||||
|
||||
const Page = async (props: { params: Promise<{ organizationId: string }> }) => {
|
||||
const Page = async (props) => {
|
||||
const params = await props.params;
|
||||
const t = await getTranslate();
|
||||
|
||||
|
||||
@@ -8,10 +8,7 @@ import { getTranslate } from "@/lingodotdev/server";
|
||||
import { authOptions } from "@/modules/auth/lib/authOptions";
|
||||
import { ToasterClient } from "@/modules/ui/components/toaster-client";
|
||||
|
||||
const ProjectOnboardingLayout = async (props: {
|
||||
params: Promise<{ organizationId: string }>;
|
||||
children: React.ReactNode;
|
||||
}) => {
|
||||
const ProjectOnboardingLayout = async (props) => {
|
||||
const params = await props.params;
|
||||
|
||||
const { children } = props;
|
||||
|
||||
@@ -8,10 +8,7 @@ import { getTranslate } from "@/lingodotdev/server";
|
||||
import { authOptions } from "@/modules/auth/lib/authOptions";
|
||||
import { getOrganizationProjectsLimit } from "@/modules/ee/license-check/lib/utils";
|
||||
|
||||
const OnboardingLayout = async (props: {
|
||||
params: Promise<{ organizationId: string }>;
|
||||
children: React.ReactNode;
|
||||
}) => {
|
||||
const OnboardingLayout = async (props) => {
|
||||
const params = await props.params;
|
||||
|
||||
const { children } = props;
|
||||
@@ -31,10 +28,8 @@ const OnboardingLayout = async (props: {
|
||||
throw new Error(t("common.organization_not_found"));
|
||||
}
|
||||
|
||||
const [organizationProjectsLimit, organizationProjectsCount] = await Promise.all([
|
||||
getOrganizationProjectsLimit(organization.id),
|
||||
getOrganizationProjectsCount(organization.id),
|
||||
]);
|
||||
const organizationProjectsLimit = await getOrganizationProjectsLimit(organization.billing.limits);
|
||||
const organizationProjectsCount = await getOrganizationProjectsCount(organization.id);
|
||||
|
||||
if (organizationProjectsCount >= organizationProjectsLimit) {
|
||||
return redirect(`/`);
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { getTranslate } from "@/lingodotdev/server";
|
||||
import { SelectPlanCard } from "@/modules/ee/billing/components/select-plan-card";
|
||||
import { Header } from "@/modules/ui/components/header";
|
||||
|
||||
interface SelectPlanOnboardingProps {
|
||||
organizationId: string;
|
||||
}
|
||||
|
||||
export const SelectPlanOnboarding = async ({ organizationId }: SelectPlanOnboardingProps) => {
|
||||
const t = await getTranslate();
|
||||
const nextUrl = `/organizations/${organizationId}/workspaces/new/mode`;
|
||||
|
||||
return (
|
||||
<div className="flex min-h-full min-w-full flex-col items-center justify-center space-y-8">
|
||||
<Header
|
||||
title={t("environments.settings.billing.select_plan_header_title")}
|
||||
subtitle={t("environments.settings.billing.select_plan_header_subtitle")}
|
||||
/>
|
||||
<SelectPlanCard nextUrl={nextUrl} organizationId={organizationId} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { IS_FORMBRICKS_CLOUD } from "@/lib/constants";
|
||||
import { getOrganizationAuth } from "@/modules/organization/lib/utils";
|
||||
import { SelectPlanOnboarding } from "./components/select-plan-onboarding";
|
||||
|
||||
interface PlanPageProps {
|
||||
params: Promise<{
|
||||
organizationId: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
const Page = async (props: PlanPageProps) => {
|
||||
const params = await props.params;
|
||||
|
||||
if (!IS_FORMBRICKS_CLOUD) {
|
||||
return redirect(`/organizations/${params.organizationId}/workspaces/new/mode`);
|
||||
}
|
||||
|
||||
const { session } = await getOrganizationAuth(params.organizationId);
|
||||
|
||||
if (!session?.user) {
|
||||
return redirect(`/auth/login`);
|
||||
}
|
||||
|
||||
return <SelectPlanOnboarding organizationId={params.organizationId} />;
|
||||
};
|
||||
|
||||
export default Page;
|
||||
@@ -42,7 +42,7 @@ const Page = async (props: ProjectSettingsPageProps) => {
|
||||
|
||||
const organizationTeams = await getTeamsByOrganizationId(params.organizationId);
|
||||
|
||||
const isAccessControlAllowed = await getAccessControlPermission(organization.id);
|
||||
const isAccessControlAllowed = await getAccessControlPermission(organization.billing.plan);
|
||||
|
||||
if (!organizationTeams) {
|
||||
throw new Error(t("common.organization_teams_not_found"));
|
||||
|
||||
@@ -16,7 +16,7 @@ interface OnboardingOptionsContainerProps {
|
||||
}
|
||||
|
||||
export const OnboardingOptionsContainer = ({ options }: OnboardingOptionsContainerProps) => {
|
||||
const getOptionCard = (option: OnboardingOptionsContainerProps["options"][number]) => {
|
||||
const getOptionCard = (option) => {
|
||||
const Icon = option.icon;
|
||||
return (
|
||||
<OptionCard
|
||||
|
||||
@@ -2,10 +2,7 @@ import { redirect } from "next/navigation";
|
||||
import { getEnvironment } from "@/lib/environment/service";
|
||||
import { environmentIdLayoutChecks } from "@/modules/environments/lib/utils";
|
||||
|
||||
const SurveyEditorEnvironmentLayout = async (props: {
|
||||
params: Promise<{ environmentId: string }>;
|
||||
children: React.ReactNode;
|
||||
}) => {
|
||||
const SurveyEditorEnvironmentLayout = async (props) => {
|
||||
const params = await props.params;
|
||||
|
||||
const { children } = props;
|
||||
|
||||
@@ -6,26 +6,15 @@ import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@/modules/ui/components/button";
|
||||
import { Confetti } from "@/modules/ui/components/confetti";
|
||||
|
||||
const BILLING_CONFIRMATION_ENVIRONMENT_ID_KEY = "billingConfirmationEnvironmentId";
|
||||
interface ConfirmationPageProps {
|
||||
environmentId: string;
|
||||
}
|
||||
|
||||
export const ConfirmationPage = () => {
|
||||
export const ConfirmationPage = ({ environmentId }: ConfirmationPageProps) => {
|
||||
const { t } = useTranslation();
|
||||
const [showConfetti, setShowConfetti] = useState(false);
|
||||
const [resolvedEnvironmentId, setResolvedEnvironmentId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setShowConfetti(true);
|
||||
|
||||
if (globalThis.window === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const storedEnvironmentId = globalThis.window.sessionStorage.getItem(
|
||||
BILLING_CONFIRMATION_ENVIRONMENT_ID_KEY
|
||||
);
|
||||
if (storedEnvironmentId) {
|
||||
setResolvedEnvironmentId(storedEnvironmentId);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
@@ -41,12 +30,7 @@ export const ConfirmationPage = () => {
|
||||
</p>
|
||||
</div>
|
||||
<Button asChild className="w-full justify-center">
|
||||
<Link
|
||||
href={
|
||||
resolvedEnvironmentId
|
||||
? `/environments/${resolvedEnvironmentId}/settings/billing`
|
||||
: "/environments"
|
||||
}>
|
||||
<Link href={`/environments/${environmentId}/settings/billing`}>
|
||||
{t("billing_confirmation.back_to_billing_overview")}
|
||||
</Link>
|
||||
</Button>
|
||||
|
||||
@@ -3,10 +3,13 @@ import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const Page = async () => {
|
||||
const Page = async (props) => {
|
||||
const searchParams = await props.searchParams;
|
||||
const { environmentId } = searchParams;
|
||||
|
||||
return (
|
||||
<PageContentWrapper>
|
||||
<ConfirmationPage />
|
||||
<ConfirmationPage environmentId={environmentId?.toString()} />
|
||||
</PageContentWrapper>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -10,6 +10,7 @@ import { getOrganizationProjectsCount } from "@/lib/project/service";
|
||||
import { updateUser } from "@/lib/user/service";
|
||||
import { authenticatedActionClient } from "@/lib/utils/action-client";
|
||||
import { checkAuthorizationUpdated } from "@/lib/utils/action-client/action-client-middleware";
|
||||
import { AuthenticatedActionClientCtx } from "@/lib/utils/action-client/types/context";
|
||||
import { withAuditLogging } from "@/modules/ee/audit-logs/lib/handler";
|
||||
import {
|
||||
getAccessControlPermission,
|
||||
@@ -25,62 +26,66 @@ const ZCreateProjectAction = z.object({
|
||||
});
|
||||
|
||||
export const createProjectAction = authenticatedActionClient.inputSchema(ZCreateProjectAction).action(
|
||||
withAuditLogging("created", "project", async ({ ctx, parsedInput }) => {
|
||||
const { user } = ctx;
|
||||
withAuditLogging(
|
||||
"created",
|
||||
"project",
|
||||
async ({ ctx, parsedInput }: { ctx: AuthenticatedActionClientCtx; parsedInput: Record<string, any> }) => {
|
||||
const { user } = ctx;
|
||||
|
||||
const organizationId = parsedInput.organizationId;
|
||||
const organizationId = parsedInput.organizationId;
|
||||
|
||||
await checkAuthorizationUpdated({
|
||||
userId: user.id,
|
||||
organizationId: parsedInput.organizationId,
|
||||
access: [
|
||||
{
|
||||
data: parsedInput.data,
|
||||
schema: ZProjectUpdateInput,
|
||||
type: "organization",
|
||||
roles: ["owner", "manager"],
|
||||
},
|
||||
],
|
||||
});
|
||||
await checkAuthorizationUpdated({
|
||||
userId: user.id,
|
||||
organizationId: parsedInput.organizationId,
|
||||
access: [
|
||||
{
|
||||
data: parsedInput.data,
|
||||
schema: ZProjectUpdateInput,
|
||||
type: "organization",
|
||||
roles: ["owner", "manager"],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const organization = await getOrganization(organizationId);
|
||||
const organization = await getOrganization(organizationId);
|
||||
|
||||
if (!organization) {
|
||||
throw new Error("Organization not found");
|
||||
}
|
||||
|
||||
const organizationProjectsLimit = await getOrganizationProjectsLimit(organization.id);
|
||||
const organizationProjectsCount = await getOrganizationProjectsCount(organization.id);
|
||||
|
||||
if (organizationProjectsCount >= organizationProjectsLimit) {
|
||||
throw new OperationNotAllowedError("Organization workspace limit reached");
|
||||
}
|
||||
|
||||
if (parsedInput.data.teamIds && parsedInput.data.teamIds.length > 0) {
|
||||
const isAccessControlAllowed = await getAccessControlPermission(organization.id);
|
||||
|
||||
if (!isAccessControlAllowed) {
|
||||
throw new OperationNotAllowedError("You do not have permission to manage roles");
|
||||
if (!organization) {
|
||||
throw new Error("Organization not found");
|
||||
}
|
||||
|
||||
const organizationProjectsLimit = await getOrganizationProjectsLimit(organization.billing.limits);
|
||||
const organizationProjectsCount = await getOrganizationProjectsCount(organization.id);
|
||||
|
||||
if (organizationProjectsCount >= organizationProjectsLimit) {
|
||||
throw new OperationNotAllowedError("Organization workspace limit reached");
|
||||
}
|
||||
|
||||
if (parsedInput.data.teamIds && parsedInput.data.teamIds.length > 0) {
|
||||
const isAccessControlAllowed = await getAccessControlPermission(organization.billing.plan);
|
||||
|
||||
if (!isAccessControlAllowed) {
|
||||
throw new OperationNotAllowedError("You do not have permission to manage roles");
|
||||
}
|
||||
}
|
||||
|
||||
const project = await createProject(parsedInput.organizationId, parsedInput.data);
|
||||
const updatedNotificationSettings = {
|
||||
...user.notificationSettings,
|
||||
alert: {
|
||||
...user.notificationSettings?.alert,
|
||||
},
|
||||
};
|
||||
|
||||
await updateUser(user.id, {
|
||||
notificationSettings: updatedNotificationSettings,
|
||||
});
|
||||
|
||||
ctx.auditLoggingCtx.organizationId = organizationId;
|
||||
ctx.auditLoggingCtx.projectId = project.id;
|
||||
ctx.auditLoggingCtx.newObject = project;
|
||||
return project;
|
||||
}
|
||||
|
||||
const project = await createProject(parsedInput.organizationId, parsedInput.data);
|
||||
const updatedNotificationSettings = {
|
||||
...user.notificationSettings,
|
||||
alert: {
|
||||
...user.notificationSettings?.alert,
|
||||
},
|
||||
};
|
||||
|
||||
await updateUser(user.id, {
|
||||
notificationSettings: updatedNotificationSettings,
|
||||
});
|
||||
|
||||
ctx.auditLoggingCtx.organizationId = organizationId;
|
||||
ctx.auditLoggingCtx.projectId = project.id;
|
||||
ctx.auditLoggingCtx.newObject = project;
|
||||
return project;
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
const ZGetOrganizationsForSwitcherAction = z.object({
|
||||
|
||||
@@ -29,6 +29,7 @@ export const EnvironmentLayout = async ({ layoutData, children }: EnvironmentLay
|
||||
isAccessControlAllowed,
|
||||
projectPermission,
|
||||
license,
|
||||
peopleCount,
|
||||
responseCount,
|
||||
} = layoutData;
|
||||
|
||||
@@ -37,7 +38,7 @@ export const EnvironmentLayout = async ({ layoutData, children }: EnvironmentLay
|
||||
|
||||
const { features, lastChecked, isPendingDowngrade, active, status } = license;
|
||||
const isMultiOrgEnabled = features?.isMultiOrgEnabled ?? false;
|
||||
const organizationProjectsLimit = await getOrganizationProjectsLimit(organization.id);
|
||||
const organizationProjectsLimit = await getOrganizationProjectsLimit(organization.billing.limits);
|
||||
const isOwnerOrManager = isOwner || isManager;
|
||||
|
||||
// Validate that project permission exists for members
|
||||
@@ -51,6 +52,7 @@ export const EnvironmentLayout = async ({ layoutData, children }: EnvironmentLay
|
||||
<LimitsReachedBanner
|
||||
organization={organization}
|
||||
environmentId={environment.id}
|
||||
peopleCount={peopleCount}
|
||||
responseCount={responseCount}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -126,7 +126,7 @@ export const MainNavigation = ({
|
||||
name: t("common.configuration"),
|
||||
href: `/environments/${environment.id}/workspace/general`,
|
||||
icon: Cog,
|
||||
isActive: pathname?.includes("/workspace"),
|
||||
isActive: pathname?.includes("/project"),
|
||||
},
|
||||
],
|
||||
[t, environment.id, pathname, isFormbricksCloud]
|
||||
|
||||
@@ -4,7 +4,7 @@ import { getMembershipByUserIdOrganizationId } from "@/lib/membership/service";
|
||||
import { getAccessFlags } from "@/lib/membership/utils";
|
||||
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
|
||||
|
||||
const EnvironmentPage = async (props: { params: Promise<{ environmentId: string }> }) => {
|
||||
const EnvironmentPage = async (props) => {
|
||||
const params = await props.params;
|
||||
const { session, organization } = await getEnvironmentAuth(params.environmentId);
|
||||
|
||||
|
||||
@@ -4,10 +4,7 @@ import { getProjectByEnvironmentId } from "@/lib/project/service";
|
||||
import { getTranslate } from "@/lingodotdev/server";
|
||||
import { authOptions } from "@/modules/auth/lib/authOptions";
|
||||
|
||||
const AccountSettingsLayout = async (props: {
|
||||
params: Promise<{ environmentId: string }>;
|
||||
children: React.ReactNode;
|
||||
}) => {
|
||||
const AccountSettingsLayout = async (props) => {
|
||||
const params = await props.params;
|
||||
|
||||
const { children } = props;
|
||||
|
||||
@@ -4,6 +4,7 @@ import { z } from "zod";
|
||||
import { ZUserNotificationSettings } from "@formbricks/types/user";
|
||||
import { getUser, updateUser } from "@/lib/user/service";
|
||||
import { authenticatedActionClient } from "@/lib/utils/action-client";
|
||||
import { AuthenticatedActionClientCtx } from "@/lib/utils/action-client/types/context";
|
||||
import { withAuditLogging } from "@/modules/ee/audit-logs/lib/handler";
|
||||
|
||||
const ZUpdateNotificationSettingsAction = z.object({
|
||||
@@ -13,14 +14,24 @@ const ZUpdateNotificationSettingsAction = z.object({
|
||||
export const updateNotificationSettingsAction = authenticatedActionClient
|
||||
.inputSchema(ZUpdateNotificationSettingsAction)
|
||||
.action(
|
||||
withAuditLogging("updated", "user", async ({ ctx, parsedInput }) => {
|
||||
const oldObject = await getUser(ctx.user.id);
|
||||
const result = await updateUser(ctx.user.id, {
|
||||
notificationSettings: parsedInput.notificationSettings,
|
||||
});
|
||||
ctx.auditLoggingCtx.userId = ctx.user.id;
|
||||
ctx.auditLoggingCtx.oldObject = oldObject;
|
||||
ctx.auditLoggingCtx.newObject = result;
|
||||
return result;
|
||||
})
|
||||
withAuditLogging(
|
||||
"updated",
|
||||
"user",
|
||||
async ({
|
||||
ctx,
|
||||
parsedInput,
|
||||
}: {
|
||||
ctx: AuthenticatedActionClientCtx;
|
||||
parsedInput: Record<string, any>;
|
||||
}) => {
|
||||
const oldObject = await getUser(ctx.user.id);
|
||||
const result = await updateUser(ctx.user.id, {
|
||||
notificationSettings: parsedInput.notificationSettings,
|
||||
});
|
||||
ctx.auditLoggingCtx.userId = ctx.user.id;
|
||||
ctx.auditLoggingCtx.oldObject = oldObject;
|
||||
ctx.auditLoggingCtx.newObject = result;
|
||||
return result;
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
@@ -16,8 +16,8 @@ const setCompleteNotificationSettings = (
|
||||
notificationSettings: TUserNotificationSettings,
|
||||
memberships: Membership[]
|
||||
): TUserNotificationSettings => {
|
||||
const newNotificationSettings: TUserNotificationSettings = {
|
||||
alert: {} as Record<string, boolean>,
|
||||
const newNotificationSettings = {
|
||||
alert: {},
|
||||
unsubscribedOrganizationIds: notificationSettings.unsubscribedOrganizationIds || [],
|
||||
};
|
||||
for (const membership of memberships) {
|
||||
@@ -26,8 +26,7 @@ const setCompleteNotificationSettings = (
|
||||
for (const environment of project.environments) {
|
||||
for (const survey of environment.surveys) {
|
||||
newNotificationSettings.alert[survey.id] =
|
||||
(notificationSettings as unknown as Record<string, Record<string, boolean>>)[survey.id]
|
||||
?.responseFinished ||
|
||||
notificationSettings[survey.id]?.responseFinished ||
|
||||
(notificationSettings.alert && notificationSettings.alert[survey.id]) ||
|
||||
false; // check for legacy notification settings w/o "alerts" key
|
||||
}
|
||||
@@ -137,10 +136,7 @@ const getMemberships = async (userId: string): Promise<Membership[]> => {
|
||||
return memberships;
|
||||
};
|
||||
|
||||
const Page = async (props: {
|
||||
params: Promise<{ environmentId: string }>;
|
||||
searchParams: Promise<Record<string, string>>;
|
||||
}) => {
|
||||
const Page = async (props) => {
|
||||
const searchParams = await props.searchParams;
|
||||
const params = await props.params;
|
||||
const t = await getTranslate();
|
||||
|
||||
@@ -20,7 +20,7 @@ import { rateLimitConfigs } from "@/modules/core/rate-limit/rate-limit-configs";
|
||||
import { withAuditLogging } from "@/modules/ee/audit-logs/lib/handler";
|
||||
import { sendForgotPasswordEmail, sendVerificationNewEmail } from "@/modules/email";
|
||||
|
||||
function buildUserUpdatePayload(parsedInput: TUserPersonalInfoUpdateInput): TUserUpdateInput {
|
||||
function buildUserUpdatePayload(parsedInput: any): TUserUpdateInput {
|
||||
return {
|
||||
...(parsedInput.name && { name: parsedInput.name }),
|
||||
...(parsedInput.locale && { locale: parsedInput.locale }),
|
||||
@@ -64,35 +64,49 @@ async function handleEmailUpdate({
|
||||
}
|
||||
|
||||
export const updateUserAction = authenticatedActionClient.inputSchema(ZUserPersonalInfoUpdateInput).action(
|
||||
withAuditLogging("updated", "user", async ({ ctx, parsedInput }) => {
|
||||
const oldObject = await getUser(ctx.user.id);
|
||||
let payload = buildUserUpdatePayload(parsedInput);
|
||||
payload = await handleEmailUpdate({ ctx, parsedInput, payload });
|
||||
withAuditLogging(
|
||||
"updated",
|
||||
"user",
|
||||
async ({
|
||||
ctx,
|
||||
parsedInput,
|
||||
}: {
|
||||
ctx: AuthenticatedActionClientCtx;
|
||||
parsedInput: TUserPersonalInfoUpdateInput;
|
||||
}) => {
|
||||
const oldObject = await getUser(ctx.user.id);
|
||||
let payload = buildUserUpdatePayload(parsedInput);
|
||||
payload = await handleEmailUpdate({ ctx, parsedInput, payload });
|
||||
|
||||
// Only proceed with updateUser if we have actual changes to make
|
||||
let newObject = oldObject;
|
||||
if (Object.keys(payload).length > 0) {
|
||||
newObject = await updateUser(ctx.user.id, payload);
|
||||
// Only proceed with updateUser if we have actual changes to make
|
||||
let newObject = oldObject;
|
||||
if (Object.keys(payload).length > 0) {
|
||||
newObject = await updateUser(ctx.user.id, payload);
|
||||
}
|
||||
|
||||
ctx.auditLoggingCtx.userId = ctx.user.id;
|
||||
ctx.auditLoggingCtx.oldObject = oldObject;
|
||||
ctx.auditLoggingCtx.newObject = newObject;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
ctx.auditLoggingCtx.userId = ctx.user.id;
|
||||
ctx.auditLoggingCtx.oldObject = oldObject;
|
||||
ctx.auditLoggingCtx.newObject = newObject;
|
||||
|
||||
return true;
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
export const resetPasswordAction = authenticatedActionClient.action(
|
||||
withAuditLogging("passwordReset", "user", async ({ ctx }) => {
|
||||
if (ctx.user.identityProvider !== "email") {
|
||||
throw new OperationNotAllowedError("Password reset is not allowed for this user.");
|
||||
withAuditLogging(
|
||||
"passwordReset",
|
||||
"user",
|
||||
async ({ ctx }: { ctx: AuthenticatedActionClientCtx; parsedInput: undefined }) => {
|
||||
if (ctx.user.identityProvider !== "email") {
|
||||
throw new OperationNotAllowedError("Password reset is not allowed for this user.");
|
||||
}
|
||||
|
||||
await sendForgotPasswordEmail(ctx.user);
|
||||
|
||||
ctx.auditLoggingCtx.userId = ctx.user.id;
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
await sendForgotPasswordEmail(ctx.user);
|
||||
|
||||
ctx.auditLoggingCtx.userId = ctx.user.id;
|
||||
|
||||
return { success: true };
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
@@ -28,7 +28,7 @@ const Page = async (props: { params: Promise<{ environmentId: string }> }) => {
|
||||
throw new Error(t("common.session_not_found"));
|
||||
}
|
||||
|
||||
const hasWhiteLabelPermission = await getWhiteLabelPermission(organization.id);
|
||||
const hasWhiteLabelPermission = await getWhiteLabelPermission(organization.billing.plan);
|
||||
const isOwnerOrManager = isManager || isOwner;
|
||||
|
||||
const surveys = await getSurveysWithSlugsByOrganizationId(organization.id);
|
||||
|
||||
@@ -7,20 +7,21 @@ import { useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { recheckLicenseAction } from "@/modules/ee/license-check/actions";
|
||||
import type { TLicenseStatus } from "@/modules/ee/license-check/types/enterprise-license";
|
||||
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: TLicenseStatus;
|
||||
status: LicenseStatus;
|
||||
gracePeriodEnd?: Date;
|
||||
environmentId: string;
|
||||
}
|
||||
|
||||
const getBadgeConfig = (
|
||||
status: TLicenseStatus,
|
||||
status: LicenseStatus,
|
||||
t: TFunction
|
||||
): { type: "success" | "error" | "warning" | "gray"; label: string } => {
|
||||
switch (status) {
|
||||
@@ -28,11 +29,6 @@ const getBadgeConfig = (
|
||||
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 "instance_mismatch":
|
||||
return {
|
||||
type: "error",
|
||||
label: t("environments.settings.enterprise.license_status_instance_mismatch"),
|
||||
};
|
||||
case "unreachable":
|
||||
return { type: "warning", label: t("environments.settings.enterprise.license_status_unreachable") };
|
||||
case "invalid_license":
|
||||
@@ -63,8 +59,6 @@ export const EnterpriseLicenseStatus = ({
|
||||
if (result?.data) {
|
||||
if (result.data.status === "unreachable") {
|
||||
toast.error(t("environments.settings.enterprise.recheck_license_unreachable"));
|
||||
} else if (result.data.status === "instance_mismatch") {
|
||||
toast.error(t("environments.settings.enterprise.recheck_license_instance_mismatch"));
|
||||
} else if (result.data.status === "invalid_license") {
|
||||
toast.error(t("environments.settings.enterprise.recheck_license_invalid"));
|
||||
} else {
|
||||
@@ -134,13 +128,6 @@ export const EnterpriseLicenseStatus = ({
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{status === "instance_mismatch" && (
|
||||
<Alert variant="error" size="small">
|
||||
<AlertDescription className="overflow-visible whitespace-normal">
|
||||
{t("environments.settings.enterprise.license_instance_mismatch_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
|
||||
|
||||
@@ -11,7 +11,7 @@ import { Button } from "@/modules/ui/components/button";
|
||||
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
|
||||
import { PageHeader } from "@/modules/ui/components/page-header";
|
||||
|
||||
const Page = async (props: { params: Promise<{ environmentId: string }> }) => {
|
||||
const Page = async (props) => {
|
||||
const params = await props.params;
|
||||
const t = await getTranslate();
|
||||
if (IS_FORMBRICKS_CLOUD) {
|
||||
@@ -94,7 +94,7 @@ const Page = async (props: { params: Promise<{ environmentId: string }> }) => {
|
||||
</PageHeader>
|
||||
{hasLicense ? (
|
||||
<EnterpriseLicenseStatus
|
||||
status={licenseState.status}
|
||||
status={licenseState.status as "active" | "expired" | "unreachable" | "invalid_license"}
|
||||
gracePeriodEnd={
|
||||
licenseState.status === "unreachable"
|
||||
? new Date(licenseState.lastChecked.getTime() + GRACE_PERIOD_MS)
|
||||
|
||||
@@ -7,6 +7,7 @@ import { ZOrganizationUpdateInput } from "@formbricks/types/organizations";
|
||||
import { deleteOrganization, getOrganization, updateOrganization } from "@/lib/organization/service";
|
||||
import { authenticatedActionClient } from "@/lib/utils/action-client";
|
||||
import { checkAuthorizationUpdated } from "@/lib/utils/action-client/action-client-middleware";
|
||||
import { AuthenticatedActionClientCtx } from "@/lib/utils/action-client/types/context";
|
||||
import { withAuditLogging } from "@/modules/ee/audit-logs/lib/handler";
|
||||
import { getIsMultiOrgEnabled } from "@/modules/ee/license-check/lib/utils";
|
||||
|
||||
@@ -18,26 +19,36 @@ const ZUpdateOrganizationNameAction = z.object({
|
||||
export const updateOrganizationNameAction = authenticatedActionClient
|
||||
.inputSchema(ZUpdateOrganizationNameAction)
|
||||
.action(
|
||||
withAuditLogging("updated", "organization", async ({ ctx, parsedInput }) => {
|
||||
await checkAuthorizationUpdated({
|
||||
userId: ctx.user.id,
|
||||
organizationId: parsedInput.organizationId,
|
||||
access: [
|
||||
{
|
||||
type: "organization",
|
||||
schema: ZOrganizationUpdateInput.pick({ name: true }),
|
||||
data: parsedInput.data,
|
||||
roles: ["owner"],
|
||||
},
|
||||
],
|
||||
});
|
||||
ctx.auditLoggingCtx.organizationId = parsedInput.organizationId;
|
||||
const oldObject = await getOrganization(parsedInput.organizationId);
|
||||
const result = await updateOrganization(parsedInput.organizationId, parsedInput.data);
|
||||
ctx.auditLoggingCtx.oldObject = oldObject;
|
||||
ctx.auditLoggingCtx.newObject = result;
|
||||
return result;
|
||||
})
|
||||
withAuditLogging(
|
||||
"updated",
|
||||
"organization",
|
||||
async ({
|
||||
ctx,
|
||||
parsedInput,
|
||||
}: {
|
||||
ctx: AuthenticatedActionClientCtx;
|
||||
parsedInput: Record<string, any>;
|
||||
}) => {
|
||||
await checkAuthorizationUpdated({
|
||||
userId: ctx.user.id,
|
||||
organizationId: parsedInput.organizationId,
|
||||
access: [
|
||||
{
|
||||
type: "organization",
|
||||
schema: ZOrganizationUpdateInput.pick({ name: true }),
|
||||
data: parsedInput.data,
|
||||
roles: ["owner"],
|
||||
},
|
||||
],
|
||||
});
|
||||
ctx.auditLoggingCtx.organizationId = parsedInput.organizationId;
|
||||
const oldObject = await getOrganization(parsedInput.organizationId);
|
||||
const result = await updateOrganization(parsedInput.organizationId, parsedInput.data);
|
||||
ctx.auditLoggingCtx.oldObject = oldObject;
|
||||
ctx.auditLoggingCtx.newObject = result;
|
||||
return result;
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
const ZDeleteOrganizationAction = z.object({
|
||||
@@ -47,23 +58,33 @@ const ZDeleteOrganizationAction = z.object({
|
||||
export const deleteOrganizationAction = authenticatedActionClient
|
||||
.inputSchema(ZDeleteOrganizationAction)
|
||||
.action(
|
||||
withAuditLogging("deleted", "organization", async ({ ctx, parsedInput }) => {
|
||||
const isMultiOrgEnabled = await getIsMultiOrgEnabled();
|
||||
if (!isMultiOrgEnabled) throw new OperationNotAllowedError("Organization deletion disabled");
|
||||
withAuditLogging(
|
||||
"deleted",
|
||||
"organization",
|
||||
async ({
|
||||
ctx,
|
||||
parsedInput,
|
||||
}: {
|
||||
ctx: AuthenticatedActionClientCtx;
|
||||
parsedInput: Record<string, any>;
|
||||
}) => {
|
||||
const isMultiOrgEnabled = await getIsMultiOrgEnabled();
|
||||
if (!isMultiOrgEnabled) throw new OperationNotAllowedError("Organization deletion disabled");
|
||||
|
||||
await checkAuthorizationUpdated({
|
||||
userId: ctx.user.id,
|
||||
organizationId: parsedInput.organizationId,
|
||||
access: [
|
||||
{
|
||||
type: "organization",
|
||||
roles: ["owner"],
|
||||
},
|
||||
],
|
||||
});
|
||||
ctx.auditLoggingCtx.organizationId = parsedInput.organizationId;
|
||||
const oldObject = await getOrganization(parsedInput.organizationId);
|
||||
ctx.auditLoggingCtx.oldObject = oldObject;
|
||||
return await deleteOrganization(parsedInput.organizationId);
|
||||
})
|
||||
await checkAuthorizationUpdated({
|
||||
userId: ctx.user.id,
|
||||
organizationId: parsedInput.organizationId,
|
||||
access: [
|
||||
{
|
||||
type: "organization",
|
||||
roles: ["owner"],
|
||||
},
|
||||
],
|
||||
});
|
||||
ctx.auditLoggingCtx.organizationId = parsedInput.organizationId;
|
||||
const oldObject = await getOrganization(parsedInput.organizationId);
|
||||
ctx.auditLoggingCtx.oldObject = oldObject;
|
||||
return await deleteOrganization(parsedInput.organizationId);
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
@@ -107,7 +107,7 @@ const DeleteOrganizationModal = ({
|
||||
}: DeleteOrganizationModalProps) => {
|
||||
const [inputValue, setInputValue] = useState("");
|
||||
const { t } = useTranslation();
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const handleInputChange = (e) => {
|
||||
setInputValue(e.target.value);
|
||||
};
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ export const EditOrganizationNameForm = ({ organization, membershipRole }: EditO
|
||||
toast.error(errorMessage);
|
||||
}
|
||||
} catch (err) {
|
||||
toast.error(`Error: ${err instanceof Error ? err.message : "Unknown error occurred"}`);
|
||||
toast.error(`Error: ${err.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ const Page = async (props: { params: Promise<{ environmentId: string }> }) => {
|
||||
const user = session?.user?.id ? await getUser(session.user.id) : null;
|
||||
|
||||
const isMultiOrgEnabled = await getIsMultiOrgEnabled();
|
||||
const hasWhiteLabelPermission = await getWhiteLabelPermission(organization.id);
|
||||
const hasWhiteLabelPermission = await getWhiteLabelPermission(organization.billing.plan);
|
||||
|
||||
const isDeleteDisabled = !isOwner || !isMultiOrgEnabled;
|
||||
const currentUserRole = currentUserMembership?.role;
|
||||
|
||||
@@ -4,7 +4,7 @@ import { getProjectByEnvironmentId } from "@/lib/project/service";
|
||||
import { getTranslate } from "@/lingodotdev/server";
|
||||
import { authOptions } from "@/modules/auth/lib/authOptions";
|
||||
|
||||
const Layout = async (props: { params: Promise<{ environmentId: string }>; children: React.ReactNode }) => {
|
||||
const Layout = async (props) => {
|
||||
const params = await props.params;
|
||||
|
||||
const { children } = props;
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
export const SettingsTitle = ({ title }: { title: string }) => {
|
||||
export const SettingsTitle = ({ title }) => {
|
||||
return <h2 className="my-4 text-2xl font-medium leading-6 text-slate-800">{title}</h2>;
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
const Page = async (props: { params: Promise<{ environmentId: string }> }) => {
|
||||
const Page = async (props) => {
|
||||
const params = await props.params;
|
||||
return redirect(`/environments/${params.environmentId}/settings/profile`);
|
||||
};
|
||||
|
||||
@@ -27,7 +27,7 @@ export const generateMetadata = async (props: Props): Promise<Metadata> => {
|
||||
};
|
||||
};
|
||||
|
||||
const SurveyLayout = async ({ children }: { children: React.ReactNode }) => {
|
||||
const SurveyLayout = async ({ children }) => {
|
||||
return <ResponseFilterProvider>{children}</ResponseFilterProvider>;
|
||||
};
|
||||
|
||||
|
||||
@@ -205,11 +205,11 @@ export const ResponseTable = ({
|
||||
};
|
||||
|
||||
// Handle downloading selected responses
|
||||
const downloadSelectedRows = async (responseIds: string[], format: "xlsx" | "csv") => {
|
||||
const downloadSelectedRows = async (responseIds: string[], format: "csv" | "xlsx") => {
|
||||
try {
|
||||
const downloadResponse = await getResponsesDownloadUrlAction({
|
||||
surveyId: survey.id,
|
||||
format,
|
||||
format: format,
|
||||
filterCriteria: { responseIds },
|
||||
});
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { TFunction } from "i18next";
|
||||
import { CircleHelpIcon, EyeOffIcon, MailIcon, TagIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { TResponseTableData } from "@formbricks/types/responses";
|
||||
import { TSurveyElement, TSurveyElementTypeEnum } from "@formbricks/types/surveys/elements";
|
||||
import { TSurveyElement } from "@formbricks/types/surveys/elements";
|
||||
import { TSurvey } from "@formbricks/types/surveys/types";
|
||||
import { getTextContent } from "@formbricks/types/surveys/validation";
|
||||
import { getLocalizedValue } from "@/lib/i18n/utils";
|
||||
@@ -41,7 +41,7 @@ const getElementColumnsData = (
|
||||
const contactInfoFields = ["firstName", "lastName", "email", "phone", "company"];
|
||||
|
||||
// Helper function to create consistent column headers
|
||||
const createElementHeader = (elementType: TSurveyElementTypeEnum, headline: string, suffix?: string) => {
|
||||
const createElementHeader = (elementType: string, headline: string, suffix?: string) => {
|
||||
const title = suffix ? `${headline} - ${suffix}` : headline;
|
||||
const ElementHeader = () => (
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -232,7 +232,7 @@ const getMetadataColumnsData = (t: TFunction): ColumnDef<TResponseTableData>[] =
|
||||
const metadataColumns: ColumnDef<TResponseTableData>[] = [];
|
||||
|
||||
METADATA_FIELDS.forEach((label) => {
|
||||
const IconComponent = COLUMNS_ICON_MAP[label as keyof typeof COLUMNS_ICON_MAP];
|
||||
const IconComponent = COLUMNS_ICON_MAP[label];
|
||||
|
||||
metadataColumns.push({
|
||||
accessorKey: "METADATA_" + label,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { TFunction } from "i18next";
|
||||
import {
|
||||
AirplayIcon,
|
||||
ArrowUpFromDotIcon,
|
||||
@@ -39,7 +38,7 @@ describe("utils", () => {
|
||||
"environments.surveys.responses.source": "Source",
|
||||
};
|
||||
return translations[key] || key;
|
||||
}) as unknown as TFunction;
|
||||
});
|
||||
|
||||
describe("getAddressFieldLabel", () => {
|
||||
test("returns correct label for addressLine1", () => {
|
||||
|
||||
@@ -80,24 +80,9 @@ export const COLUMNS_ICON_MAP = {
|
||||
const userAgentFields = ["browser", "os", "device"];
|
||||
export const METADATA_FIELDS = ["action", "country", ...userAgentFields, "source", "url"];
|
||||
|
||||
export const getMetadataValue = (
|
||||
meta: TResponseMeta,
|
||||
label: (typeof METADATA_FIELDS)[number]
|
||||
): string | undefined => {
|
||||
switch (label) {
|
||||
case "browser":
|
||||
return meta.userAgent?.browser;
|
||||
case "os":
|
||||
return meta.userAgent?.os;
|
||||
case "device":
|
||||
return meta.userAgent?.device;
|
||||
case "action":
|
||||
return meta.action;
|
||||
case "country":
|
||||
return meta.country;
|
||||
case "source":
|
||||
return meta.source;
|
||||
case "url":
|
||||
return meta.url;
|
||||
export const getMetadataValue = (meta: TResponseMeta, label: string) => {
|
||||
if (userAgentFields.includes(label)) {
|
||||
return meta.userAgent?.[label];
|
||||
}
|
||||
return meta[label];
|
||||
};
|
||||
|
||||
@@ -17,7 +17,7 @@ import { getOrganizationBilling } from "@/modules/survey/lib/survey";
|
||||
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
|
||||
import { PageHeader } from "@/modules/ui/components/page-header";
|
||||
|
||||
const Page = async (props: { params: Promise<{ environmentId: string; surveyId: string }> }) => {
|
||||
const Page = async (props) => {
|
||||
const params = await props.params;
|
||||
const t = await getTranslate();
|
||||
|
||||
@@ -27,7 +27,7 @@ const Page = async (props: { params: Promise<{ environmentId: string; surveyId:
|
||||
getSurvey(params.surveyId),
|
||||
getUser(session.user.id),
|
||||
getTagsByEnvironmentId(params.environmentId),
|
||||
getIsContactsEnabled(organization.id),
|
||||
getIsContactsEnabled(),
|
||||
getResponseCountBySurveyId(params.surveyId),
|
||||
findMatchingLocale(),
|
||||
]);
|
||||
@@ -53,7 +53,7 @@ const Page = async (props: { params: Promise<{ environmentId: string; surveyId:
|
||||
throw new Error(t("common.organization_not_found"));
|
||||
}
|
||||
|
||||
const isQuotasAllowed = await getIsQuotasEnabled(organization.id);
|
||||
const isQuotasAllowed = await getIsQuotasEnabled(organizationBilling.plan);
|
||||
const quotas = isQuotasAllowed ? await getQuotas(survey.id) : [];
|
||||
|
||||
// Fetch initial responses on the server to prevent duplicate client-side fetch
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getEmailTemplateHtml } from "@/app/(app)/environments/[environmentId]/s
|
||||
import { getSurvey, updateSurvey } from "@/lib/survey/service";
|
||||
import { authenticatedActionClient } from "@/lib/utils/action-client";
|
||||
import { checkAuthorizationUpdated } from "@/lib/utils/action-client/action-client-middleware";
|
||||
import { AuthenticatedActionClientCtx } from "@/lib/utils/action-client/types/context";
|
||||
import { convertToCsv } from "@/lib/utils/file-conversion";
|
||||
import { getOrganizationIdFromSurveyId, getProjectIdFromSurveyId } from "@/lib/utils/helper";
|
||||
import { withAuditLogging } from "@/modules/ee/audit-logs/lib/handler";
|
||||
@@ -69,42 +70,52 @@ const ZResetSurveyAction = z.object({
|
||||
});
|
||||
|
||||
export const resetSurveyAction = authenticatedActionClient.inputSchema(ZResetSurveyAction).action(
|
||||
withAuditLogging("updated", "survey", async ({ ctx, parsedInput }) => {
|
||||
await checkAuthorizationUpdated({
|
||||
userId: ctx.user.id,
|
||||
organizationId: parsedInput.organizationId,
|
||||
access: [
|
||||
{
|
||||
type: "organization",
|
||||
roles: ["owner", "manager"],
|
||||
},
|
||||
{
|
||||
type: "projectTeam",
|
||||
minPermission: "readWrite",
|
||||
projectId: parsedInput.projectId,
|
||||
},
|
||||
],
|
||||
});
|
||||
withAuditLogging(
|
||||
"updated",
|
||||
"survey",
|
||||
async ({
|
||||
ctx,
|
||||
parsedInput,
|
||||
}: {
|
||||
ctx: AuthenticatedActionClientCtx;
|
||||
parsedInput: z.infer<typeof ZResetSurveyAction>;
|
||||
}) => {
|
||||
await checkAuthorizationUpdated({
|
||||
userId: ctx.user.id,
|
||||
organizationId: parsedInput.organizationId,
|
||||
access: [
|
||||
{
|
||||
type: "organization",
|
||||
roles: ["owner", "manager"],
|
||||
},
|
||||
{
|
||||
type: "projectTeam",
|
||||
minPermission: "readWrite",
|
||||
projectId: parsedInput.projectId,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
ctx.auditLoggingCtx.organizationId = parsedInput.organizationId;
|
||||
ctx.auditLoggingCtx.surveyId = parsedInput.surveyId;
|
||||
ctx.auditLoggingCtx.oldObject = null;
|
||||
ctx.auditLoggingCtx.organizationId = parsedInput.organizationId;
|
||||
ctx.auditLoggingCtx.surveyId = parsedInput.surveyId;
|
||||
ctx.auditLoggingCtx.oldObject = null;
|
||||
|
||||
const { deletedResponsesCount, deletedDisplaysCount } = await deleteResponsesAndDisplaysForSurvey(
|
||||
parsedInput.surveyId
|
||||
);
|
||||
const { deletedResponsesCount, deletedDisplaysCount } = await deleteResponsesAndDisplaysForSurvey(
|
||||
parsedInput.surveyId
|
||||
);
|
||||
|
||||
ctx.auditLoggingCtx.newObject = {
|
||||
deletedResponsesCount: deletedResponsesCount,
|
||||
deletedDisplaysCount: deletedDisplaysCount,
|
||||
};
|
||||
ctx.auditLoggingCtx.newObject = {
|
||||
deletedResponsesCount: deletedResponsesCount,
|
||||
deletedDisplaysCount: deletedDisplaysCount,
|
||||
};
|
||||
|
||||
return {
|
||||
success: true,
|
||||
deletedResponsesCount: deletedResponsesCount,
|
||||
deletedDisplaysCount: deletedDisplaysCount,
|
||||
};
|
||||
})
|
||||
return {
|
||||
success: true,
|
||||
deletedResponsesCount: deletedResponsesCount,
|
||||
deletedDisplaysCount: deletedDisplaysCount,
|
||||
};
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
const ZGetEmailHtmlAction = z.object({
|
||||
@@ -143,8 +154,7 @@ const ZGeneratePersonalLinksAction = z.object({
|
||||
export const generatePersonalLinksAction = authenticatedActionClient
|
||||
.inputSchema(ZGeneratePersonalLinksAction)
|
||||
.action(async ({ ctx, parsedInput }) => {
|
||||
const organizationId = await getOrganizationIdFromSurveyId(parsedInput.surveyId);
|
||||
const isContactsEnabled = await getIsContactsEnabled(organizationId);
|
||||
const isContactsEnabled = await getIsContactsEnabled();
|
||||
if (!isContactsEnabled) {
|
||||
throw new OperationNotAllowedError("Contacts are not enabled for this environment");
|
||||
}
|
||||
|
||||
@@ -60,9 +60,7 @@ export const NPSSummary = ({ elementSummary, survey, setFilter }: NPSSummaryProp
|
||||
},
|
||||
};
|
||||
|
||||
const filter = (filters as Record<string, { comparison: string; values: string | string[] | undefined }>)[
|
||||
group
|
||||
];
|
||||
const filter = filters[group];
|
||||
|
||||
if (filter) {
|
||||
setFilter(
|
||||
@@ -106,7 +104,7 @@ export const NPSSummary = ({ elementSummary, survey, setFilter }: NPSSummaryProp
|
||||
<TabsContent value="aggregated" className="mt-4">
|
||||
<div className="px-4 pb-6 pt-4 md:px-6">
|
||||
<div className="space-y-5 text-sm md:text-base">
|
||||
{(["promoters", "passives", "detractors", "dismissed"] as const).map((group) => (
|
||||
{["promoters", "passives", "detractors", "dismissed"].map((group) => (
|
||||
<button
|
||||
className="w-full cursor-pointer hover:opacity-80"
|
||||
key={group}
|
||||
|
||||
@@ -15,7 +15,7 @@ interface SummaryMetadataProps {
|
||||
isQuotasAllowed: boolean;
|
||||
}
|
||||
|
||||
const formatTime = (ttc: number) => {
|
||||
const formatTime = (ttc) => {
|
||||
const seconds = ttc / 1000;
|
||||
let formattedValue;
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ export const SummaryPage = ({
|
||||
setDisplays(data);
|
||||
setHasMoreDisplays(data.length === DISPLAYS_PER_PAGE);
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : String(error));
|
||||
toast.error(error);
|
||||
setDisplays([]);
|
||||
setHasMoreDisplays(false);
|
||||
} finally {
|
||||
|
||||
@@ -75,7 +75,17 @@ export const ShareSurveyModal = ({
|
||||
const [showView, setShowView] = useState<ModalView>(modalView);
|
||||
const { email } = user;
|
||||
const { t } = useTranslation();
|
||||
const linkTabs = useMemo(() => {
|
||||
const linkTabs: {
|
||||
id: ShareViaType | ShareSettingsType;
|
||||
type: LinkTabsType;
|
||||
label: string;
|
||||
icon: React.ElementType;
|
||||
title: string;
|
||||
description: string;
|
||||
componentType: React.ComponentType<unknown>;
|
||||
componentProps: unknown;
|
||||
disabled?: boolean;
|
||||
}[] = useMemo(() => {
|
||||
const tabs = [
|
||||
{
|
||||
id: ShareViaType.ANON_LINKS,
|
||||
|
||||
@@ -47,7 +47,6 @@ const createNoCodeConfigType = (t: ReturnType<typeof useTranslation>["t"]) => ({
|
||||
pageView: t("environments.actions.page_view"),
|
||||
exitIntent: t("environments.actions.exit_intent"),
|
||||
fiftyPercentScroll: t("environments.actions.fifty_percent_scroll"),
|
||||
pageDwell: t("environments.actions.time_on_page"),
|
||||
});
|
||||
|
||||
const formatRecontactDaysString = (days: number, t: ReturnType<typeof useTranslation>["t"]) => {
|
||||
|
||||
@@ -39,7 +39,7 @@ export const QRCodeTab = ({ surveyUrl }: QRCodeTabProps) => {
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(error as Error, "Failed to generate QR code");
|
||||
logger.error("Failed to generate QR code:", error);
|
||||
setHasError(true);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
@@ -66,7 +66,7 @@ export const QRCodeTab = ({ surveyUrl }: QRCodeTabProps) => {
|
||||
downloadInstance.download({ name: "survey-qr-code", extension: "png" });
|
||||
toast.success(t("environments.surveys.summary.qr_code_download_with_start_soon"));
|
||||
} catch (error) {
|
||||
logger.error(error as Error, "Failed to download QR code");
|
||||
logger.error("Failed to download QR code:", error);
|
||||
toast.error(t("environments.surveys.summary.qr_code_download_failed"));
|
||||
} finally {
|
||||
setIsDownloading(false);
|
||||
|
||||
@@ -4,10 +4,6 @@ import React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { TSurvey } from "@formbricks/types/surveys/types";
|
||||
import { TUser } from "@formbricks/types/user";
|
||||
import {
|
||||
ShareSettingsType,
|
||||
ShareViaType,
|
||||
} from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/types/share";
|
||||
import { ShareSurveyLink } from "@/modules/analysis/components/ShareSurveyLink";
|
||||
import { Badge } from "@/modules/ui/components/badge";
|
||||
|
||||
@@ -17,9 +13,9 @@ interface SuccessViewProps {
|
||||
publicDomain: string;
|
||||
setSurveyUrl: (url: string) => void;
|
||||
user: TUser;
|
||||
tabs: { id: ShareViaType | ShareSettingsType; label: string; icon: React.ElementType }[];
|
||||
handleViewChange: (view: "start" | "share") => void;
|
||||
handleEmbedViewWithTab: (tabId: ShareViaType | ShareSettingsType) => void;
|
||||
tabs: { id: string; label: string; icon: React.ElementType }[];
|
||||
handleViewChange: (view: string) => void;
|
||||
handleEmbedViewWithTab: (tabId: string) => void;
|
||||
isReadOnly: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ describe("Tests for getQuotasSummary service", () => {
|
||||
_count: {
|
||||
quotaLinks: 0,
|
||||
},
|
||||
} as unknown as Awaited<ReturnType<typeof prisma.surveyQuota.findMany>>[number],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await getQuotasSummary(surveyId);
|
||||
@@ -120,7 +120,7 @@ describe("Tests for getQuotasSummary service", () => {
|
||||
_count: {
|
||||
quotaLinks: 0,
|
||||
},
|
||||
} as unknown as Awaited<ReturnType<typeof prisma.surveyQuota.findMany>>[number],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await getQuotasSummary(surveyId);
|
||||
|
||||
@@ -662,23 +662,17 @@ describe("getQuestionSummary", () => {
|
||||
expect((summary[0] as any).choices).toHaveLength(3);
|
||||
|
||||
// Item 1 is in position 1 once and position 2 once, so avg ranking should be (1+2)/2 = 1.5
|
||||
const item1 = (summary[0] as any).choices.find(
|
||||
(c: { value: string; count: number; avgRanking: number }) => c.value === "Item 1"
|
||||
);
|
||||
const item1 = (summary[0] as any).choices.find((c) => c.value === "Item 1");
|
||||
expect(item1.count).toBe(2);
|
||||
expect(item1.avgRanking).toBe(1.5);
|
||||
|
||||
// Item 2 is in position 1 once and position 2 once, so avg ranking should be (1+2)/2 = 1.5
|
||||
const item2 = (summary[0] as any).choices.find(
|
||||
(c: { value: string; count: number; avgRanking: number }) => c.value === "Item 2"
|
||||
);
|
||||
const item2 = (summary[0] as any).choices.find((c) => c.value === "Item 2");
|
||||
expect(item2.count).toBe(2);
|
||||
expect(item2.avgRanking).toBe(1.5);
|
||||
|
||||
// Item 3 is in position 3 twice, so avg ranking should be 3
|
||||
const item3 = (summary[0] as any).choices.find(
|
||||
(c: { value: string; count: number; avgRanking: number }) => c.value === "Item 3"
|
||||
);
|
||||
const item3 = (summary[0] as any).choices.find((c) => c.value === "Item 3");
|
||||
expect(item3.count).toBe(2);
|
||||
expect(item3.avgRanking).toBe(3);
|
||||
});
|
||||
@@ -753,23 +747,17 @@ describe("getQuestionSummary", () => {
|
||||
expect(summary[0].responseCount).toBe(1);
|
||||
|
||||
// Item 1 is in position 2, so avg ranking should be 2
|
||||
const item1 = (summary[0] as any).choices.find(
|
||||
(c: { value: string; count: number; avgRanking: number }) => c.value === "Item 1"
|
||||
);
|
||||
const item1 = (summary[0] as any).choices.find((c) => c.value === "Item 1");
|
||||
expect(item1.count).toBe(1);
|
||||
expect(item1.avgRanking).toBe(2);
|
||||
|
||||
// Item 2 is in position 1, so avg ranking should be 1
|
||||
const item2 = (summary[0] as any).choices.find(
|
||||
(c: { value: string; count: number; avgRanking: number }) => c.value === "Item 2"
|
||||
);
|
||||
const item2 = (summary[0] as any).choices.find((c) => c.value === "Item 2");
|
||||
expect(item2.count).toBe(1);
|
||||
expect(item2.avgRanking).toBe(1);
|
||||
|
||||
// Item 3 is in position 3, so avg ranking should be 3
|
||||
const item3 = (summary[0] as any).choices.find(
|
||||
(c: { value: string; count: number; avgRanking: number }) => c.value === "Item 3"
|
||||
);
|
||||
const item3 = (summary[0] as any).choices.find((c) => c.value === "Item 3");
|
||||
expect(item3.count).toBe(1);
|
||||
expect(item3.avgRanking).toBe(3);
|
||||
});
|
||||
@@ -842,12 +830,10 @@ describe("getQuestionSummary", () => {
|
||||
expect((summary[0] as any).choices).toHaveLength(3);
|
||||
|
||||
// All items should have count 0 and avgRanking 0
|
||||
(summary[0] as any).choices.forEach(
|
||||
(choice: { value?: string; count: number; avgRanking?: number; percentage?: number }) => {
|
||||
expect(choice.count).toBe(0);
|
||||
expect(choice.avgRanking).toBe(0);
|
||||
}
|
||||
);
|
||||
(summary[0] as any).choices.forEach((choice) => {
|
||||
expect(choice.count).toBe(0);
|
||||
expect(choice.avgRanking).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
test("getQuestionSummary handles ranking question with non-array answers", async () => {
|
||||
@@ -908,12 +894,10 @@ describe("getQuestionSummary", () => {
|
||||
expect((summary[0] as any).choices).toHaveLength(3);
|
||||
|
||||
// All items should have count 0 and avgRanking 0 since we had no valid ranking data
|
||||
(summary[0] as any).choices.forEach(
|
||||
(choice: { value?: string; count: number; avgRanking?: number; percentage?: number }) => {
|
||||
expect(choice.count).toBe(0);
|
||||
expect(choice.avgRanking).toBe(0);
|
||||
}
|
||||
);
|
||||
(summary[0] as any).choices.forEach((choice) => {
|
||||
expect(choice.count).toBe(0);
|
||||
expect(choice.avgRanking).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
test("getQuestionSummary handles ranking question with values not in choices", async () => {
|
||||
@@ -974,23 +958,17 @@ describe("getQuestionSummary", () => {
|
||||
expect((summary[0] as any).choices).toHaveLength(3);
|
||||
|
||||
// Item 1 is in position 1, so avg ranking should be 1
|
||||
const item1 = (summary[0] as any).choices.find(
|
||||
(c: { value: string; count: number; avgRanking: number }) => c.value === "Item 1"
|
||||
);
|
||||
const item1 = (summary[0] as any).choices.find((c) => c.value === "Item 1");
|
||||
expect(item1.count).toBe(1);
|
||||
expect(item1.avgRanking).toBe(1);
|
||||
|
||||
// Item 2 was not ranked, so should have count 0 and avgRanking 0
|
||||
const item2 = (summary[0] as any).choices.find(
|
||||
(c: { value: string; count: number; avgRanking: number }) => c.value === "Item 2"
|
||||
);
|
||||
const item2 = (summary[0] as any).choices.find((c) => c.value === "Item 2");
|
||||
expect(item2.count).toBe(0);
|
||||
expect(item2.avgRanking).toBe(0);
|
||||
|
||||
// Item 3 is in position 3, so avg ranking should be 3
|
||||
const item3 = (summary[0] as any).choices.find(
|
||||
(c: { value: string; count: number; avgRanking: number }) => c.value === "Item 3"
|
||||
);
|
||||
const item3 = (summary[0] as any).choices.find((c) => c.value === "Item 3");
|
||||
expect(item3.count).toBe(1);
|
||||
expect(item3.avgRanking).toBe(3);
|
||||
});
|
||||
@@ -1008,11 +986,7 @@ describe("getSurveySummary", () => {
|
||||
// Since getSurveySummary calls getResponsesForSummary internally, we'll mock prisma.response.findMany
|
||||
// which is used by the actual implementation of getResponsesForSummary.
|
||||
vi.mocked(prisma.response.findMany).mockResolvedValue(
|
||||
mockResponses.map((r: Record<string, unknown>) => ({
|
||||
...r,
|
||||
contactId: null,
|
||||
personAttributes: {},
|
||||
})) as any
|
||||
mockResponses.map((r) => ({ ...r, contactId: null, personAttributes: {} })) as any
|
||||
);
|
||||
vi.mocked(getDisplayCountBySurveyId).mockResolvedValue(10);
|
||||
|
||||
@@ -1046,8 +1020,8 @@ describe("getSurveySummary", () => {
|
||||
test("handles filterCriteria", async () => {
|
||||
const filterCriteria: TResponseFilterCriteria = { finished: true };
|
||||
const finishedResponses = mockResponses
|
||||
.filter((r: Record<string, unknown>) => r.finished)
|
||||
.map((r: Record<string, unknown>) => ({ ...r, contactId: null, personAttributes: {} }));
|
||||
.filter((r) => r.finished)
|
||||
.map((r) => ({ ...r, contactId: null, personAttributes: {} }));
|
||||
vi.mocked(prisma.response.findMany).mockResolvedValue(finishedResponses as any);
|
||||
|
||||
await getSurveySummary(mockSurveyId, filterCriteria);
|
||||
@@ -1069,11 +1043,7 @@ describe("getResponsesForSummary", () => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(getSurvey).mockResolvedValue(mockBaseSurvey);
|
||||
vi.mocked(prisma.response.findMany).mockResolvedValue(
|
||||
mockResponses.map((r: Record<string, unknown>) => ({
|
||||
...r,
|
||||
contactId: null,
|
||||
personAttributes: {},
|
||||
})) as any
|
||||
mockResponses.map((r) => ({ ...r, contactId: null, personAttributes: {} })) as any
|
||||
);
|
||||
// React cache is already mocked globally - no need to mock it again
|
||||
});
|
||||
@@ -1872,63 +1842,23 @@ describe("Matrix question type tests", () => {
|
||||
expect(summary[0].responseCount).toBe(2);
|
||||
|
||||
// Verify Speed row
|
||||
const speedRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Speed"
|
||||
);
|
||||
const speedRow = summary[0].data.find((row) => row.rowLabel === "Speed");
|
||||
expect(speedRow.totalResponsesForRow).toBe(2);
|
||||
expect(speedRow.columnPercentages).toHaveLength(4); // 4 columns
|
||||
expect(
|
||||
speedRow.columnPercentages.find((col: { column: string; percentage: number }) => col.column === "Good")
|
||||
.percentage
|
||||
).toBe(50);
|
||||
expect(
|
||||
speedRow.columnPercentages.find(
|
||||
(col: { column: string; percentage: number }) => col.column === "Average"
|
||||
).percentage
|
||||
).toBe(50);
|
||||
expect(speedRow.columnPercentages.find((col) => col.column === "Good").percentage).toBe(50);
|
||||
expect(speedRow.columnPercentages.find((col) => col.column === "Average").percentage).toBe(50);
|
||||
|
||||
// Verify Quality row
|
||||
const qualityRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Quality"
|
||||
);
|
||||
const qualityRow = summary[0].data.find((row) => row.rowLabel === "Quality");
|
||||
expect(qualityRow.totalResponsesForRow).toBe(2);
|
||||
expect(
|
||||
qualityRow.columnPercentages.find(
|
||||
(col: { column: string; percentage: number }) => col.column === "Excellent"
|
||||
).percentage
|
||||
).toBe(50);
|
||||
expect(
|
||||
qualityRow.columnPercentages.find(
|
||||
(col: { column: string; percentage: number }) => col.column === "Good"
|
||||
).percentage
|
||||
).toBe(50);
|
||||
expect(qualityRow.columnPercentages.find((col) => col.column === "Excellent").percentage).toBe(50);
|
||||
expect(qualityRow.columnPercentages.find((col) => col.column === "Good").percentage).toBe(50);
|
||||
|
||||
// Verify Price row
|
||||
const priceRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Price"
|
||||
);
|
||||
const priceRow = summary[0].data.find((row) => row.rowLabel === "Price");
|
||||
expect(priceRow.totalResponsesForRow).toBe(2);
|
||||
expect(
|
||||
priceRow.columnPercentages.find((col: { column: string; percentage: number }) => col.column === "Poor")
|
||||
.percentage
|
||||
).toBe(50);
|
||||
expect(
|
||||
priceRow.columnPercentages.find(
|
||||
(col: { column: string; percentage: number }) => col.column === "Average"
|
||||
).percentage
|
||||
).toBe(50);
|
||||
expect(priceRow.columnPercentages.find((col) => col.column === "Poor").percentage).toBe(50);
|
||||
expect(priceRow.columnPercentages.find((col) => col.column === "Average").percentage).toBe(50);
|
||||
});
|
||||
|
||||
test("getQuestionSummary correctly processes Matrix question with non-default language responses", async () => {
|
||||
@@ -2019,48 +1949,19 @@ describe("Matrix question type tests", () => {
|
||||
expect(summary[0].responseCount).toBe(1);
|
||||
|
||||
// Verify Speed row with localized values mapped to default language
|
||||
const speedRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Speed"
|
||||
);
|
||||
const speedRow = summary[0].data.find((row) => row.rowLabel === "Speed");
|
||||
expect(speedRow.totalResponsesForRow).toBe(1);
|
||||
expect(
|
||||
speedRow.columnPercentages.find((col: { column: string; percentage: number }) => col.column === "Good")
|
||||
.percentage
|
||||
).toBe(100);
|
||||
expect(speedRow.columnPercentages.find((col) => col.column === "Good").percentage).toBe(100);
|
||||
|
||||
// Verify Quality row
|
||||
const qualityRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Quality"
|
||||
);
|
||||
const qualityRow = summary[0].data.find((row) => row.rowLabel === "Quality");
|
||||
expect(qualityRow.totalResponsesForRow).toBe(1);
|
||||
expect(
|
||||
qualityRow.columnPercentages.find(
|
||||
(col: { column: string; percentage: number }) => col.column === "Excellent"
|
||||
).percentage
|
||||
).toBe(100);
|
||||
expect(qualityRow.columnPercentages.find((col) => col.column === "Excellent").percentage).toBe(100);
|
||||
|
||||
// Verify Price row
|
||||
const priceRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Price"
|
||||
);
|
||||
const priceRow = summary[0].data.find((row) => row.rowLabel === "Price");
|
||||
expect(priceRow.totalResponsesForRow).toBe(1);
|
||||
expect(
|
||||
priceRow.columnPercentages.find(
|
||||
(col: { column: string; percentage: number }) => col.column === "Average"
|
||||
).percentage
|
||||
).toBe(100);
|
||||
expect(priceRow.columnPercentages.find((col) => col.column === "Average").percentage).toBe(100);
|
||||
});
|
||||
|
||||
test("getQuestionSummary handles missing or invalid data for Matrix questions", async () => {
|
||||
@@ -2154,18 +2055,12 @@ describe("Matrix question type tests", () => {
|
||||
expect(summary[0].responseCount).toBe(3); // Count is 3 because responses 2, 3, and 4 have the "matrix-q1" property
|
||||
|
||||
// All rows should have zero responses for all columns
|
||||
summary[0].data.forEach(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => {
|
||||
expect(row.totalResponsesForRow).toBe(0);
|
||||
row.columnPercentages.forEach((col: { column: string; percentage: number }) => {
|
||||
expect(col.percentage).toBe(0);
|
||||
});
|
||||
}
|
||||
);
|
||||
summary[0].data.forEach((row) => {
|
||||
expect(row.totalResponsesForRow).toBe(0);
|
||||
row.columnPercentages.forEach((col) => {
|
||||
expect(col.percentage).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("getQuestionSummary handles partial and incomplete matrix responses", async () => {
|
||||
@@ -2252,59 +2147,22 @@ describe("Matrix question type tests", () => {
|
||||
expect(summary[0].responseCount).toBe(2);
|
||||
|
||||
// Verify Speed row - both responses provided data
|
||||
const speedRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Speed"
|
||||
);
|
||||
const speedRow = summary[0].data.find((row) => row.rowLabel === "Speed");
|
||||
expect(speedRow.totalResponsesForRow).toBe(2);
|
||||
expect(
|
||||
speedRow.columnPercentages.find((col: { column: string; percentage: number }) => col.column === "Good")
|
||||
.percentage
|
||||
).toBe(50);
|
||||
expect(
|
||||
speedRow.columnPercentages.find(
|
||||
(col: { column: string; percentage: number }) => col.column === "Average"
|
||||
).percentage
|
||||
).toBe(50);
|
||||
expect(speedRow.columnPercentages.find((col) => col.column === "Good").percentage).toBe(50);
|
||||
expect(speedRow.columnPercentages.find((col) => col.column === "Average").percentage).toBe(50);
|
||||
|
||||
// Verify Quality row - only one response provided data
|
||||
const qualityRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Quality"
|
||||
);
|
||||
const qualityRow = summary[0].data.find((row) => row.rowLabel === "Quality");
|
||||
expect(qualityRow.totalResponsesForRow).toBe(1);
|
||||
expect(
|
||||
qualityRow.columnPercentages.find(
|
||||
(col: { column: string; percentage: number }) => col.column === "Good"
|
||||
).percentage
|
||||
).toBe(100);
|
||||
expect(qualityRow.columnPercentages.find((col) => col.column === "Good").percentage).toBe(100);
|
||||
|
||||
// Verify Price row - both responses provided data
|
||||
const priceRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Price"
|
||||
);
|
||||
const priceRow = summary[0].data.find((row) => row.rowLabel === "Price");
|
||||
expect(priceRow.totalResponsesForRow).toBe(2);
|
||||
|
||||
// ExtraRow should not appear in the summary
|
||||
expect(
|
||||
summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "ExtraRow"
|
||||
)
|
||||
).toBeUndefined();
|
||||
expect(summary[0].data.find((row) => row.rowLabel === "ExtraRow")).toBeUndefined();
|
||||
});
|
||||
|
||||
test("getQuestionSummary handles zero responses for Matrix question correctly", async () => {
|
||||
@@ -2363,18 +2221,12 @@ describe("Matrix question type tests", () => {
|
||||
// All rows should have proper structure but zero counts
|
||||
expect(summary[0].data).toHaveLength(2); // 2 rows
|
||||
|
||||
summary[0].data.forEach(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => {
|
||||
expect(row.columnPercentages).toHaveLength(2); // 2 columns
|
||||
expect(row.totalResponsesForRow).toBe(0);
|
||||
expect(row.columnPercentages[0].percentage).toBe(0);
|
||||
expect(row.columnPercentages[1].percentage).toBe(0);
|
||||
}
|
||||
);
|
||||
summary[0].data.forEach((row) => {
|
||||
expect(row.columnPercentages).toHaveLength(2); // 2 columns
|
||||
expect(row.totalResponsesForRow).toBe(0);
|
||||
expect(row.columnPercentages[0].percentage).toBe(0);
|
||||
expect(row.columnPercentages[1].percentage).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
test("getQuestionSummary handles Matrix question with mixed valid and invalid column values", async () => {
|
||||
@@ -2444,46 +2296,21 @@ describe("Matrix question type tests", () => {
|
||||
expect(summary[0].responseCount).toBe(1);
|
||||
|
||||
// Speed row should have a valid response
|
||||
const speedRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Speed"
|
||||
);
|
||||
const speedRow = summary[0].data.find((row) => row.rowLabel === "Speed");
|
||||
expect(speedRow.totalResponsesForRow).toBe(1);
|
||||
expect(
|
||||
speedRow.columnPercentages.find((col: { column: string; percentage: number }) => col.column === "Good")
|
||||
.percentage
|
||||
).toBe(100);
|
||||
expect(speedRow.columnPercentages.find((col) => col.column === "Good").percentage).toBe(100);
|
||||
|
||||
// Quality row should have no valid responses
|
||||
const qualityRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Quality"
|
||||
);
|
||||
const qualityRow = summary[0].data.find((row) => row.rowLabel === "Quality");
|
||||
expect(qualityRow.totalResponsesForRow).toBe(0);
|
||||
qualityRow.columnPercentages.forEach((col: { column: string; percentage: number }) => {
|
||||
qualityRow.columnPercentages.forEach((col) => {
|
||||
expect(col.percentage).toBe(0);
|
||||
});
|
||||
|
||||
// Price row should have a valid response
|
||||
const priceRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Price"
|
||||
);
|
||||
const priceRow = summary[0].data.find((row) => row.rowLabel === "Price");
|
||||
expect(priceRow.totalResponsesForRow).toBe(1);
|
||||
expect(
|
||||
priceRow.columnPercentages.find(
|
||||
(col: { column: string; percentage: number }) => col.column === "Average"
|
||||
).percentage
|
||||
).toBe(100);
|
||||
expect(priceRow.columnPercentages.find((col) => col.column === "Average").percentage).toBe(100);
|
||||
});
|
||||
|
||||
test("getQuestionSummary handles Matrix question with invalid row labels", async () => {
|
||||
@@ -2554,48 +2381,17 @@ describe("Matrix question type tests", () => {
|
||||
expect(summary[0].data).toHaveLength(2); // 2 rows
|
||||
|
||||
// Speed row should have a valid response
|
||||
const speedRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Speed"
|
||||
);
|
||||
const speedRow = summary[0].data.find((row) => row.rowLabel === "Speed");
|
||||
expect(speedRow.totalResponsesForRow).toBe(1);
|
||||
expect(
|
||||
speedRow.columnPercentages.find((col: { column: string; percentage: number }) => col.column === "Good")
|
||||
.percentage
|
||||
).toBe(100);
|
||||
expect(speedRow.columnPercentages.find((col) => col.column === "Good").percentage).toBe(100);
|
||||
|
||||
// Quality row should have no responses
|
||||
const qualityRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Quality"
|
||||
);
|
||||
const qualityRow = summary[0].data.find((row) => row.rowLabel === "Quality");
|
||||
expect(qualityRow.totalResponsesForRow).toBe(0);
|
||||
|
||||
// Invalid rows should not appear in the summary
|
||||
expect(
|
||||
summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "InvalidRow"
|
||||
)
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "AnotherInvalidRow"
|
||||
)
|
||||
).toBeUndefined();
|
||||
expect(summary[0].data.find((row) => row.rowLabel === "InvalidRow")).toBeUndefined();
|
||||
expect(summary[0].data.find((row) => row.rowLabel === "AnotherInvalidRow")).toBeUndefined();
|
||||
});
|
||||
|
||||
test("getQuestionSummary handles Matrix question with mixed language responses", async () => {
|
||||
@@ -2697,27 +2493,12 @@ describe("Matrix question type tests", () => {
|
||||
expect(summary[0].responseCount).toBe(2);
|
||||
|
||||
// Speed row should have both responses
|
||||
const speedRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Speed"
|
||||
);
|
||||
const speedRow = summary[0].data.find((row) => row.rowLabel === "Speed");
|
||||
expect(speedRow.totalResponsesForRow).toBe(2);
|
||||
expect(
|
||||
speedRow.columnPercentages.find((col: { column: string; percentage: number }) => col.column === "Good")
|
||||
.percentage
|
||||
).toBe(100);
|
||||
expect(speedRow.columnPercentages.find((col) => col.column === "Good").percentage).toBe(100);
|
||||
|
||||
// Quality row should have no responses
|
||||
const qualityRow = summary[0].data.find(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => row.rowLabel === "Quality"
|
||||
);
|
||||
const qualityRow = summary[0].data.find((row) => row.rowLabel === "Quality");
|
||||
expect(qualityRow.totalResponsesForRow).toBe(0);
|
||||
});
|
||||
|
||||
@@ -2776,18 +2557,12 @@ describe("Matrix question type tests", () => {
|
||||
expect(summary[0].responseCount).toBe(0); // Counts as response even with null data
|
||||
|
||||
// Both rows should have zero responses
|
||||
summary[0].data.forEach(
|
||||
(row: {
|
||||
rowLabel: string;
|
||||
totalResponsesForRow: number;
|
||||
columnPercentages: { column: string; percentage: number }[];
|
||||
}) => {
|
||||
expect(row.totalResponsesForRow).toBe(0);
|
||||
row.columnPercentages.forEach((col: { column: string; percentage: number }) => {
|
||||
expect(col.percentage).toBe(0);
|
||||
});
|
||||
}
|
||||
);
|
||||
summary[0].data.forEach((row) => {
|
||||
expect(row.totalResponsesForRow).toBe(0);
|
||||
row.columnPercentages.forEach((col) => {
|
||||
expect(col.percentage).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3219,33 +2994,23 @@ describe("Rating question type tests", () => {
|
||||
expect(summary[0].average).toBe(4.25);
|
||||
|
||||
// Verify each rating option count and percentage
|
||||
const rating5 = summary[0].choices.find(
|
||||
(c: { rating: number; count: number; percentage: number }) => c.rating === 5
|
||||
);
|
||||
const rating5 = summary[0].choices.find((c) => c.rating === 5);
|
||||
expect(rating5.count).toBe(2);
|
||||
expect(rating5.percentage).toBe(50); // 2/4 * 100
|
||||
|
||||
const rating4 = summary[0].choices.find(
|
||||
(c: { rating: number; count: number; percentage: number }) => c.rating === 4
|
||||
);
|
||||
const rating4 = summary[0].choices.find((c) => c.rating === 4);
|
||||
expect(rating4.count).toBe(1);
|
||||
expect(rating4.percentage).toBe(25); // 1/4 * 100
|
||||
|
||||
const rating3 = summary[0].choices.find(
|
||||
(c: { rating: number; count: number; percentage: number }) => c.rating === 3
|
||||
);
|
||||
const rating3 = summary[0].choices.find((c) => c.rating === 3);
|
||||
expect(rating3.count).toBe(1);
|
||||
expect(rating3.percentage).toBe(25); // 1/4 * 100
|
||||
|
||||
const rating2 = summary[0].choices.find(
|
||||
(c: { rating: number; count: number; percentage: number }) => c.rating === 2
|
||||
);
|
||||
const rating2 = summary[0].choices.find((c) => c.rating === 2);
|
||||
expect(rating2.count).toBe(0);
|
||||
expect(rating2.percentage).toBe(0);
|
||||
|
||||
const rating1 = summary[0].choices.find(
|
||||
(c: { rating: number; count: number; percentage: number }) => c.rating === 1
|
||||
);
|
||||
const rating1 = summary[0].choices.find((c) => c.rating === 1);
|
||||
expect(rating1.count).toBe(0);
|
||||
expect(rating1.percentage).toBe(0);
|
||||
|
||||
@@ -3389,12 +3154,10 @@ describe("Rating question type tests", () => {
|
||||
expect(summary[0].average).toBe(0);
|
||||
|
||||
// Verify all ratings have 0 count and percentage
|
||||
summary[0].choices.forEach(
|
||||
(choice: { value?: string; count: number; avgRanking?: number; percentage?: number }) => {
|
||||
expect(choice.count).toBe(0);
|
||||
expect(choice.percentage).toBe(0);
|
||||
}
|
||||
);
|
||||
summary[0].choices.forEach((choice) => {
|
||||
expect(choice.count).toBe(0);
|
||||
expect(choice.percentage).toBe(0);
|
||||
});
|
||||
|
||||
// Verify dismissed is 0
|
||||
expect(summary[0].dismissed.count).toBe(0);
|
||||
@@ -3469,21 +3232,15 @@ describe("PictureSelection question type tests", () => {
|
||||
expect(summary[0].selectionCount).toBe(3); // Total selections: img1, img2, img3
|
||||
|
||||
// Check individual choice counts
|
||||
const img1 = summary[0].choices.find(
|
||||
(c: { id: string; count: number; percentage: number }) => c.id === "img1"
|
||||
);
|
||||
const img1 = summary[0].choices.find((c) => c.id === "img1");
|
||||
expect(img1.count).toBe(1);
|
||||
expect(img1.percentage).toBe(50);
|
||||
|
||||
const img2 = summary[0].choices.find(
|
||||
(c: { id: string; count: number; percentage: number }) => c.id === "img2"
|
||||
);
|
||||
const img2 = summary[0].choices.find((c) => c.id === "img2");
|
||||
expect(img2.count).toBe(1);
|
||||
expect(img2.percentage).toBe(50);
|
||||
|
||||
const img3 = summary[0].choices.find(
|
||||
(c: { id: string; count: number; percentage: number }) => c.id === "img3"
|
||||
);
|
||||
const img3 = summary[0].choices.find((c) => c.id === "img3");
|
||||
expect(img3.count).toBe(1);
|
||||
expect(img3.percentage).toBe(50);
|
||||
});
|
||||
@@ -3554,12 +3311,10 @@ describe("PictureSelection question type tests", () => {
|
||||
expect(summary[0].selectionCount).toBe(0);
|
||||
|
||||
// All choices should have zero count
|
||||
summary[0].choices.forEach(
|
||||
(choice: { value?: string; count: number; avgRanking?: number; percentage?: number }) => {
|
||||
expect(choice.count).toBe(0);
|
||||
expect(choice.percentage).toBe(0);
|
||||
}
|
||||
);
|
||||
summary[0].choices.forEach((choice) => {
|
||||
expect(choice.count).toBe(0);
|
||||
expect(choice.percentage).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
test("getQuestionSummary handles PictureSelection with invalid choice ids", async () => {
|
||||
@@ -3618,23 +3373,17 @@ describe("PictureSelection question type tests", () => {
|
||||
expect(summary[0].selectionCount).toBe(2); // Total selections including invalid one
|
||||
|
||||
// img1 should be counted
|
||||
const img1 = summary[0].choices.find(
|
||||
(c: { id: string; count: number; percentage: number }) => c.id === "img1"
|
||||
);
|
||||
const img1 = summary[0].choices.find((c) => c.id === "img1");
|
||||
expect(img1.count).toBe(1);
|
||||
expect(img1.percentage).toBe(100);
|
||||
|
||||
// img2 should not be counted
|
||||
const img2 = summary[0].choices.find(
|
||||
(c: { id: string; count: number; percentage: number }) => c.id === "img2"
|
||||
);
|
||||
const img2 = summary[0].choices.find((c) => c.id === "img2");
|
||||
expect(img2.count).toBe(0);
|
||||
expect(img2.percentage).toBe(0);
|
||||
|
||||
// Invalid ID should not appear in choices
|
||||
expect(
|
||||
summary[0].choices.find((c: { id: string; count: number; percentage: number }) => c.id === "invalid-id")
|
||||
).toBeUndefined();
|
||||
expect(summary[0].choices.find((c) => c.id === "invalid-id")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -14,7 +14,11 @@ import {
|
||||
TResponseVariables,
|
||||
ZResponseFilterCriteria,
|
||||
} from "@formbricks/types/responses";
|
||||
import { TSurveyElement, TSurveyElementTypeEnum } from "@formbricks/types/surveys/elements";
|
||||
import {
|
||||
TSurveyElement,
|
||||
TSurveyElementChoice,
|
||||
TSurveyElementTypeEnum,
|
||||
} from "@formbricks/types/surveys/elements";
|
||||
import {
|
||||
TSurvey,
|
||||
TSurveyElementSummaryAddress,
|
||||
@@ -289,10 +293,7 @@ const checkForI18n = (
|
||||
) => {
|
||||
const element = elements.find((element) => element.id === id);
|
||||
|
||||
if (
|
||||
element?.type === TSurveyElementTypeEnum.MultipleChoiceMulti ||
|
||||
element?.type === TSurveyElementTypeEnum.Ranking
|
||||
) {
|
||||
if (element?.type === "multipleChoiceMulti" || element?.type === "ranking") {
|
||||
// Initialize an array to hold the choice values
|
||||
let choiceValues = [] as string[];
|
||||
|
||||
@@ -317,9 +318,13 @@ const checkForI18n = (
|
||||
}
|
||||
|
||||
// Return the localized value of the choice fo multiSelect single element
|
||||
if (element?.type === TSurveyElementTypeEnum.MultipleChoiceSingle) {
|
||||
const choice = element.choices?.find((choice) => choice.label[languageCode] === responseData[id]);
|
||||
return choice ? getLocalizedValue(choice.label, "default") || responseData[id] : responseData[id];
|
||||
if (element && "choices" in element) {
|
||||
const choice = element.choices?.find(
|
||||
(choice: TSurveyElementChoice) => choice.label?.[languageCode] === responseData[id]
|
||||
);
|
||||
return choice && "label" in choice
|
||||
? getLocalizedValue(choice.label, "default") || responseData[id]
|
||||
: responseData[id];
|
||||
}
|
||||
|
||||
return responseData[id];
|
||||
@@ -827,19 +832,13 @@ export const getElementSummary = async (
|
||||
let totalResponseCount = 0;
|
||||
|
||||
// Initialize count object
|
||||
const countMap: Record<string, Record<string, number>> = rows.reduce(
|
||||
(acc: Record<string, Record<string, number>>, row) => {
|
||||
acc[row] = columns.reduce(
|
||||
(colAcc: Record<string, number>, col) => {
|
||||
colAcc[col] = 0;
|
||||
return colAcc;
|
||||
},
|
||||
{} as Record<string, number>
|
||||
);
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, Record<string, number>>
|
||||
);
|
||||
const countMap: Record<string, string> = rows.reduce((acc, row) => {
|
||||
acc[row] = columns.reduce((colAcc, col) => {
|
||||
colAcc[col] = 0;
|
||||
return colAcc;
|
||||
}, {});
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
responses.forEach((response) => {
|
||||
const selectedResponses = response.data[element.id] as Record<string, string>;
|
||||
|
||||
@@ -40,11 +40,10 @@ const SurveyPage = async (props: { params: Promise<{ environmentId: string; surv
|
||||
if (!user) {
|
||||
throw new Error(t("common.user_not_found"));
|
||||
}
|
||||
const organizationId = await getOrganizationIdFromEnvironmentId(environment.id);
|
||||
|
||||
const isContactsEnabled = await getIsContactsEnabled(organizationId);
|
||||
const isContactsEnabled = await getIsContactsEnabled();
|
||||
const segments = isContactsEnabled ? await getSegments(environment.id) : [];
|
||||
|
||||
const organizationId = await getOrganizationIdFromEnvironmentId(environment.id);
|
||||
if (!organizationId) {
|
||||
throw new Error(t("common.organization_not_found"));
|
||||
}
|
||||
@@ -52,7 +51,7 @@ const SurveyPage = async (props: { params: Promise<{ environmentId: string; surv
|
||||
if (!organizationBilling) {
|
||||
throw new Error(t("common.organization_not_found"));
|
||||
}
|
||||
const isQuotasAllowed = await getIsQuotasEnabled(organizationId);
|
||||
const isQuotasAllowed = await getIsQuotasEnabled(organizationBilling.plan);
|
||||
|
||||
// Fetch initial survey summary data on the server to prevent duplicate API calls during hydration
|
||||
const initialSurveySummary = await getSurveySummary(surveyId);
|
||||
|
||||
@@ -4,16 +4,18 @@ import { z } from "zod";
|
||||
import { ZId } from "@formbricks/types/common";
|
||||
import { OperationNotAllowedError, ResourceNotFoundError } from "@formbricks/types/errors";
|
||||
import { ZResponseFilterCriteria } from "@formbricks/types/responses";
|
||||
import { ZSurvey } from "@formbricks/types/surveys/types";
|
||||
import { TSurvey, ZSurvey } from "@formbricks/types/surveys/types";
|
||||
import { getOrganization } from "@/lib/organization/service";
|
||||
import { getResponseDownloadFile, getResponseFilteringValues } from "@/lib/response/service";
|
||||
import { getSurvey, updateSurvey } from "@/lib/survey/service";
|
||||
import { getTagsByEnvironmentId } from "@/lib/tag/service";
|
||||
import { authenticatedActionClient } from "@/lib/utils/action-client";
|
||||
import { checkAuthorizationUpdated } from "@/lib/utils/action-client/action-client-middleware";
|
||||
import { AuthenticatedActionClientCtx } from "@/lib/utils/action-client/types/context";
|
||||
import { getOrganizationIdFromSurveyId, getProjectIdFromSurveyId } from "@/lib/utils/helper";
|
||||
import { withAuditLogging } from "@/modules/ee/audit-logs/lib/handler";
|
||||
import { getIsQuotasEnabled } from "@/modules/ee/license-check/lib/utils";
|
||||
import { checkMultiLanguagePermission } from "@/modules/ee/multi-language-surveys/lib/actions";
|
||||
import { getQuotas } from "@/modules/ee/quotas/lib/quotas";
|
||||
import { getSurveyFollowUpsPermission } from "@/modules/survey/follow-ups/lib/utils";
|
||||
import { checkSpamProtectionPermission } from "@/modules/survey/lib/permission";
|
||||
@@ -87,7 +89,7 @@ export const getSurveyFilterDataAction = authenticatedActionClient
|
||||
throw new ResourceNotFoundError("Organization", organizationId);
|
||||
}
|
||||
|
||||
const isQuotasAllowed = await getIsQuotasEnabled(organizationId);
|
||||
const isQuotasAllowed = await getIsQuotasEnabled(organizationBilling.plan);
|
||||
|
||||
const [tags, { contactAttributes: attributes, meta, hiddenFields }, quotas = []] = await Promise.all([
|
||||
getTagsByEnvironmentId(survey.environmentId),
|
||||
@@ -113,52 +115,60 @@ const checkSurveyFollowUpsPermission = async (organizationId: string): Promise<v
|
||||
throw new ResourceNotFoundError("Organization not found", organizationId);
|
||||
}
|
||||
|
||||
const isSurveyFollowUpsEnabled = await getSurveyFollowUpsPermission(organizationId);
|
||||
const isSurveyFollowUpsEnabled = await getSurveyFollowUpsPermission(organization.billing.plan);
|
||||
if (!isSurveyFollowUpsEnabled) {
|
||||
throw new OperationNotAllowedError("Survey follow ups are not enabled for this organization");
|
||||
}
|
||||
};
|
||||
|
||||
export const updateSurveyAction = authenticatedActionClient.inputSchema(ZSurvey).action(
|
||||
withAuditLogging("updated", "survey", async ({ ctx, parsedInput }) => {
|
||||
const organizationId = await getOrganizationIdFromSurveyId(parsedInput.id);
|
||||
await checkAuthorizationUpdated({
|
||||
userId: ctx.user?.id ?? "",
|
||||
organizationId,
|
||||
access: [
|
||||
{
|
||||
type: "organization",
|
||||
roles: ["owner", "manager"],
|
||||
},
|
||||
{
|
||||
type: "projectTeam",
|
||||
projectId: await getProjectIdFromSurveyId(parsedInput.id),
|
||||
minPermission: "readWrite",
|
||||
},
|
||||
],
|
||||
});
|
||||
withAuditLogging(
|
||||
"updated",
|
||||
"survey",
|
||||
async ({ ctx, parsedInput }: { ctx: AuthenticatedActionClientCtx; parsedInput: TSurvey }) => {
|
||||
const organizationId = await getOrganizationIdFromSurveyId(parsedInput.id);
|
||||
await checkAuthorizationUpdated({
|
||||
userId: ctx.user?.id ?? "",
|
||||
organizationId,
|
||||
access: [
|
||||
{
|
||||
type: "organization",
|
||||
roles: ["owner", "manager"],
|
||||
},
|
||||
{
|
||||
type: "projectTeam",
|
||||
projectId: await getProjectIdFromSurveyId(parsedInput.id),
|
||||
minPermission: "readWrite",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const { followUps } = parsedInput;
|
||||
const { followUps } = parsedInput;
|
||||
|
||||
const oldSurvey = await getSurvey(parsedInput.id);
|
||||
const oldSurvey = await getSurvey(parsedInput.id);
|
||||
|
||||
if (parsedInput.recaptcha?.enabled) {
|
||||
await checkSpamProtectionPermission(organizationId);
|
||||
if (parsedInput.recaptcha?.enabled) {
|
||||
await checkSpamProtectionPermission(organizationId);
|
||||
}
|
||||
|
||||
if (followUps?.length) {
|
||||
await checkSurveyFollowUpsPermission(organizationId);
|
||||
}
|
||||
|
||||
if (parsedInput.languages?.length) {
|
||||
await checkMultiLanguagePermission(organizationId);
|
||||
}
|
||||
|
||||
// Context for audit log
|
||||
ctx.auditLoggingCtx.surveyId = parsedInput.id;
|
||||
ctx.auditLoggingCtx.organizationId = organizationId;
|
||||
ctx.auditLoggingCtx.oldObject = oldSurvey;
|
||||
|
||||
const newSurvey = await updateSurvey(parsedInput);
|
||||
|
||||
ctx.auditLoggingCtx.newObject = newSurvey;
|
||||
|
||||
return newSurvey;
|
||||
}
|
||||
|
||||
if (followUps?.length) {
|
||||
await checkSurveyFollowUpsPermission(organizationId);
|
||||
}
|
||||
|
||||
// Context for audit log
|
||||
ctx.auditLoggingCtx.surveyId = parsedInput.id;
|
||||
ctx.auditLoggingCtx.organizationId = organizationId;
|
||||
ctx.auditLoggingCtx.oldObject = oldSurvey;
|
||||
|
||||
const newSurvey = await updateSurvey(parsedInput);
|
||||
|
||||
ctx.auditLoggingCtx.newObject = newSurvey;
|
||||
|
||||
return newSurvey;
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
@@ -164,12 +164,12 @@ export const CustomFilter = ({ survey }: CustomFilterProps) => {
|
||||
|
||||
const datePickerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const extractMetadataKeys = useCallback((obj: Record<string, unknown>, parentKey = "") => {
|
||||
const extractMetadataKeys = useCallback((obj, parentKey = "") => {
|
||||
let keys: string[] = [];
|
||||
|
||||
for (let key in obj) {
|
||||
if (typeof obj[key] === "object" && obj[key] !== null) {
|
||||
keys = keys.concat(extractMetadataKeys(obj[key] as Record<string, unknown>, parentKey + key + " - "));
|
||||
keys = keys.concat(extractMetadataKeys(obj[key], parentKey + key + " - "));
|
||||
} else {
|
||||
keys.push(parentKey + key);
|
||||
}
|
||||
|
||||
@@ -113,9 +113,7 @@ const elementIcons = {
|
||||
};
|
||||
|
||||
const getIcon = (type: string) => {
|
||||
const IconComponent = (elementIcons as Record<string, (typeof elementIcons)[keyof typeof elementIcons]>)[
|
||||
type
|
||||
];
|
||||
const IconComponent = elementIcons[type];
|
||||
return IconComponent ? <IconComponent className="h-5 w-5" strokeWidth={1.5} /> : null;
|
||||
};
|
||||
|
||||
|
||||
@@ -198,7 +198,7 @@ export const ResponseFilter = ({ survey }: ResponseFilterProps) => {
|
||||
};
|
||||
setFilterValue({ ...filterValue });
|
||||
};
|
||||
const handleRemoveMultiSelect = (value: string[], index: number) => {
|
||||
const handleRemoveMultiSelect = (value: string[], index) => {
|
||||
filterValue.filter[index] = {
|
||||
...filterValue.filter[index],
|
||||
filterType: {
|
||||
|
||||
@@ -34,27 +34,23 @@ export const SurveyStatusDropdown = ({
|
||||
const updateSurveyActionResponse = await updateSurveyAction({ ...survey, status });
|
||||
|
||||
if (updateSurveyActionResponse?.data) {
|
||||
const resultingStatus = updateSurveyActionResponse.data.status;
|
||||
const statusToToastMessage: Partial<Record<TSurvey["status"], string>> = {
|
||||
inProgress: t("common.survey_live"),
|
||||
paused: t("common.survey_paused"),
|
||||
completed: t("common.survey_completed"),
|
||||
};
|
||||
|
||||
const toastMessage = statusToToastMessage[resultingStatus];
|
||||
if (toastMessage) {
|
||||
toast.success(toastMessage);
|
||||
}
|
||||
|
||||
if (updateLocalSurveyStatus) {
|
||||
updateLocalSurveyStatus(resultingStatus);
|
||||
}
|
||||
toast.success(
|
||||
status === "inProgress"
|
||||
? t("common.survey_live")
|
||||
: status === "paused"
|
||||
? t("common.survey_paused")
|
||||
: status === "completed"
|
||||
? t("common.survey_completed")
|
||||
: ""
|
||||
);
|
||||
|
||||
router.refresh();
|
||||
} else {
|
||||
const errorMessage = getFormattedErrorMessage(updateSurveyActionResponse);
|
||||
toast.error(errorMessage);
|
||||
}
|
||||
|
||||
if (updateLocalSurveyStatus) updateLocalSurveyStatus(status);
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
const Page = async (props: { params: Promise<{ environmentId: string; surveyId: string }> }) => {
|
||||
const Page = async (props) => {
|
||||
const params = await props.params;
|
||||
return redirect(`/environments/${params.environmentId}/surveys/${params.surveyId}/summary`);
|
||||
};
|
||||
|
||||
@@ -110,7 +110,7 @@ export const WorkflowsPage = ({ userEmail, organizationName, billingPlan }: Work
|
||||
<div className="flex h-full flex-col items-center px-4 pt-[15vh]">
|
||||
<div className="w-full max-w-2xl space-y-8">
|
||||
<div className="space-y-3 text-center">
|
||||
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-brand-light to-brand-dark shadow-md">
|
||||
<div className="from-brand-light to-brand-dark mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br shadow-md">
|
||||
<Sparkles className="h-6 w-6 text-white" />
|
||||
</div>
|
||||
<h1 className="text-4xl font-bold tracking-tight text-slate-800">{t("workflows.heading")}</h1>
|
||||
@@ -123,7 +123,7 @@ export const WorkflowsPage = ({ userEmail, organizationName, billingPlan }: Work
|
||||
onChange={(e) => setPromptValue(e.target.value)}
|
||||
placeholder={t("workflows.placeholder")}
|
||||
rows={5}
|
||||
className="w-full resize-none rounded-xl border border-slate-200 bg-white px-5 py-4 text-base text-slate-800 shadow-sm transition-all placeholder:text-slate-400 focus:border-brand-dark focus:outline-none focus:ring-2 focus:ring-brand-light/20"
|
||||
className="focus:border-brand-dark focus:ring-brand-light/20 w-full resize-none rounded-xl border border-slate-200 bg-white px-5 py-4 text-base text-slate-800 shadow-sm transition-all placeholder:text-slate-400 focus:outline-none focus:ring-2"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
|
||||
handleGenerateWorkflow();
|
||||
@@ -156,7 +156,7 @@ export const WorkflowsPage = ({ userEmail, organizationName, billingPlan }: Work
|
||||
<div className="w-full max-w-2xl space-y-8">
|
||||
<div className="space-y-3 text-center">
|
||||
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-xl bg-slate-100">
|
||||
<Sparkles className="h-6 w-6 text-brand-dark" />
|
||||
<Sparkles className="text-brand-dark h-6 w-6" />
|
||||
</div>
|
||||
<h1 className="text-3xl font-bold tracking-tight text-slate-800">
|
||||
{t("workflows.coming_soon_title")}
|
||||
@@ -175,7 +175,7 @@ export const WorkflowsPage = ({ userEmail, organizationName, billingPlan }: Work
|
||||
onChange={(e) => setDetailsValue(e.target.value)}
|
||||
placeholder={t("workflows.follow_up_placeholder")}
|
||||
rows={4}
|
||||
className="w-full resize-none rounded-lg border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-800 transition-all placeholder:text-slate-400 focus:border-brand-dark focus:bg-white focus:outline-none focus:ring-2 focus:ring-brand-light/20"
|
||||
className="focus:border-brand-dark focus:ring-brand-light/20 w-full resize-none rounded-lg border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-800 transition-all placeholder:text-slate-400 focus:bg-white focus:outline-none focus:ring-2"
|
||||
/>
|
||||
<div className="mt-4 flex items-center justify-end gap-3">
|
||||
<Button variant="ghost" onClick={handleSkipFeedback} className="text-slate-500">
|
||||
|
||||
@@ -2,7 +2,6 @@ import { Metadata } from "next";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { IS_FORMBRICKS_CLOUD } from "@/lib/constants";
|
||||
import { getUser } from "@/lib/user/service";
|
||||
import { getCloudBillingDisplayContext } from "@/modules/ee/billing/lib/cloud-billing-display";
|
||||
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
|
||||
import { WorkflowsPage } from "./components/workflows-page";
|
||||
|
||||
@@ -28,13 +27,11 @@ const Page = async (props: { params: Promise<{ environmentId: string }> }) => {
|
||||
return redirect("/auth/login");
|
||||
}
|
||||
|
||||
const cloudBillingDisplayContext = await getCloudBillingDisplayContext(organization.id);
|
||||
|
||||
return (
|
||||
<WorkflowsPage
|
||||
userEmail={user.email}
|
||||
organizationName={organization.name}
|
||||
billingPlan={cloudBillingDisplayContext.currentCloudPlan}
|
||||
billingPlan={organization.billing.plan}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -6,6 +6,7 @@ import { ZIntegrationInput } from "@formbricks/types/integration";
|
||||
import { createOrUpdateIntegration, deleteIntegration } from "@/lib/integration/service";
|
||||
import { authenticatedActionClient } from "@/lib/utils/action-client";
|
||||
import { checkAuthorizationUpdated } from "@/lib/utils/action-client/action-client-middleware";
|
||||
import { AuthenticatedActionClientCtx } from "@/lib/utils/action-client/types/context";
|
||||
import {
|
||||
getOrganizationIdFromEnvironmentId,
|
||||
getOrganizationIdFromIntegrationId,
|
||||
@@ -22,8 +23,56 @@ const ZCreateOrUpdateIntegrationAction = z.object({
|
||||
export const createOrUpdateIntegrationAction = authenticatedActionClient
|
||||
.inputSchema(ZCreateOrUpdateIntegrationAction)
|
||||
.action(
|
||||
withAuditLogging("createdUpdated", "integration", async ({ ctx, parsedInput }) => {
|
||||
const organizationId = await getOrganizationIdFromEnvironmentId(parsedInput.environmentId);
|
||||
withAuditLogging(
|
||||
"createdUpdated",
|
||||
"integration",
|
||||
async ({
|
||||
ctx,
|
||||
parsedInput,
|
||||
}: {
|
||||
ctx: AuthenticatedActionClientCtx;
|
||||
parsedInput: Record<string, any>;
|
||||
}) => {
|
||||
const organizationId = await getOrganizationIdFromEnvironmentId(parsedInput.environmentId);
|
||||
|
||||
await checkAuthorizationUpdated({
|
||||
userId: ctx.user.id,
|
||||
organizationId,
|
||||
access: [
|
||||
{
|
||||
type: "organization",
|
||||
roles: ["owner", "manager"],
|
||||
},
|
||||
{
|
||||
type: "projectTeam",
|
||||
minPermission: "readWrite",
|
||||
projectId: await getProjectIdFromEnvironmentId(parsedInput.environmentId),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
ctx.auditLoggingCtx.organizationId = organizationId;
|
||||
const result = await createOrUpdateIntegration(
|
||||
parsedInput.environmentId,
|
||||
parsedInput.integrationData
|
||||
);
|
||||
ctx.auditLoggingCtx.integrationId = result.id;
|
||||
ctx.auditLoggingCtx.newObject = result;
|
||||
return result;
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
const ZDeleteIntegrationAction = z.object({
|
||||
integrationId: ZId,
|
||||
});
|
||||
|
||||
export const deleteIntegrationAction = authenticatedActionClient.inputSchema(ZDeleteIntegrationAction).action(
|
||||
withAuditLogging(
|
||||
"deleted",
|
||||
"integration",
|
||||
async ({ ctx, parsedInput }: { ctx: AuthenticatedActionClientCtx; parsedInput: Record<string, any> }) => {
|
||||
const organizationId = await getOrganizationIdFromIntegrationId(parsedInput.integrationId);
|
||||
|
||||
await checkAuthorizationUpdated({
|
||||
userId: ctx.user.id,
|
||||
@@ -35,48 +84,17 @@ export const createOrUpdateIntegrationAction = authenticatedActionClient
|
||||
},
|
||||
{
|
||||
type: "projectTeam",
|
||||
projectId: await getProjectIdFromIntegrationId(parsedInput.integrationId),
|
||||
minPermission: "readWrite",
|
||||
projectId: await getProjectIdFromEnvironmentId(parsedInput.environmentId),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
ctx.auditLoggingCtx.organizationId = organizationId;
|
||||
const result = await createOrUpdateIntegration(parsedInput.environmentId, parsedInput.integrationData);
|
||||
ctx.auditLoggingCtx.integrationId = result.id;
|
||||
ctx.auditLoggingCtx.newObject = result;
|
||||
ctx.auditLoggingCtx.integrationId = parsedInput.integrationId;
|
||||
const result = await deleteIntegration(parsedInput.integrationId);
|
||||
ctx.auditLoggingCtx.oldObject = result;
|
||||
return result;
|
||||
})
|
||||
);
|
||||
|
||||
const ZDeleteIntegrationAction = z.object({
|
||||
integrationId: ZId,
|
||||
});
|
||||
|
||||
export const deleteIntegrationAction = authenticatedActionClient.inputSchema(ZDeleteIntegrationAction).action(
|
||||
withAuditLogging("deleted", "integration", async ({ ctx, parsedInput }) => {
|
||||
const organizationId = await getOrganizationIdFromIntegrationId(parsedInput.integrationId);
|
||||
|
||||
await checkAuthorizationUpdated({
|
||||
userId: ctx.user.id,
|
||||
organizationId,
|
||||
access: [
|
||||
{
|
||||
type: "organization",
|
||||
roles: ["owner", "manager"],
|
||||
},
|
||||
{
|
||||
type: "projectTeam",
|
||||
projectId: await getProjectIdFromIntegrationId(parsedInput.integrationId),
|
||||
minPermission: "readWrite",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
ctx.auditLoggingCtx.organizationId = organizationId;
|
||||
ctx.auditLoggingCtx.integrationId = parsedInput.integrationId;
|
||||
const result = await deleteIntegration(parsedInput.integrationId);
|
||||
ctx.auditLoggingCtx.oldObject = result;
|
||||
return result;
|
||||
})
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
@@ -284,7 +284,7 @@ export const AddIntegrationModal = ({
|
||||
}
|
||||
handleClose();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "Unknown error occurred");
|
||||
toast.error(e.message);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -322,7 +322,7 @@ export const AddIntegrationModal = ({
|
||||
|
||||
toast.success(t("environments.integrations.integration_removed_successfully"));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "Unknown error occurred");
|
||||
toast.error(e.message);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import { GoBackButton } from "@/modules/ui/components/go-back-button";
|
||||
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
|
||||
import { PageHeader } from "@/modules/ui/components/page-header";
|
||||
|
||||
const Page = async (props: { params: Promise<{ environmentId: string }> }) => {
|
||||
const Page = async (props) => {
|
||||
const params = await props.params;
|
||||
const t = await getTranslate();
|
||||
const isEnabled = !!AIRTABLE_CLIENT_ID;
|
||||
|
||||
@@ -195,7 +195,7 @@ export const AddIntegrationModal = ({
|
||||
resetForm();
|
||||
setOpen(false);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "Unknown error occurred");
|
||||
toast.error(e.message);
|
||||
} finally {
|
||||
setIsLinkingSheet(false);
|
||||
}
|
||||
@@ -237,7 +237,7 @@ export const AddIntegrationModal = ({
|
||||
toast.success(t("environments.integrations.integration_removed_successfully"));
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "Unknown error occurred");
|
||||
toast.error(error.message);
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ import { GoBackButton } from "@/modules/ui/components/go-back-button";
|
||||
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
|
||||
import { PageHeader } from "@/modules/ui/components/page-header";
|
||||
|
||||
const Page = async (props: { params: Promise<{ environmentId: string }> }) => {
|
||||
const Page = async (props) => {
|
||||
const params = await props.params;
|
||||
const t = await getTranslate();
|
||||
const isEnabled = !!(GOOGLE_SHEETS_CLIENT_ID && GOOGLE_SHEETS_CLIENT_SECRET && GOOGLE_SHEETS_REDIRECT_URL);
|
||||
|
||||
@@ -234,7 +234,7 @@ export const AddIntegrationModal = ({
|
||||
resetForm();
|
||||
setOpen(false);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "Unknown error occurred");
|
||||
toast.error(e.message);
|
||||
} finally {
|
||||
setIsLinkingDatabase(false);
|
||||
}
|
||||
@@ -255,7 +255,7 @@ export const AddIntegrationModal = ({
|
||||
toast.success(t("environments.integrations.integration_removed_successfully"));
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "Unknown error occurred");
|
||||
toast.error(error.message);
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ const MappingErrorMessage = ({
|
||||
question_label: element.label,
|
||||
col_name: col.name,
|
||||
col_type: col.type,
|
||||
mapped_type: (TYPE_MAPPING as Record<string, string[]>)[element.id].join(" ,"),
|
||||
mapped_type: TYPE_MAPPING[element.id].join(" ,"),
|
||||
})}
|
||||
</>
|
||||
);
|
||||
@@ -135,7 +135,7 @@ export const MappingRow = ({
|
||||
return copy;
|
||||
}
|
||||
|
||||
const isValidColType = (TYPE_MAPPING as Record<string, string[]>)[item.type]?.includes(col.type);
|
||||
const isValidColType = TYPE_MAPPING[item.type].includes(col.type);
|
||||
if (!isValidColType) {
|
||||
copy[idx] = {
|
||||
...copy[idx],
|
||||
@@ -166,7 +166,7 @@ export const MappingRow = ({
|
||||
return copy;
|
||||
}
|
||||
|
||||
const isValidElemType = (TYPE_MAPPING as Record<string, string[]>)[elem.type]?.includes(item.type);
|
||||
const isValidElemType = TYPE_MAPPING[elem.type].includes(item.type);
|
||||
if (!isValidElemType) {
|
||||
copy[idx] = {
|
||||
...copy[idx],
|
||||
|
||||
@@ -36,7 +36,7 @@ export const NotionWrapper = ({
|
||||
}: NotionWrapperProps) => {
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [isConnected, setIsConnected] = useState(
|
||||
notionIntegration ? !!notionIntegration.config.key?.bot_id : false
|
||||
notionIntegration ? notionIntegration.config.key?.bot_id : false
|
||||
);
|
||||
const [selectedIntegration, setSelectedIntegration] = useState<
|
||||
(TIntegrationNotionConfigData & { index: number }) | null
|
||||
|
||||
@@ -18,7 +18,7 @@ import { GoBackButton } from "@/modules/ui/components/go-back-button";
|
||||
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
|
||||
import { PageHeader } from "@/modules/ui/components/page-header";
|
||||
|
||||
const Page = async (props: { params: Promise<{ environmentId: string }> }) => {
|
||||
const Page = async (props) => {
|
||||
const params = await props.params;
|
||||
const t = await getTranslate();
|
||||
const enabled = !!(
|
||||
|
||||
@@ -27,7 +27,7 @@ const getStatusText = (count: number, t: TFunction, type: string) => {
|
||||
return `${count} ${type}s`;
|
||||
};
|
||||
|
||||
const Page = async (props: { params: Promise<{ environmentId: string }> }) => {
|
||||
const Page = async (props) => {
|
||||
const params = await props.params;
|
||||
const t = await getTranslate();
|
||||
|
||||
|
||||
@@ -161,7 +161,7 @@ export const AddChannelMappingModal = ({
|
||||
resetForm();
|
||||
setOpen(false);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "Unknown error occurred");
|
||||
toast.error(e.message);
|
||||
} finally {
|
||||
setIsLinkingChannel(false);
|
||||
}
|
||||
@@ -200,7 +200,7 @@ export const AddChannelMappingModal = ({
|
||||
toast.success(t("environments.integrations.integration_removed_successfully"));
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "Unknown error occurred");
|
||||
toast.error(error.message);
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ export const SlackWrapper = ({
|
||||
webAppUrl,
|
||||
locale,
|
||||
}: SlackWrapperProps) => {
|
||||
const [isConnected, setIsConnected] = useState(slackIntegration ? !!slackIntegration.config?.key : false);
|
||||
const [isConnected, setIsConnected] = useState(slackIntegration ? slackIntegration.config?.key : false);
|
||||
const [slackChannels, setSlackChannels] = useState<TIntegrationItem[]>([]);
|
||||
const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
|
||||
const [showReconnectButton, setShowReconnectButton] = useState<boolean>(false);
|
||||
|
||||
@@ -11,7 +11,7 @@ import { GoBackButton } from "@/modules/ui/components/go-back-button";
|
||||
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
|
||||
import { PageHeader } from "@/modules/ui/components/page-header";
|
||||
|
||||
const Page = async (props: { params: Promise<{ environmentId: string }> }) => {
|
||||
const Page = async (props) => {
|
||||
const params = await props.params;
|
||||
const isEnabled = !!(SLACK_CLIENT_ID && SLACK_CLIENT_SECRET);
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
import { LanguagesLoading } from "@/modules/projects/settings/languages/loading";
|
||||
import { LanguagesLoading } from "@/modules/ee/languages/loading";
|
||||
|
||||
export default LanguagesLoading;
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
import { LanguagesPage } from "@/modules/projects/settings/languages/page";
|
||||
import { LanguagesPage } from "@/modules/ee/languages/page";
|
||||
|
||||
export default LanguagesPage;
|
||||
|
||||
@@ -1,19 +1,13 @@
|
||||
import { getServerSession } from "next-auth";
|
||||
import { ChatwootWidget } from "@/app/chatwoot/ChatwootWidget";
|
||||
import { PostHogIdentify } from "@/app/posthog/PostHogIdentify";
|
||||
import {
|
||||
CHATWOOT_BASE_URL,
|
||||
CHATWOOT_WEBSITE_TOKEN,
|
||||
IS_CHATWOOT_CONFIGURED,
|
||||
POSTHOG_KEY,
|
||||
} from "@/lib/constants";
|
||||
import { CHATWOOT_BASE_URL, CHATWOOT_WEBSITE_TOKEN, IS_CHATWOOT_CONFIGURED } from "@/lib/constants";
|
||||
import { getUser } from "@/lib/user/service";
|
||||
import { authOptions } from "@/modules/auth/lib/authOptions";
|
||||
import { ClientLogout } from "@/modules/ui/components/client-logout";
|
||||
import { NoMobileOverlay } from "@/modules/ui/components/no-mobile-overlay";
|
||||
import { ToasterClient } from "@/modules/ui/components/toaster-client";
|
||||
|
||||
const AppLayout = async ({ children }: { children: React.ReactNode }) => {
|
||||
const AppLayout = async ({ children }) => {
|
||||
const session = await getServerSession(authOptions);
|
||||
const user = session?.user?.id ? await getUser(session.user.id) : null;
|
||||
|
||||
@@ -25,9 +19,6 @@ const AppLayout = async ({ children }: { children: React.ReactNode }) => {
|
||||
return (
|
||||
<>
|
||||
<NoMobileOverlay />
|
||||
{POSTHOG_KEY && user && (
|
||||
<PostHogIdentify posthogKey={POSTHOG_KEY} userId={user.id} email={user.email} name={user.name} />
|
||||
)}
|
||||
{IS_CHATWOOT_CONFIGURED && (
|
||||
<ChatwootWidget
|
||||
userEmail={user?.email}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NoMobileOverlay } from "@/modules/ui/components/no-mobile-overlay";
|
||||
|
||||
const AppLayout = async ({ children }: { children: React.ReactNode }) => {
|
||||
const AppLayout = async ({ children }) => {
|
||||
return (
|
||||
<>
|
||||
<NoMobileOverlay />
|
||||
|
||||
@@ -169,9 +169,6 @@ export const mockSurvey: TSurvey = {
|
||||
segment: null,
|
||||
followUps: mockFollowUps,
|
||||
metadata: {},
|
||||
blocks: [],
|
||||
isCaptureIpEnabled: false,
|
||||
slug: null,
|
||||
};
|
||||
|
||||
export const mockContactQuestion: TSurveyContactInfoQuestion = {
|
||||
|
||||
@@ -156,7 +156,7 @@ const handleAirtableIntegration = async (
|
||||
} catch (err) {
|
||||
return {
|
||||
ok: false,
|
||||
error: err instanceof Error ? err : new Error(String(err)),
|
||||
error: err,
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -197,7 +197,7 @@ const handleGoogleSheetsIntegration = async (
|
||||
} catch (err) {
|
||||
return {
|
||||
ok: false,
|
||||
error: err instanceof Error ? err : new Error(String(err)),
|
||||
error: err,
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -239,7 +239,7 @@ const handleSlackIntegration = async (
|
||||
} catch (err) {
|
||||
return {
|
||||
ok: false,
|
||||
error: err instanceof Error ? err : new Error(String(err)),
|
||||
error: err,
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -349,7 +349,7 @@ const handleNotionIntegration = async (
|
||||
} catch (err) {
|
||||
return {
|
||||
ok: false,
|
||||
error: err instanceof Error ? err : new Error(String(err)),
|
||||
error: err,
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -374,8 +374,8 @@ const buildNotionPayloadProperties = (
|
||||
const pictureElement = surveyElements.find((el) => el.id === resp);
|
||||
|
||||
responses[resp] = (pictureElement as any)?.choices
|
||||
.filter((choice: { id: string; imageUrl: string }) => selectedChoiceIds.includes(choice.id))
|
||||
.map((choice: { id: string; imageUrl: string }) => resolveStorageUrlAuto(choice.imageUrl));
|
||||
.filter((choice) => selectedChoiceIds.includes(choice.id))
|
||||
.map((choice) => resolveStorageUrlAuto(choice.imageUrl));
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -6,12 +6,7 @@ import { logger } from "@formbricks/logger";
|
||||
import { sendTelemetryEvents } from "./telemetry";
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock("@formbricks/cache", () => ({
|
||||
getCacheService: vi.fn(),
|
||||
createCacheKey: {
|
||||
custom: vi.fn((_namespace: string, key: string) => key),
|
||||
},
|
||||
}));
|
||||
vi.mock("@formbricks/cache");
|
||||
vi.mock("@formbricks/database", () => ({
|
||||
prisma: {
|
||||
organization: {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { IntegrationType } from "@prisma/client";
|
||||
import { createCacheKey, getCacheService } from "@formbricks/cache";
|
||||
import { type CacheKey, getCacheService } from "@formbricks/cache";
|
||||
import { prisma } from "@formbricks/database";
|
||||
import { logger } from "@formbricks/logger";
|
||||
import { env } from "@/lib/env";
|
||||
@@ -7,8 +7,8 @@ import { getInstanceInfo } from "@/lib/instance";
|
||||
import packageJson from "@/package.json";
|
||||
|
||||
const TELEMETRY_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||
const TELEMETRY_LOCK_KEY = createCacheKey.custom("analytics", "telemetry_lock");
|
||||
const TELEMETRY_LAST_SENT_KEY = createCacheKey.custom("analytics", "telemetry_last_sent_ts");
|
||||
const TELEMETRY_LOCK_KEY = "telemetry_lock" as CacheKey;
|
||||
const TELEMETRY_LAST_SENT_KEY = "telemetry_last_sent_ts" as CacheKey;
|
||||
|
||||
/**
|
||||
* In-memory timestamp for the next telemetry check.
|
||||
|
||||
@@ -18,7 +18,6 @@ import { convertDatesInObject } from "@/lib/time";
|
||||
import { validateWebhookUrl } from "@/lib/utils/validate-webhook-url";
|
||||
import { queueAuditEvent } from "@/modules/ee/audit-logs/lib/handler";
|
||||
import { TAuditStatus, UNKNOWN_DATA } from "@/modules/ee/audit-logs/types/audit-log";
|
||||
import { recordResponseCreatedMeterEvent } from "@/modules/ee/billing/lib/metering";
|
||||
import { sendResponseFinishedEmail } from "@/modules/email";
|
||||
import { resolveStorageUrlsInObject } from "@/modules/storage/utils";
|
||||
import { sendFollowUpsForResponse } from "@/modules/survey/follow-ups/lib/follow-ups";
|
||||
@@ -291,14 +290,6 @@ export const POST = async (request: Request) => {
|
||||
});
|
||||
}
|
||||
if (event === "responseCreated") {
|
||||
recordResponseCreatedMeterEvent({
|
||||
stripeCustomerId: organization.billing.stripeCustomerId,
|
||||
responseId: response.id,
|
||||
createdAt: response.createdAt,
|
||||
}).catch((error) => {
|
||||
logger.error({ error, responseId: response.id }, "Failed to record response meter event");
|
||||
});
|
||||
|
||||
// Send telemetry events
|
||||
await sendTelemetryEvents();
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import * as Sentry from "@sentry/nextjs";
|
||||
import NextAuth, { Account, Profile, User } from "next-auth";
|
||||
import { AdapterUser } from "next-auth/adapters";
|
||||
import { CredentialInput } from "next-auth/providers/credentials";
|
||||
import NextAuth from "next-auth";
|
||||
import { logger } from "@formbricks/logger";
|
||||
import { IS_PRODUCTION, SENTRY_DSN } from "@/lib/constants";
|
||||
import { authOptions as baseAuthOptions } from "@/modules/auth/lib/authOptions";
|
||||
@@ -75,19 +73,7 @@ const handler = async (req: Request, ctx: any) => {
|
||||
if (error) throw error;
|
||||
return result;
|
||||
},
|
||||
async signIn({
|
||||
user,
|
||||
account,
|
||||
profile,
|
||||
email,
|
||||
credentials,
|
||||
}: {
|
||||
user: User | AdapterUser;
|
||||
account: Account | null;
|
||||
profile?: Profile;
|
||||
email?: { verificationRequest?: boolean };
|
||||
credentials?: Record<string, CredentialInput>;
|
||||
}) {
|
||||
async signIn({ user, account, profile, email, credentials }) {
|
||||
let result: boolean | string = true;
|
||||
let error: any = undefined;
|
||||
let authMethod = "unknown";
|
||||
|
||||
@@ -8,9 +8,7 @@ import { getContactByUserId } from "./contact";
|
||||
import { createDisplay } from "./display";
|
||||
|
||||
vi.mock("@/lib/utils/validate", () => ({
|
||||
validateInputs: vi.fn((inputs: [unknown, unknown][]) =>
|
||||
inputs.map((input: [unknown, unknown]) => input[0])
|
||||
), // Pass through validation for testing
|
||||
validateInputs: vi.fn((inputs) => inputs.map((input) => input[0])), // Pass through validation for testing
|
||||
}));
|
||||
|
||||
vi.mock("@formbricks/database", () => ({
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { logger } from "@formbricks/logger";
|
||||
import { ZDisplayCreateInput } from "@formbricks/types/displays";
|
||||
import { ResourceNotFoundError } from "@formbricks/types/errors";
|
||||
import { responses } from "@/app/lib/api/response";
|
||||
import { transformErrorToDetails } from "@/app/lib/api/validator";
|
||||
import { THandlerParams, withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
|
||||
import { getOrganizationIdFromEnvironmentId } from "@/lib/utils/helper";
|
||||
import { withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
|
||||
import { getIsContactsEnabled } from "@/modules/ee/license-check/lib/utils";
|
||||
import { createDisplay } from "./lib/display";
|
||||
|
||||
interface Context {
|
||||
params: Promise<{
|
||||
environmentId: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export const OPTIONS = async (): Promise<Response> => {
|
||||
return responses.successResponse(
|
||||
{},
|
||||
@@ -19,7 +25,7 @@ export const OPTIONS = async (): Promise<Response> => {
|
||||
};
|
||||
|
||||
export const POST = withV1ApiWrapper({
|
||||
handler: async ({ req, props }: THandlerParams<{ params: Promise<{ environmentId: string }> }>) => {
|
||||
handler: async ({ req, props }: { req: NextRequest; props: Context }) => {
|
||||
const params = await props.params;
|
||||
const jsonInput = await req.json();
|
||||
const inputValidation = ZDisplayCreateInput.safeParse({
|
||||
@@ -38,8 +44,7 @@ export const POST = withV1ApiWrapper({
|
||||
}
|
||||
|
||||
if (inputValidation.data.userId) {
|
||||
const organizationId = await getOrganizationIdFromEnvironmentId(params.environmentId);
|
||||
const isContactsEnabled = await getIsContactsEnabled(organizationId);
|
||||
const isContactsEnabled = await getIsContactsEnabled();
|
||||
if (!isContactsEnabled) {
|
||||
return {
|
||||
response: responses.forbiddenResponse(
|
||||
|
||||
@@ -38,6 +38,13 @@ const mockEnvironmentData = {
|
||||
placement: "bottomRight",
|
||||
inAppSurveyBranding: true,
|
||||
styling: { allowStyleOverwrite: false },
|
||||
organization: {
|
||||
id: "org-123",
|
||||
billing: {
|
||||
plan: "free",
|
||||
limits: { monthly: { responses: 100 } },
|
||||
},
|
||||
},
|
||||
},
|
||||
actionClasses: [
|
||||
{
|
||||
@@ -107,6 +114,13 @@ describe("getEnvironmentStateData", () => {
|
||||
styling: { allowStyleOverwrite: false },
|
||||
},
|
||||
},
|
||||
organization: {
|
||||
id: "org-123",
|
||||
billing: {
|
||||
plan: "free",
|
||||
limits: { monthly: { responses: 100 } },
|
||||
},
|
||||
},
|
||||
surveys: mockEnvironmentData.surveys,
|
||||
actionClasses: mockEnvironmentData.actionClasses,
|
||||
});
|
||||
@@ -140,6 +154,18 @@ describe("getEnvironmentStateData", () => {
|
||||
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",
|
||||
@@ -257,11 +283,32 @@ describe("getEnvironmentStateData", () => {
|
||||
expect(result.environment.appSetupCompleted).toBe(false);
|
||||
});
|
||||
|
||||
test("should not include organization in result", async () => {
|
||||
vi.mocked(prisma.environment.findUnique).mockResolvedValue(mockEnvironmentData as never);
|
||||
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).not.toHaveProperty("organization");
|
||||
expect(result.organization).toEqual({
|
||||
id: "org-enterprise",
|
||||
billing: customBilling,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,6 +25,10 @@ export interface EnvironmentStateData {
|
||||
appSetupCompleted: boolean;
|
||||
project: TJsEnvironmentStateProject;
|
||||
};
|
||||
organization: {
|
||||
id: string;
|
||||
billing: any;
|
||||
};
|
||||
surveys: TJsEnvironmentStateSurvey[];
|
||||
actionClasses: TJsEnvironmentStateActionClass[];
|
||||
}
|
||||
@@ -55,6 +59,13 @@ export const getEnvironmentStateData = async (environmentId: string): Promise<En
|
||||
placement: true,
|
||||
inAppSurveyBranding: true,
|
||||
styling: true,
|
||||
// Organization data (nested select for efficiency)
|
||||
organization: {
|
||||
select: {
|
||||
id: true,
|
||||
billing: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
// Action classes (optimized for environment state)
|
||||
@@ -146,6 +157,10 @@ export const getEnvironmentStateData = async (environmentId: string): Promise<En
|
||||
throw new ResourceNotFoundError("project", null);
|
||||
}
|
||||
|
||||
if (!environmentData.project.organization) {
|
||||
throw new ResourceNotFoundError("organization", null);
|
||||
}
|
||||
|
||||
// Transform surveys using existing utility
|
||||
const transformedSurveys = environmentData.surveys.map((survey) =>
|
||||
transformPrismaSurvey<TJsEnvironmentStateSurvey>(survey)
|
||||
@@ -166,6 +181,10 @@ export const getEnvironmentStateData = async (environmentId: string): Promise<En
|
||||
styling: resolveStorageUrlsInObject(environmentData.project.styling),
|
||||
},
|
||||
},
|
||||
organization: {
|
||||
id: environmentData.project.organization.id,
|
||||
billing: environmentData.project.organization.billing,
|
||||
},
|
||||
surveys: resolveStorageUrlsInObject(transformedSurveys),
|
||||
actionClasses: environmentData.actionClasses as TJsEnvironmentStateActionClass[],
|
||||
};
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { prisma } from "@formbricks/database";
|
||||
import { logger } from "@formbricks/logger";
|
||||
import { TActionClass } from "@formbricks/types/action-classes";
|
||||
import { ResourceNotFoundError } from "@formbricks/types/errors";
|
||||
import { TJsEnvironmentState, TJsEnvironmentStateProject } from "@formbricks/types/js";
|
||||
import { TOrganization } from "@formbricks/types/organizations";
|
||||
import { TSurvey } from "@formbricks/types/surveys/types";
|
||||
import { cache } from "@/lib/cache";
|
||||
import { getMonthlyOrganizationResponseCount } from "@/lib/organization/service";
|
||||
import { EnvironmentStateData, getEnvironmentStateData } from "./data";
|
||||
import { getEnvironmentState } from "./environmentState";
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock("@/lib/organization/service");
|
||||
vi.mock("@/lib/cache", () => ({
|
||||
cache: {
|
||||
withCache: vi.fn(),
|
||||
@@ -67,14 +70,17 @@ const mockOrganization: TOrganization = {
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
billing: {
|
||||
plan: "free",
|
||||
stripeCustomerId: null,
|
||||
period: "monthly",
|
||||
limits: {
|
||||
projects: 1,
|
||||
monthly: {
|
||||
responses: 100,
|
||||
miu: 1000,
|
||||
},
|
||||
},
|
||||
usageCycleAnchor: new Date(),
|
||||
periodStart: new Date(),
|
||||
},
|
||||
isAIEnabled: false,
|
||||
};
|
||||
@@ -156,6 +162,7 @@ describe("getEnvironmentState", () => {
|
||||
|
||||
// Default mocks for successful retrieval
|
||||
vi.mocked(getEnvironmentStateData).mockResolvedValue(mockEnvironmentStateData);
|
||||
vi.mocked(getMonthlyOrganizationResponseCount).mockResolvedValue(50); // Default below limit
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -175,6 +182,7 @@ describe("getEnvironmentState", () => {
|
||||
expect(result.data).toEqual(expectedData);
|
||||
expect(getEnvironmentStateData).toHaveBeenCalledWith(environmentId);
|
||||
expect(prisma.environment.update).not.toHaveBeenCalled();
|
||||
expect(getMonthlyOrganizationResponseCount).toHaveBeenCalledWith(mockOrganization.id);
|
||||
});
|
||||
|
||||
test("should throw ResourceNotFoundError if environment not found", async () => {
|
||||
@@ -213,6 +221,24 @@ describe("getEnvironmentState", () => {
|
||||
expect(result.data).toBeDefined();
|
||||
});
|
||||
|
||||
test("should return empty surveys if monthly response limit reached (Cloud)", async () => {
|
||||
vi.mocked(getMonthlyOrganizationResponseCount).mockResolvedValue(100); // Exactly at limit
|
||||
|
||||
const result = await getEnvironmentState(environmentId);
|
||||
|
||||
expect(result.data.surveys).toEqual([]);
|
||||
expect(getMonthlyOrganizationResponseCount).toHaveBeenCalledWith(mockOrganization.id);
|
||||
});
|
||||
|
||||
test("should return surveys if monthly response limit not reached (Cloud)", async () => {
|
||||
vi.mocked(getMonthlyOrganizationResponseCount).mockResolvedValue(99); // Below limit
|
||||
|
||||
const result = await getEnvironmentState(environmentId);
|
||||
|
||||
expect(result.data.surveys).toEqual(mockSurveys);
|
||||
expect(getMonthlyOrganizationResponseCount).toHaveBeenCalledWith(mockOrganization.id);
|
||||
});
|
||||
|
||||
test("should include recaptchaSiteKey if recaptcha variables are set", async () => {
|
||||
const result = await getEnvironmentState(environmentId);
|
||||
|
||||
@@ -229,6 +255,32 @@ describe("getEnvironmentState", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("should handle null response limit correctly (unlimited)", async () => {
|
||||
const unlimitedOrgData = {
|
||||
...mockEnvironmentStateData,
|
||||
organization: {
|
||||
...mockEnvironmentStateData.organization,
|
||||
billing: {
|
||||
...mockOrganization.billing,
|
||||
limits: {
|
||||
...mockOrganization.billing.limits,
|
||||
monthly: {
|
||||
...mockOrganization.billing.limits.monthly,
|
||||
responses: null, // Unlimited
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
vi.mocked(getEnvironmentStateData).mockResolvedValue(unlimitedOrgData);
|
||||
vi.mocked(getMonthlyOrganizationResponseCount).mockResolvedValue(999999); // High count
|
||||
|
||||
const result = await getEnvironmentState(environmentId);
|
||||
|
||||
// Should return surveys even with high count since limit is null (unlimited)
|
||||
expect(result.data.surveys).toEqual(mockSurveys);
|
||||
});
|
||||
|
||||
test("should propagate database update errors", async () => {
|
||||
const incompleteEnvironmentData = {
|
||||
...mockEnvironmentStateData,
|
||||
|
||||
@@ -3,7 +3,8 @@ import { createCacheKey } from "@formbricks/cache";
|
||||
import { prisma } from "@formbricks/database";
|
||||
import { TJsEnvironmentState } from "@formbricks/types/js";
|
||||
import { cache } from "@/lib/cache";
|
||||
import { IS_RECAPTCHA_CONFIGURED, RECAPTCHA_SITE_KEY } from "@/lib/constants";
|
||||
import { IS_FORMBRICKS_CLOUD, IS_RECAPTCHA_CONFIGURED, RECAPTCHA_SITE_KEY } from "@/lib/constants";
|
||||
import { getMonthlyOrganizationResponseCount } from "@/lib/organization/service";
|
||||
import { getEnvironmentStateData } from "./data";
|
||||
|
||||
/**
|
||||
@@ -21,7 +22,8 @@ export const getEnvironmentState = async (
|
||||
return cache.withCache(
|
||||
async () => {
|
||||
// Single optimized database call replacing multiple service calls
|
||||
const { environment, surveys, actionClasses } = await getEnvironmentStateData(environmentId);
|
||||
const { environment, organization, surveys, actionClasses } =
|
||||
await getEnvironmentStateData(environmentId);
|
||||
|
||||
// Handle app setup completion update if needed
|
||||
// This is a one-time setup flag that can tolerate TTL-based cache expiration
|
||||
@@ -32,9 +34,18 @@ export const getEnvironmentState = async (
|
||||
});
|
||||
}
|
||||
|
||||
// Check monthly response limits for Formbricks Cloud
|
||||
let isMonthlyResponsesLimitReached = false;
|
||||
if (IS_FORMBRICKS_CLOUD) {
|
||||
const monthlyResponseLimit = organization.billing.limits.monthly.responses;
|
||||
const currentResponseCount = await getMonthlyOrganizationResponseCount(organization.id);
|
||||
isMonthlyResponsesLimitReached =
|
||||
monthlyResponseLimit !== null && currentResponseCount >= monthlyResponseLimit;
|
||||
}
|
||||
|
||||
// Build the response data
|
||||
const data: TJsEnvironmentState["data"] = {
|
||||
surveys,
|
||||
surveys: !isMonthlyResponsesLimitReached ? surveys : [],
|
||||
actionClasses,
|
||||
project: environment.project,
|
||||
...(IS_RECAPTCHA_CONFIGURED ? { recaptchaSiteKey: RECAPTCHA_SITE_KEY } : {}),
|
||||
@@ -43,6 +54,6 @@ export const getEnvironmentState = async (
|
||||
return { data };
|
||||
},
|
||||
createCacheKey.environment.state(environmentId),
|
||||
60 * 1000 // 1 minute in milliseconds
|
||||
60 * 1000 // 1 minutes in milliseconds
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { logger } from "@formbricks/logger";
|
||||
import { ZEnvironmentId } from "@formbricks/types/environment";
|
||||
import { ResourceNotFoundError } from "@formbricks/types/errors";
|
||||
import { getEnvironmentState } from "@/app/api/v1/client/[environmentId]/environment/lib/environmentState";
|
||||
import { responses } from "@/app/lib/api/response";
|
||||
import { THandlerParams, withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
|
||||
import { withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
|
||||
|
||||
export const OPTIONS = async (): Promise<Response> => {
|
||||
return responses.successResponse(
|
||||
@@ -18,7 +19,13 @@ export const OPTIONS = async (): Promise<Response> => {
|
||||
};
|
||||
|
||||
export const GET = withV1ApiWrapper({
|
||||
handler: async ({ req, props }: THandlerParams<{ params: Promise<{ environmentId: string }> }>) => {
|
||||
handler: async ({
|
||||
req,
|
||||
props,
|
||||
}: {
|
||||
req: NextRequest;
|
||||
props: { params: Promise<{ environmentId: string }> };
|
||||
}) => {
|
||||
const params = await props.params;
|
||||
|
||||
try {
|
||||
@@ -95,10 +102,7 @@ export const GET = withV1ApiWrapper({
|
||||
"Error in GET /api/v1/client/[environmentId]/environment"
|
||||
);
|
||||
return {
|
||||
response: responses.internalServerErrorResponse(
|
||||
err instanceof Error ? err.message : "Unknown error occurred",
|
||||
true
|
||||
),
|
||||
response: responses.internalServerErrorResponse(err.message, true),
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
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 { TSurveyElement } from "@formbricks/types/surveys/elements";
|
||||
import { TSurvey } from "@formbricks/types/surveys/types";
|
||||
import { responses } from "@/app/lib/api/response";
|
||||
import { transformErrorToDetails } from "@/app/lib/api/validator";
|
||||
import { THandlerParams, withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
|
||||
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";
|
||||
@@ -63,7 +63,13 @@ const validateResponse = (
|
||||
};
|
||||
|
||||
export const PUT = withV1ApiWrapper({
|
||||
handler: async ({ req, props }: THandlerParams<{ params: Promise<{ responseId: string }> }>) => {
|
||||
handler: async ({
|
||||
req,
|
||||
props,
|
||||
}: {
|
||||
req: NextRequest;
|
||||
props: { params: Promise<{ responseId: string }> };
|
||||
}) => {
|
||||
const params = await props.params;
|
||||
const { responseId } = params;
|
||||
|
||||
@@ -92,18 +98,7 @@ export const PUT = withV1ApiWrapper({
|
||||
} catch (error) {
|
||||
const endpoint = "PUT /api/v1/client/[environmentId]/responses/[responseId]";
|
||||
return {
|
||||
response: handleDatabaseError(
|
||||
error instanceof Error ? error : new Error(String(error)),
|
||||
req.url,
|
||||
endpoint,
|
||||
responseId
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
if (!response) {
|
||||
return {
|
||||
response: responses.notFoundResponse("Response", responseId, true),
|
||||
response: handleDatabaseError(error, req.url, endpoint, responseId),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -120,18 +115,7 @@ export const PUT = withV1ApiWrapper({
|
||||
} catch (error) {
|
||||
const endpoint = "PUT /api/v1/client/[environmentId]/responses/[responseId]";
|
||||
return {
|
||||
response: handleDatabaseError(
|
||||
error instanceof Error ? error : new Error(String(error)),
|
||||
req.url,
|
||||
endpoint,
|
||||
responseId
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
if (!survey) {
|
||||
return {
|
||||
response: responses.notFoundResponse("Survey", response.surveyId, true),
|
||||
response: handleDatabaseError(error, req.url, endpoint, responseId),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -144,7 +128,7 @@ export const PUT = withV1ApiWrapper({
|
||||
// Validate response data for "other" options exceeding character limit
|
||||
const otherResponseInvalidQuestionId = validateOtherOptionLengthForMultipleChoice({
|
||||
responseData: inputValidation.data.data,
|
||||
surveyQuestions: survey.questions as unknown as TSurveyElement[],
|
||||
surveyQuestions: survey.questions,
|
||||
responseLanguage: inputValidation.data.language,
|
||||
});
|
||||
|
||||
@@ -189,14 +173,6 @@ export const PUT = withV1ApiWrapper({
|
||||
response: responses.internalServerErrorResponse(error.message),
|
||||
};
|
||||
}
|
||||
|
||||
logger.error(
|
||||
{ error, url: req.url },
|
||||
"Error in PUT /api/v1/client/[environmentId]/responses/[responseId]"
|
||||
);
|
||||
return {
|
||||
response: responses.internalServerErrorResponse("Something went wrong"),
|
||||
};
|
||||
}
|
||||
|
||||
const { quotaFull, ...responseData } = updatedResponse;
|
||||
|
||||
@@ -19,7 +19,7 @@ vi.mock("react", async () => {
|
||||
const actual = await vi.importActual("react");
|
||||
return {
|
||||
...actual,
|
||||
cache: vi.fn((fn: Function) => fn), // Mock react's cache to just return the function
|
||||
cache: vi.fn((fn) => fn), // Mock react's cache to just return the function
|
||||
};
|
||||
});
|
||||
|
||||
@@ -34,12 +34,7 @@ describe("Contact API Lib", () => {
|
||||
|
||||
describe("getContact", () => {
|
||||
test("should return contact if found", async () => {
|
||||
const mockContactData = {
|
||||
id: mockContactId,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
environmentId: mockEnvironmentId,
|
||||
};
|
||||
const mockContactData = { id: mockContactId };
|
||||
vi.mocked(prisma.contact.findUnique).mockResolvedValue(mockContactData);
|
||||
|
||||
const contact = await getContact(mockContactId);
|
||||
@@ -82,17 +77,12 @@ describe("Contact API Lib", () => {
|
||||
test("should return contact with formatted attributes if found", async () => {
|
||||
const mockContactData = {
|
||||
id: mockContactId,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
environmentId: mockEnvironmentId,
|
||||
attributes: [
|
||||
{ attributeKey: { key: "userId" }, value: mockUserId },
|
||||
{ attributeKey: { key: "email" }, value: "test@example.com" },
|
||||
],
|
||||
};
|
||||
vi.mocked(prisma.contact.findFirst).mockResolvedValue(
|
||||
mockContactData as Awaited<ReturnType<typeof prisma.contact.findFirst>>
|
||||
);
|
||||
vi.mocked(prisma.contact.findFirst).mockResolvedValue(mockContactData);
|
||||
|
||||
const contact = await getContactByUserId(mockEnvironmentId, mockUserId);
|
||||
|
||||
|
||||
@@ -54,10 +54,10 @@ export const getContactByUserId = reactCache(
|
||||
return null;
|
||||
}
|
||||
|
||||
const contactAttributes = contact.attributes.reduce<TContactAttributes>((acc, attr) => {
|
||||
const contactAttributes = contact.attributes.reduce((acc, attr) => {
|
||||
acc[attr.attributeKey.key] = attr.value;
|
||||
return acc;
|
||||
}, {});
|
||||
}, {}) as TContactAttributes;
|
||||
|
||||
return {
|
||||
id: contact.id,
|
||||
|
||||
@@ -63,6 +63,7 @@ const mockOrganization = {
|
||||
name: "Test Org",
|
||||
billing: {
|
||||
limits: { monthly: { responses: 100 } },
|
||||
plan: "free",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -114,7 +115,7 @@ describe("createResponse", () => {
|
||||
|
||||
test("should handle finished response and calculate TTC", async () => {
|
||||
const finishedInput = { ...mockResponseInput, finished: true };
|
||||
await createResponse(finishedInput, prisma);
|
||||
await createResponse(finishedInput);
|
||||
expect(calculateTtcTotal).toHaveBeenCalledWith(mockResponseInput.ttc);
|
||||
expect(prisma.response.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
@@ -134,13 +135,13 @@ describe("createResponse", () => {
|
||||
clientVersion: "test",
|
||||
});
|
||||
vi.mocked(prisma.response.create).mockRejectedValue(prismaError);
|
||||
await expect(createResponse(mockResponseInput, prisma)).rejects.toThrow(DatabaseError);
|
||||
await expect(createResponse(mockResponseInput)).rejects.toThrow(DatabaseError);
|
||||
});
|
||||
|
||||
test("should throw original error on other Prisma errors", async () => {
|
||||
const genericError = new Error("Generic database error");
|
||||
vi.mocked(prisma.response.create).mockRejectedValue(genericError);
|
||||
await expect(createResponse(mockResponseInput, prisma)).rejects.toThrow(genericError);
|
||||
await expect(createResponse(mockResponseInput)).rejects.toThrow(genericError);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -169,7 +170,7 @@ describe("createResponseWithQuotaEvaluation", () => {
|
||||
quotaFull: undefined,
|
||||
});
|
||||
|
||||
const result = await createResponseWithQuotaEvaluation(mockResponseInput);
|
||||
const result = await createResponseWithQuotaEvaluation(mockResponseInput, mockTx);
|
||||
|
||||
expect(evaluateResponseQuotas).toHaveBeenCalledWith({
|
||||
surveyId: mockResponseInput.surveyId,
|
||||
@@ -223,7 +224,7 @@ describe("createResponseWithQuotaEvaluation", () => {
|
||||
quotaFull: mockQuotaFull,
|
||||
});
|
||||
|
||||
const result = await createResponseWithQuotaEvaluation(mockResponseInput);
|
||||
const result = await createResponseWithQuotaEvaluation(mockResponseInput, mockTx);
|
||||
|
||||
expect(evaluateResponseQuotas).toHaveBeenCalledWith({
|
||||
surveyId: mockResponseInput.surveyId,
|
||||
@@ -277,7 +278,7 @@ describe("createResponseWithQuotaEvaluation", () => {
|
||||
quotaFull: mockQuotaFull,
|
||||
});
|
||||
|
||||
const result = await createResponseWithQuotaEvaluation(mockResponseInput);
|
||||
const result = await createResponseWithQuotaEvaluation(mockResponseInput, mockTx);
|
||||
|
||||
expect(result).toEqual({
|
||||
id: responseId,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { headers } from "next/headers";
|
||||
import { NextRequest } from "next/server";
|
||||
import { UAParser } from "ua-parser-js";
|
||||
import { logger } from "@formbricks/logger";
|
||||
import { ZEnvironmentId } from "@formbricks/types/environment";
|
||||
@@ -8,17 +9,22 @@ 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 { THandlerParams, withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
|
||||
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 { getOrganizationIdFromEnvironmentId } from "@/lib/utils/helper";
|
||||
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";
|
||||
import { createResponseWithQuotaEvaluation } from "./lib/response";
|
||||
|
||||
interface Context {
|
||||
params: Promise<{
|
||||
environmentId: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export const OPTIONS = async (): Promise<Response> => {
|
||||
return responses.successResponse(
|
||||
{},
|
||||
@@ -50,7 +56,7 @@ const validateResponse = (responseInputData: TResponseInput, survey: TSurvey) =>
|
||||
};
|
||||
|
||||
export const POST = withV1ApiWrapper({
|
||||
handler: async ({ req, props }: THandlerParams<{ params: Promise<{ environmentId: string }> }>) => {
|
||||
handler: async ({ req, props }: { req: NextRequest; props: Context }) => {
|
||||
const params = await props.params;
|
||||
const requestHeaders = await headers();
|
||||
let responseInput;
|
||||
@@ -60,7 +66,7 @@ export const POST = withV1ApiWrapper({
|
||||
return {
|
||||
response: responses.badRequestResponse(
|
||||
"Invalid JSON in request body",
|
||||
{ error: error instanceof Error ? error.message : "Unknown error occurred" },
|
||||
{ error: error.message },
|
||||
true
|
||||
),
|
||||
};
|
||||
@@ -102,8 +108,7 @@ export const POST = withV1ApiWrapper({
|
||||
const responseInputData = responseInputValidation.data;
|
||||
|
||||
if (responseInputData.userId) {
|
||||
const organizationId = await getOrganizationIdFromEnvironmentId(environmentId);
|
||||
const isContactsEnabled = await getIsContactsEnabled(organizationId);
|
||||
const isContactsEnabled = await getIsContactsEnabled();
|
||||
if (!isContactsEnabled) {
|
||||
return {
|
||||
response: responses.forbiddenResponse(
|
||||
@@ -178,9 +183,7 @@ export const POST = withV1ApiWrapper({
|
||||
} else {
|
||||
logger.error({ error, url: req.url }, "Error creating response");
|
||||
return {
|
||||
response: responses.internalServerErrorResponse(
|
||||
error instanceof Error ? error.message : "Unknown error occurred"
|
||||
),
|
||||
response: responses.internalServerErrorResponse(error.message),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user