Merge branch 'main' of https://github.com/formbricks/formbricks into survey-height-tweaks

This commit is contained in:
Johannes
2025-05-17 14:24:14 +07:00
61 changed files with 2954 additions and 3092 deletions

View File

@@ -211,5 +211,5 @@ UNKEY_ROOT_KEY=
# It's used automatically by Sentry during the build for authentication when uploading source maps.
# SENTRY_AUTH_TOKEN=
# Disable the user management from UI
# DISABLE_USER_MANAGEMENT=1
# Configure the minimum role for user management from UI(owner, manager, disabled)
# USER_MANAGEMENT_MINIMUM_ROLE="manager"

View File

@@ -11,9 +11,7 @@
"clean": "rimraf .turbo node_modules dist storybook-static"
},
"dependencies": {
"eslint-plugin-react-refresh": "0.4.20",
"react": "19.1.0",
"react-dom": "19.1.0"
"eslint-plugin-react-refresh": "0.4.20"
},
"devDependencies": {
"@chromatic-com/storybook": "3.2.6",

View File

@@ -1,487 +1,494 @@
import { generateResponseTableColumns } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponseTableColumns";
import { deleteResponseAction } from "@/modules/analysis/components/SingleResponseCard/actions";
import type { DragEndEvent } from "@dnd-kit/core";
import { act, cleanup, render, screen } from "@testing-library/react";
import { ResponseTable } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponseTable";
import { getResponsesDownloadUrlAction } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/actions";
import { getFormattedErrorMessage } from "@/lib/utils/helper";
import { cleanup, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, test, vi } from "vitest";
import toast from "react-hot-toast";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { TEnvironment } from "@formbricks/types/environment";
import { TResponse, TResponseTableData } from "@formbricks/types/responses";
import { TSurvey, TSurveyQuestion, TSurveyQuestionTypeEnum } from "@formbricks/types/surveys/types";
import { TResponse } from "@formbricks/types/responses";
import { TSurvey } from "@formbricks/types/surveys/types";
import { TTag } from "@formbricks/types/tags";
import { TUser, TUserLocale } from "@formbricks/types/user";
import { ResponseTable } from "./ResponseTable";
import { TUserLocale } from "@formbricks/types/user";
// Hoist variables used in mock factories
const { DndContextMock, SortableContextMock, arrayMoveMock } = vi.hoisted(() => {
const dndMock = vi.fn(({ children, onDragEnd }) => {
// Store the onDragEnd prop to allow triggering it in tests
(dndMock as any).lastOnDragEnd = onDragEnd;
return <div data-testid="dnd-context">{children}</div>;
});
const sortableMock = vi.fn(({ children }) => <>{children}</>);
const moveMock = vi.fn((array, from, to) => {
const newArray = [...array];
const [item] = newArray.splice(from, 1);
newArray.splice(to, 0, item);
return newArray;
});
return {
DndContextMock: dndMock,
SortableContextMock: sortableMock,
arrayMoveMock: moveMock,
};
});
// Mock react-hot-toast
vi.mock("react-hot-toast", () => ({
default: {
error: vi.fn(),
success: vi.fn(),
dismiss: vi.fn(),
},
}));
vi.mock("@dnd-kit/core", async (importOriginal) => {
const actual = await importOriginal<typeof import("@dnd-kit/core")>();
return {
...actual,
DndContext: DndContextMock,
useSensor: vi.fn(),
useSensors: vi.fn(),
closestCenter: vi.fn(),
};
});
// Mock components
vi.mock("@/modules/ui/components/button", () => ({
Button: ({ children, onClick, ...props }: any) => (
<button onClick={onClick} data-testid="button" {...props}>
{children}
</button>
),
}));
// Mock DndContext/SortableContext
vi.mock("@dnd-kit/core", () => ({
DndContext: ({ children }: any) => <div>{children}</div>,
useSensor: vi.fn(),
useSensors: vi.fn(() => "sensors"),
closestCenter: vi.fn(),
MouseSensor: vi.fn(),
TouchSensor: vi.fn(),
KeyboardSensor: vi.fn(),
}));
vi.mock("@dnd-kit/modifiers", () => ({
restrictToHorizontalAxis: vi.fn(),
restrictToHorizontalAxis: "restrictToHorizontalAxis",
}));
vi.mock("@dnd-kit/sortable", () => ({
SortableContext: SortableContextMock,
arrayMove: arrayMoveMock,
horizontalListSortingStrategy: vi.fn(),
SortableContext: ({ children }: any) => <>{children}</>,
horizontalListSortingStrategy: "horizontalListSortingStrategy",
arrayMove: vi.fn((arr, oldIndex, newIndex) => {
const result = [...arr];
const [removed] = result.splice(oldIndex, 1);
result.splice(newIndex, 0, removed);
return result;
}),
}));
// Mock AutoAnimate
vi.mock("@formkit/auto-animate/react", () => ({
useAutoAnimate: () => [vi.fn()],
}));
// Mock UI components
vi.mock("@/modules/ui/components/data-table", () => ({
DataTableHeader: ({ header }: any) => <th data-testid={`header-${header.id}`}>{header.id}</th>,
DataTableSettingsModal: ({ open, setOpen }: any) =>
open ? (
<div data-testid="settings-modal">
Settings Modal <button onClick={() => setOpen(false)}>Close</button>
</div>
) : null,
DataTableToolbar: ({
table,
deleteRowsAction,
downloadRowsAction,
setIsTableSettingsModalOpen,
setIsExpanded,
isExpanded,
}: any) => (
<div data-testid="table-toolbar">
<button
data-testid="toggle-expand"
onClick={() => setIsExpanded(!isExpanded)}
aria-pressed={isExpanded}>
Toggle Expand
</button>
<button data-testid="open-settings" onClick={() => setIsTableSettingsModalOpen(true)}>
Open Settings
</button>
<button
data-testid="delete-rows"
onClick={() => deleteRowsAction(Object.keys(table.getState().rowSelection))}>
Delete Selected
</button>
<button
data-testid="download-csv"
onClick={() => downloadRowsAction(Object.keys(table.getState().rowSelection), "csv")}>
Download CSV
</button>
<button
data-testid="download-xlsx"
onClick={() => downloadRowsAction(Object.keys(table.getState().rowSelection), "xlsx")}>
Download XLSX
</button>
</div>
),
}));
// Mock child components and hooks
vi.mock(
"@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponseCardModal",
() => ({
ResponseCardModal: vi.fn(({ open, setOpen, selectedResponseId }) =>
ResponseCardModal: ({ open, setOpen }: any) =>
open ? (
<div data-testid="response-card-modal">
Selected Response ID: {selectedResponseId}
<button onClick={() => setOpen(false)}>Close ResponseCardModal</button>
<div data-testid="response-modal">
Response Modal <button onClick={() => setOpen(false)}>Close</button>
</div>
) : null
),
) : null,
})
);
vi.mock(
"@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponseTableCell",
() => ({
ResponseTableCell: vi.fn(({ cell, row, setSelectedResponseId }) => (
<td data-testid={`cell-${cell.id}`} onClick={() => setSelectedResponseId(row.original.responseId)}>
{typeof cell.getValue === "function" ? cell.getValue() : JSON.stringify(cell.getValue())}
ResponseTableCell: ({ cell, row, setSelectedResponseId }: any) => (
<td data-testid={`cell-${cell.id}-${row.id}`} onClick={() => setSelectedResponseId(row.id)}>
Cell Content
</td>
)),
),
})
);
const mockGeneratedColumns = [
{
id: "select",
header: () => "Select",
cell: vi.fn(() => "SelectCell"),
enableSorting: false,
meta: { type: "select", questionType: null, hidden: false },
},
{
id: "createdAt",
header: () => "Created At",
cell: vi.fn(({ row }) => new Date(row.original.createdAt).toISOString()),
enableSorting: true,
meta: { type: "createdAt", questionType: null, hidden: false },
},
{
id: "q1",
header: () => "Question 1",
cell: vi.fn(({ row }) => row.original.responseData.q1),
enableSorting: true,
meta: { type: "question", questionType: "openText", hidden: false },
},
];
vi.mock(
"@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponseTableColumns",
() => ({
generateResponseTableColumns: vi.fn(() => mockGeneratedColumns),
generateResponseTableColumns: vi.fn(() => [
{ id: "select", accessorKey: "select", header: "Select" },
{ id: "createdAt", accessorKey: "createdAt", header: "Created At" },
{ id: "person", accessorKey: "person", header: "Person" },
{ id: "status", accessorKey: "status", header: "Status" },
]),
})
);
vi.mock("@/modules/ui/components/table", () => ({
Table: ({ children, ...props }: any) => <table {...props}>{children}</table>,
TableBody: ({ children, ...props }: any) => <tbody {...props}>{children}</tbody>,
TableCell: ({ children, ...props }: any) => <td {...props}>{children}</td>,
TableHeader: ({ children, ...props }: any) => <thead {...props}>{children}</thead>,
TableRow: ({ children, ...props }: any) => <tr {...props}>{children}</tr>,
}));
vi.mock("@/modules/ui/components/skeleton", () => ({
Skeleton: ({ children }: any) => <div data-testid="skeleton">{children}</div>,
}));
// Mock the actions
vi.mock("@/app/(app)/environments/[environmentId]/surveys/[surveyId]/actions", () => ({
getResponsesDownloadUrlAction: vi.fn(),
}));
vi.mock("@/modules/analysis/components/SingleResponseCard/actions", () => ({
deleteResponseAction: vi.fn(),
}));
vi.mock("@/modules/ui/components/data-table", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/modules/ui/components/data-table")>();
return {
...actual,
DataTableToolbar: vi.fn((props) => (
<div data-testid="data-table-toolbar">
<button data-testid="toolbar-expand-toggle" onClick={() => props.setIsExpanded(!props.isExpanded)}>
Toggle Expand
</button>
<button data-testid="toolbar-open-settings" onClick={() => props.setIsTableSettingsModalOpen(true)}>
Open Settings
</button>
<button
data-testid="toolbar-delete-selected"
onClick={() => props.deleteRows(props.table.getSelectedRowModel().rows.map((r) => r.id))}>
Delete Selected
</button>
<button data-testid="toolbar-delete-single" onClick={() => props.deleteAction("single_response_id")}>
Delete Single Action
</button>
</div>
)),
DataTableHeader: vi.fn(({ header }) => (
<th
data-testid={`header-${header.id}`}
onClick={() => header.column.getToggleSortingHandler()?.(new MouseEvent("click"))}>
{typeof header.column.columnDef.header === "function"
? header.column.columnDef.header(header.getContext())
: header.column.columnDef.header}
<button
onMouseDown={header.getResizeHandler()}
onTouchStart={header.getResizeHandler()}
data-testid={`resize-${header.id}`}>
Resize
</button>
</th>
)),
DataTableSettingsModal: vi.fn(({ open, setOpen }) =>
open ? (
<div data-testid="data-table-settings-modal">
<button onClick={() => setOpen(false)}>Close Settings</button>
</div>
) : null
),
};
});
vi.mock("@formkit/auto-animate/react", () => ({
useAutoAnimate: vi.fn(() => [vi.fn()]),
// Mock helper functions
vi.mock("@/lib/utils/helper", () => ({
getFormattedErrorMessage: vi.fn(),
}));
vi.mock("@tolgee/react", () => ({
useTranslate: () => ({
t: vi.fn((key) => key), // Simple pass-through mock
}),
}));
const localStorageMock = (() => {
// Mock localStorage
const mockLocalStorage = (() => {
let store: Record<string, string> = {};
return {
getItem: vi.fn((key: string) => store[key] || null),
setItem: vi.fn((key: string, value: string) => {
store[key] = value.toString();
getItem: vi.fn((key) => store[key] || null),
setItem: vi.fn((key, value) => {
store[key] = String(value);
}),
clear: () => {
clear: vi.fn(() => {
store = {};
},
removeItem: vi.fn((key: string) => {
}),
removeItem: vi.fn((key) => {
delete store[key];
}),
};
})();
Object.defineProperty(window, "localStorage", { value: localStorageMock });
Object.defineProperty(window, "localStorage", { value: mockLocalStorage });
const mockSurvey = {
id: "survey1",
name: "Test Survey",
type: "app",
status: "inProgress",
questions: [
{
id: "q1",
type: TSurveyQuestionTypeEnum.OpenText,
headline: { default: "Question 1" },
required: true,
} as unknown as TSurveyQuestion,
],
hiddenFields: { enabled: true, fieldIds: ["hidden1"] },
variables: [{ id: "var1", name: "Variable 1", type: "text", value: "default" }],
createdAt: new Date(),
updatedAt: new Date(),
environmentId: "env1",
welcomeCard: {
enabled: false,
headline: { default: "" },
html: { default: "" },
timeToFinish: false,
showResponseCount: false,
},
autoClose: null,
delay: 0,
autoComplete: null,
closeOnDate: null,
displayOption: "displayOnce",
recontactDays: null,
singleUse: { enabled: false, isEncrypted: true },
triggers: [],
languages: [],
styling: null,
surveyClosedMessage: null,
resultShareKey: null,
displayPercentage: null,
} as unknown as TSurvey;
// Mock Tolgee
vi.mock("@tolgee/react", () => ({
useTranslate: () => ({
t: (key: string) => key,
}),
}));
const mockResponses: TResponse[] = [
{
id: "res1",
surveyId: "survey1",
finished: true,
data: { q1: "Response 1 Text" },
createdAt: new Date("2023-01-01T10:00:00.000Z"),
// Define mock data for tests
const mockProps = {
data: [
{ responseId: "resp1", createdAt: new Date().toISOString(), status: "completed", person: "Person 1" },
{ responseId: "resp2", createdAt: new Date().toISOString(), status: "completed", person: "Person 2" },
] as any[],
survey: {
id: "survey1",
createdAt: new Date(),
updatedAt: new Date(),
meta: {},
singleUseId: null,
ttc: {},
tags: [],
notes: [],
variables: {},
language: "en",
contact: null,
contactAttributes: null,
},
{
id: "res2",
surveyId: "survey1",
finished: false,
data: { q1: "Response 2 Text" },
createdAt: new Date("2023-01-02T10:00:00.000Z"),
updatedAt: new Date(),
meta: {},
singleUseId: null,
ttc: {},
tags: [],
notes: [],
variables: {},
language: "en",
contact: null,
contactAttributes: null,
},
];
const mockResponseTableData: TResponseTableData[] = [
{
responseId: "res1",
responseData: { q1: "Response 1 Text" },
createdAt: new Date("2023-01-01T10:00:00.000Z"),
status: "Completed",
tags: [],
notes: [],
variables: {},
verifiedEmail: "",
language: "en",
person: null,
contactAttributes: null,
},
{
responseId: "res2",
responseData: { q1: "Response 2 Text" },
createdAt: new Date("2023-01-02T10:00:00.000Z"),
status: "Not Completed",
tags: [],
notes: [],
variables: {},
verifiedEmail: "",
language: "en",
person: null,
contactAttributes: null,
},
];
const mockEnvironment = {
id: "env1",
createdAt: new Date(),
updatedAt: new Date(),
type: "development",
appSetupCompleted: false,
} as unknown as TEnvironment;
const mockUser = {
id: "user1",
name: "Test User",
email: "user@test.com",
emailVerified: new Date(),
imageUrl: "",
twoFactorEnabled: false,
identityProvider: "email",
createdAt: new Date(),
updatedAt: new Date(),
role: "project_manager",
objective: "other",
notificationSettings: { alert: {}, weeklySummary: {} },
} as unknown as TUser;
const mockEnvironmentTags: TTag[] = [
{ id: "tag1", name: "Tag 1", environmentId: "env1", createdAt: new Date(), updatedAt: new Date() },
];
const mockLocale: TUserLocale = "en-US";
const defaultProps = {
data: mockResponseTableData,
survey: mockSurvey,
responses: mockResponses,
environment: mockEnvironment,
user: mockUser,
environmentTags: mockEnvironmentTags,
name: "name",
type: "link",
environmentId: "env-1",
createdBy: null,
status: "draft",
} as TSurvey,
responses: [
{ id: "resp1", surveyId: "survey1", data: {}, createdAt: new Date(), updatedAt: new Date() },
{ id: "resp2", surveyId: "survey1", data: {}, createdAt: new Date(), updatedAt: new Date() },
] as TResponse[],
environment: { id: "env1" } as TEnvironment,
environmentTags: [] as TTag[],
isReadOnly: false,
fetchNextPage: vi.fn(),
hasMore: true,
hasMore: false,
deleteResponses: vi.fn(),
updateResponse: vi.fn(),
isFetchingFirstPage: false,
locale: mockLocale,
locale: "en" as TUserLocale,
};
// Setup a container for React Testing Library before each test
beforeEach(() => {
const container = document.createElement("div");
container.id = "test-container";
document.body.appendChild(container);
// Reset all toast mocks before each test
vi.mocked(toast.error).mockClear();
vi.mocked(toast.success).mockClear();
// Create a mock anchor element for download tests
const mockAnchor = {
href: "",
click: vi.fn(),
style: {},
};
// Update how we mock the document methods to avoid infinite recursion
const originalCreateElement = document.createElement.bind(document);
vi.spyOn(document, "createElement").mockImplementation((tagName) => {
if (tagName === "a") return mockAnchor as any;
return originalCreateElement(tagName);
});
vi.spyOn(document.body, "appendChild").mockReturnValue(null as any);
vi.spyOn(document.body, "removeChild").mockReturnValue(null as any);
});
// Cleanup after each test
afterEach(() => {
const container = document.getElementById("test-container");
if (container) {
document.body.removeChild(container);
}
cleanup();
vi.restoreAllMocks(); // Restore mocks after each test
});
describe("ResponseTable", () => {
afterEach(() => {
cleanup();
localStorageMock.clear();
vi.clearAllMocks();
cleanup(); // Keep cleanup within describe as per instructions
});
test("renders skeleton when isFetchingFirstPage is true", () => {
render(<ResponseTable {...defaultProps} isFetchingFirstPage={true} />);
// Check for skeleton elements (implementation detail, might need adjustment)
// For now, check that data is not directly rendered
expect(screen.queryByText("Response 1 Text")).not.toBeInTheDocument();
// Check if table headers are still there
expect(screen.getByText("Created At")).toBeInTheDocument();
test("renders the table with data", () => {
const container = document.getElementById("test-container");
render(<ResponseTable {...mockProps} />, { container: container! });
expect(screen.getByRole("table")).toBeInTheDocument();
expect(screen.getByTestId("table-toolbar")).toBeInTheDocument();
});
test("loads settings from localStorage on mount", () => {
const savedOrder = ["q1", "createdAt", "select"];
const savedVisibility = { createdAt: false };
const savedExpanded = true;
localStorageMock.setItem(`${mockSurvey.id}-columnOrder`, JSON.stringify(savedOrder));
localStorageMock.setItem(`${mockSurvey.id}-columnVisibility`, JSON.stringify(savedVisibility));
localStorageMock.setItem(`${mockSurvey.id}-rowExpand`, JSON.stringify(savedExpanded));
render(<ResponseTable {...defaultProps} />);
// Check if generateResponseTableColumns was called with the loaded expanded state
expect(vi.mocked(generateResponseTableColumns)).toHaveBeenCalledWith(
mockSurvey,
savedExpanded,
false,
expect.any(Function)
);
});
test("saves settings to localStorage when they change", async () => {
const { rerender } = render(<ResponseTable {...defaultProps} />);
// Simulate column order change via DND
const dragEvent: DragEndEvent = {
active: { id: "createdAt" },
over: { id: "q1" },
delta: { x: 0, y: 0 },
activators: { x: 0, y: 0 },
collisions: null,
overNode: null,
activeNode: null,
} as any;
act(() => {
(DndContextMock as any).lastOnDragEnd?.(dragEvent);
});
rerender(<ResponseTable {...defaultProps} />); // Rerender to reflect state change if necessary for useEffect
expect(localStorageMock.setItem).toHaveBeenCalledWith(
`${mockSurvey.id}-columnOrder`,
JSON.stringify(["select", "q1", "createdAt"])
);
// Simulate visibility change (e.g. via settings modal - direct state change for test)
// This would typically happen via table.setColumnVisibility, which is internal to useReactTable
// For this test, we'll assume a mechanism changes columnVisibility state
// This part is hard to test without deeper mocking of useReactTable or exposing setColumnVisibility
// Simulate row expansion change
await userEvent.click(screen.getByTestId("toolbar-expand-toggle")); // Toggle to true
expect(localStorageMock.setItem).toHaveBeenCalledWith(`${mockSurvey.id}-rowExpand`, "true");
});
test("handles column drag and drop", () => {
render(<ResponseTable {...defaultProps} />);
const dragEvent: DragEndEvent = {
active: { id: "createdAt" },
over: { id: "q1" },
delta: { x: 0, y: 0 },
activators: { x: 0, y: 0 },
collisions: null,
overNode: null,
activeNode: null,
} as any;
act(() => {
(DndContextMock as any).lastOnDragEnd?.(dragEvent);
});
expect(arrayMoveMock).toHaveBeenCalledWith(expect.arrayContaining(["createdAt", "q1"]), 1, 2); // Example indices
expect(localStorageMock.setItem).toHaveBeenCalledWith(
`${mockSurvey.id}-columnOrder`,
JSON.stringify(["select", "q1", "createdAt"]) // Based on initial ['select', 'createdAt', 'q1']
);
});
test("interacts with DataTableToolbar: toggle expand, open settings, delete", async () => {
const deleteResponsesMock = vi.fn();
const deleteResponseActionMock = vi.mocked(deleteResponseAction);
render(<ResponseTable {...defaultProps} deleteResponses={deleteResponsesMock} />);
// Toggle expand
await userEvent.click(screen.getByTestId("toolbar-expand-toggle"));
expect(vi.mocked(generateResponseTableColumns)).toHaveBeenCalledWith(
mockSurvey,
true,
false,
expect.any(Function)
);
expect(localStorageMock.setItem).toHaveBeenCalledWith(`${mockSurvey.id}-rowExpand`, "true");
// Open settings
await userEvent.click(screen.getByTestId("toolbar-open-settings"));
expect(screen.getByTestId("data-table-settings-modal")).toBeInTheDocument();
await userEvent.click(screen.getByText("Close Settings"));
expect(screen.queryByTestId("data-table-settings-modal")).not.toBeInTheDocument();
// Delete selected (mock table selection)
// This requires mocking table.getSelectedRowModel().rows
// For simplicity, we assume the toolbar button calls deleteRows correctly
// The mock for DataTableToolbar calls props.deleteRows with hardcoded IDs for now.
// To test properly, we'd need to mock table.getSelectedRowModel
// For now, let's assume the mock toolbar calls it.
// await userEvent.click(screen.getByTestId("toolbar-delete-selected"));
// expect(deleteResponsesMock).toHaveBeenCalledWith(["row1_id", "row2_id"]); // From mock toolbar
// Delete single action
await userEvent.click(screen.getByTestId("toolbar-delete-single"));
expect(deleteResponseActionMock).toHaveBeenCalledWith({ responseId: "single_response_id" });
});
test("calls fetchNextPage when 'Load More' is clicked", async () => {
const fetchNextPageMock = vi.fn();
render(<ResponseTable {...defaultProps} fetchNextPage={fetchNextPageMock} />);
await userEvent.click(screen.getByText("common.load_more"));
expect(fetchNextPageMock).toHaveBeenCalled();
});
test("does not show 'Load More' if hasMore is false", () => {
render(<ResponseTable {...defaultProps} hasMore={false} />);
expect(screen.queryByText("common.load_more")).not.toBeInTheDocument();
});
test("shows 'No results' when data is empty", () => {
render(<ResponseTable {...defaultProps} data={[]} responses={[]} />);
test("renders no results message when data is empty", () => {
const container = document.getElementById("test-container");
render(<ResponseTable {...mockProps} data={[]} responses={[]} />, { container: container! });
expect(screen.getByText("common.no_results")).toBeInTheDocument();
});
test("deleteResponse function calls deleteResponseAction", async () => {
render(<ResponseTable {...defaultProps} />);
// This function is called by DataTableToolbar's deleteAction prop
// We can trigger it via the mocked DataTableToolbar
await userEvent.click(screen.getByTestId("toolbar-delete-single"));
expect(vi.mocked(deleteResponseAction)).toHaveBeenCalledWith({ responseId: "single_response_id" });
test("renders load more button when hasMore is true", () => {
const container = document.getElementById("test-container");
render(<ResponseTable {...mockProps} hasMore={true} />, { container: container! });
expect(screen.getByText("common.load_more")).toBeInTheDocument();
});
test("calls fetchNextPage when load more button is clicked", async () => {
const container = document.getElementById("test-container");
render(<ResponseTable {...mockProps} hasMore={true} />, { container: container! });
const loadMoreButton = screen.getByText("common.load_more");
await userEvent.click(loadMoreButton);
expect(mockProps.fetchNextPage).toHaveBeenCalledTimes(1);
});
test("opens settings modal when toolbar button is clicked", async () => {
const container = document.getElementById("test-container");
render(<ResponseTable {...mockProps} />, { container: container! });
const openSettingsButton = screen.getByTestId("open-settings");
await userEvent.click(openSettingsButton);
expect(screen.getByTestId("settings-modal")).toBeInTheDocument();
});
test("toggles expanded state when toolbar button is clicked", async () => {
const container = document.getElementById("test-container");
render(<ResponseTable {...mockProps} />, { container: container! });
const toggleExpandButton = screen.getByTestId("toggle-expand");
// Initially might be null, first click should set it to true
await userEvent.click(toggleExpandButton);
expect(mockLocalStorage.setItem).toHaveBeenCalledWith("survey1-rowExpand", expect.any(String));
});
test("calls downloadSelectedRows with csv format when toolbar button is clicked", async () => {
vi.mocked(getResponsesDownloadUrlAction).mockResolvedValueOnce({
data: "https://download.url/file.csv",
});
const container = document.getElementById("test-container");
render(<ResponseTable {...mockProps} />, { container: container! });
const downloadCsvButton = screen.getByTestId("download-csv");
await userEvent.click(downloadCsvButton);
expect(getResponsesDownloadUrlAction).toHaveBeenCalledWith({
surveyId: "survey1",
format: "csv",
filterCriteria: { responseIds: [] },
});
// Check if link was created and clicked
expect(document.createElement).toHaveBeenCalledWith("a");
const mockLink = document.createElement("a");
expect(mockLink.href).toBe("https://download.url/file.csv");
expect(document.body.appendChild).toHaveBeenCalled();
expect(mockLink.click).toHaveBeenCalled();
expect(document.body.removeChild).toHaveBeenCalled();
});
test("calls downloadSelectedRows with xlsx format when toolbar button is clicked", async () => {
vi.mocked(getResponsesDownloadUrlAction).mockResolvedValueOnce({
data: "https://download.url/file.xlsx",
});
const container = document.getElementById("test-container");
render(<ResponseTable {...mockProps} />, { container: container! });
const downloadXlsxButton = screen.getByTestId("download-xlsx");
await userEvent.click(downloadXlsxButton);
expect(getResponsesDownloadUrlAction).toHaveBeenCalledWith({
surveyId: "survey1",
format: "xlsx",
filterCriteria: { responseIds: [] },
});
// Check if link was created and clicked
expect(document.createElement).toHaveBeenCalledWith("a");
const mockLink = document.createElement("a");
expect(mockLink.href).toBe("https://download.url/file.xlsx");
expect(document.body.appendChild).toHaveBeenCalled();
expect(mockLink.click).toHaveBeenCalled();
expect(document.body.removeChild).toHaveBeenCalled();
});
// Test response modal
test("opens and closes response modal when a cell is clicked", async () => {
const container = document.getElementById("test-container");
render(<ResponseTable {...mockProps} />, { container: container! });
const cell = screen.getByTestId("cell-resp1_select-resp1");
await userEvent.click(cell);
expect(screen.getByTestId("response-modal")).toBeInTheDocument();
// Close the modal
const closeButton = screen.getByText("Close");
await userEvent.click(closeButton);
// Modal should be closed now
expect(screen.queryByTestId("response-modal")).not.toBeInTheDocument();
});
test("shows error toast when download action returns error", async () => {
const errorMsg = "Download failed";
vi.mocked(getResponsesDownloadUrlAction).mockResolvedValueOnce({
data: undefined,
serverError: errorMsg,
});
vi.mocked(getFormattedErrorMessage).mockReturnValueOnce(errorMsg);
// Reset document.createElement spy to fix the last test
vi.mocked(document.createElement).mockClear();
const container = document.getElementById("test-container");
render(<ResponseTable {...mockProps} />, { container: container! });
const downloadCsvButton = screen.getByTestId("download-csv");
await userEvent.click(downloadCsvButton);
await waitFor(() => {
expect(getResponsesDownloadUrlAction).toHaveBeenCalled();
expect(toast.error).toHaveBeenCalledWith("environments.surveys.responses.error_downloading_responses");
});
});
test("shows default error toast when download action returns no data", async () => {
vi.mocked(getResponsesDownloadUrlAction).mockResolvedValueOnce({
data: undefined,
});
vi.mocked(getFormattedErrorMessage).mockReturnValueOnce("");
const container = document.getElementById("test-container");
render(<ResponseTable {...mockProps} />, { container: container! });
const downloadCsvButton = screen.getByTestId("download-csv");
await userEvent.click(downloadCsvButton);
await waitFor(() => {
expect(getResponsesDownloadUrlAction).toHaveBeenCalled();
expect(toast.error).toHaveBeenCalledWith("environments.surveys.responses.error_downloading_responses");
});
});
test("shows error toast when download action throws exception", async () => {
vi.mocked(getResponsesDownloadUrlAction).mockRejectedValueOnce(new Error("Network error"));
const container = document.getElementById("test-container");
render(<ResponseTable {...mockProps} />, { container: container! });
const downloadCsvButton = screen.getByTestId("download-csv");
await userEvent.click(downloadCsvButton);
await waitFor(() => {
expect(getResponsesDownloadUrlAction).toHaveBeenCalled();
expect(toast.error).toHaveBeenCalledWith("environments.surveys.responses.error_downloading_responses");
});
});
test("does not create download link when download action fails", async () => {
// Clear any previous calls to document.createElement
vi.mocked(document.createElement).mockClear();
vi.mocked(getResponsesDownloadUrlAction).mockResolvedValueOnce({
data: undefined,
serverError: "Download failed",
});
// Create a fresh spy for createElement for this test only
const createElementSpy = vi.spyOn(document, "createElement");
const container = document.getElementById("test-container");
render(<ResponseTable {...mockProps} />, { container: container! });
const downloadCsvButton = screen.getByTestId("download-csv");
await userEvent.click(downloadCsvButton);
await waitFor(() => {
expect(getResponsesDownloadUrlAction).toHaveBeenCalled();
// Check specifically for "a" element creation, not any element
expect(createElementSpy).not.toHaveBeenCalledWith("a");
});
});
test("loads saved settings from localStorage on mount", () => {
const columnOrder = ["status", "person", "createdAt", "select"];
const columnVisibility = { status: false };
const isExpanded = true;
mockLocalStorage.getItem.mockImplementation((key) => {
if (key === "survey1-columnOrder") return JSON.stringify(columnOrder);
if (key === "survey1-columnVisibility") return JSON.stringify(columnVisibility);
if (key === "survey1-rowExpand") return JSON.stringify(isExpanded);
return null;
});
const container = document.getElementById("test-container");
render(<ResponseTable {...mockProps} />, { container: container! });
// Verify localStorage calls
expect(mockLocalStorage.getItem).toHaveBeenCalledWith("survey1-columnOrder");
expect(mockLocalStorage.getItem).toHaveBeenCalledWith("survey1-columnVisibility");
expect(mockLocalStorage.getItem).toHaveBeenCalledWith("survey1-rowExpand");
// The mock for generateResponseTableColumns returns this order:
// ["select", "createdAt", "person", "status"]
// Only visible columns should be rendered, in this order
const expectedHeaders = ["select", "createdAt", "person"];
const headers = screen.getAllByTestId(/^header-/);
expect(headers).toHaveLength(expectedHeaders.length);
expectedHeaders.forEach((columnId, index) => {
expect(headers[index]).toHaveAttribute("data-testid", `header-${columnId}`);
});
// Verify column visibility is applied
const statusHeader = screen.queryByTestId("header-status");
expect(statusHeader).not.toBeInTheDocument();
// Verify row expansion is applied
const toggleExpandButton = screen.getByTestId("toggle-expand");
expect(toggleExpandButton).toHaveAttribute("aria-pressed", "true");
});
});

View File

@@ -3,6 +3,7 @@
import { ResponseCardModal } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponseCardModal";
import { ResponseTableCell } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponseTableCell";
import { generateResponseTableColumns } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponseTableColumns";
import { getResponsesDownloadUrlAction } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/actions";
import { deleteResponseAction } from "@/modules/analysis/components/SingleResponseCard/actions";
import { Button } from "@/modules/ui/components/button";
import {
@@ -25,15 +26,16 @@ import {
import { restrictToHorizontalAxis } from "@dnd-kit/modifiers";
import { SortableContext, arrayMove, horizontalListSortingStrategy } from "@dnd-kit/sortable";
import { useAutoAnimate } from "@formkit/auto-animate/react";
import * as Sentry from "@sentry/nextjs";
import { VisibilityState, getCoreRowModel, useReactTable } from "@tanstack/react-table";
import { useTranslate } from "@tolgee/react";
import { useEffect, useMemo, useState } from "react";
import toast from "react-hot-toast";
import { TEnvironment } from "@formbricks/types/environment";
import { TResponse, TResponseTableData } from "@formbricks/types/responses";
import { TSurvey } from "@formbricks/types/surveys/types";
import { TTag } from "@formbricks/types/tags";
import { TUser } from "@formbricks/types/user";
import { TUserLocale } from "@formbricks/types/user";
import { TUser, TUserLocale } from "@formbricks/types/user";
interface ResponseTableProps {
data: TResponseTableData[];
@@ -180,6 +182,32 @@ export const ResponseTable = ({
await deleteResponseAction({ responseId });
};
// Handle downloading selected responses
const downloadSelectedRows = async (responseIds: string[], format: "csv" | "xlsx") => {
try {
const downloadResponse = await getResponsesDownloadUrlAction({
surveyId: survey.id,
format: format,
filterCriteria: { responseIds },
});
if (downloadResponse?.data) {
const link = document.createElement("a");
link.href = downloadResponse.data;
link.download = "";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} else {
toast.error(t("environments.surveys.responses.error_downloading_responses"));
}
} catch (error) {
Sentry.captureException(error);
toast.error(t("environments.surveys.responses.error_downloading_responses"));
}
};
return (
<div>
<DndContext
@@ -193,9 +221,10 @@ export const ResponseTable = ({
setIsTableSettingsModalOpen={setIsTableSettingsModalOpen}
isExpanded={isExpanded ?? false}
table={table}
deleteRows={deleteResponses}
deleteRowsAction={deleteResponses}
type="response"
deleteAction={deleteResponse}
downloadRowsAction={downloadSelectedRows}
/>
<div className="w-fit max-w-full overflow-hidden overflow-x-auto rounded-xl border border-slate-200">
<div className="w-full overflow-x-auto">

View File

@@ -28,7 +28,7 @@ export const useSurveyQRCode = (surveyUrl: string) => {
} catch (error) {
toast.error(t("environments.surveys.summary.failed_to_generate_qr_code"));
}
}, [surveyUrl]);
}, [surveyUrl, t]);
const downloadQRCode = () => {
try {

View File

@@ -250,6 +250,7 @@ export const CustomFilter = ({ survey }: CustomFilterProps) => {
if (responsesDownloadUrlResponse?.data) {
const link = document.createElement("a");
link.href = responsesDownloadUrlResponse.data;
link.download = "";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

View File

@@ -7,39 +7,133 @@ export const GET = async (req: NextRequest) => {
return new ImageResponse(
(
<div tw={`flex flex-col w-full h-full items-center bg-[${brandColor}]/75 rounded-xl `}>
<div
style={{
display: "flex",
flexDirection: "column",
width: "100%",
height: "100%",
alignItems: "center",
backgroundColor: brandColor ? brandColor + "BF" : "#0000BFBF", // /75 opacity is approximately BF in hex
borderRadius: "0.75rem",
}}>
<div
tw="flex flex-col w-[80%] h-[60%] bg-white rounded-xl mt-13 absolute left-12 top-3 opacity-20"
style={{
display: "flex",
flexDirection: "column",
width: "80%",
height: "60%",
backgroundColor: "white",
borderRadius: "0.75rem",
marginTop: "3.25rem",
position: "absolute",
left: "3rem",
top: "0.75rem",
opacity: 0.2,
transform: "rotate(356deg)",
}}></div>
<div
tw="flex flex-col w-[84%] h-[60%] bg-white rounded-xl mt-12 absolute top-5 left-13 border-2 opacity-60"
style={{
display: "flex",
flexDirection: "column",
width: "84%",
height: "60%",
backgroundColor: "white",
borderRadius: "0.75rem",
marginTop: "3rem",
position: "absolute",
top: "1.25rem",
left: "3.25rem",
borderWidth: "2px",
opacity: 0.6,
transform: "rotate(357deg)",
}}></div>
<div
tw="flex flex-col w-[85%] h-[67%] items-center bg-white rounded-xl mt-8 absolute top-[2.3rem] left-14"
style={{
display: "flex",
flexDirection: "column",
width: "85%",
height: "67%",
alignItems: "center",
backgroundColor: "white",
borderRadius: "0.75rem",
marginTop: "2rem",
position: "absolute",
top: "2.3rem",
left: "3.5rem",
transform: "rotate(360deg)",
}}>
<div tw="flex flex-col w-full">
<div tw="flex flex-col md:flex-row w-full md:items-center justify-between ">
<div tw="flex flex-col px-8">
<h2 tw="flex flex-col text-[8] sm:text-4xl font-bold tracking-tight text-slate-900 text-left mt-15">
<div style={{ display: "flex", flexDirection: "column", width: "100%" }}>
<div
style={{
display: "flex",
flexDirection: "column",
width: "100%",
justifyContent: "space-between",
}}>
<div
style={{
display: "flex",
flexDirection: "column",
paddingLeft: "2rem",
paddingRight: "2rem",
}}>
<h2
style={{
display: "flex",
flexDirection: "column",
fontSize: "2rem",
fontWeight: "700",
letterSpacing: "-0.025em",
color: "#0f172a",
textAlign: "left",
marginTop: "3.75rem",
}}>
{name}
</h2>
</div>
</div>
<div tw="flex justify-end mr-10 ">
<div tw="flex rounded-2xl absolute -right-2 mt-2">
<a tw={`rounded-xl border border-transparent bg-[${brandColor}] h-18 w-38 opacity-50`}></a>
<div style={{ display: "flex", justifyContent: "flex-end", marginRight: "2.5rem" }}>
<div
style={{
display: "flex",
borderRadius: "1rem",
position: "absolute",
right: "-0.5rem",
marginTop: "0.5rem",
}}>
<div
content=""
style={{
borderRadius: "0.75rem",
border: "1px solid transparent",
backgroundColor: brandColor ?? "#000",
height: "4.5rem",
width: "9.5rem",
opacity: 0.5,
}}></div>
</div>
<div tw="flex rounded-2xl shadow ">
<a
tw={`flex items-center justify-center rounded-xl border border-transparent bg-[${brandColor}] text-2xl text-white h-18 w-38`}>
<div
style={{
display: "flex",
borderRadius: "1rem",
boxShadow: "0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",
}}>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
borderRadius: "0.75rem",
border: "1px solid transparent",
backgroundColor: brandColor ?? "#000",
fontSize: "1.5rem",
color: "white",
height: "4.5rem",
width: "9.5rem",
}}>
Begin!
</a>
</div>
</div>
</div>
</div>

View File

@@ -38,7 +38,7 @@ describe("SentryProvider", () => {
expect(initSpy).toHaveBeenCalledWith(
expect.objectContaining({
dsn: sentryDsn,
tracesSampleRate: 1,
tracesSampleRate: 0,
debug: false,
replaysOnErrorSampleRate: 1.0,
replaysSessionSampleRate: 0.1,
@@ -81,6 +81,26 @@ describe("SentryProvider", () => {
expect(screen.getByTestId("child")).toHaveTextContent("Test Content");
});
test("does not reinitialize Sentry when props change after initial render", () => {
const initSpy = vi.spyOn(Sentry, "init").mockImplementation(() => undefined);
const { rerender } = render(
<SentryProvider sentryDsn={sentryDsn} isEnabled>
<div data-testid="child">Test Content</div>
</SentryProvider>
);
expect(initSpy).toHaveBeenCalledTimes(1);
rerender(
<SentryProvider sentryDsn="https://newDsn@o0.ingest.sentry.io/0" isEnabled={false}>
<div data-testid="child">Test Content</div>
</SentryProvider>
);
expect(initSpy).toHaveBeenCalledTimes(1);
});
test("processes beforeSend correctly", () => {
const initSpy = vi.spyOn(Sentry, "init").mockImplementation(() => undefined);
@@ -109,4 +129,36 @@ describe("SentryProvider", () => {
const hintWithoutError = { originalException: undefined };
expect(beforeSend(dummyEvent, hintWithoutError)).toEqual(dummyEvent);
});
test("processes beforeSend correctly when hint.originalException is not an Error object", () => {
const initSpy = vi.spyOn(Sentry, "init").mockImplementation(() => undefined);
render(
<SentryProvider sentryDsn={sentryDsn} isEnabled>
<div data-testid="child">Test Content</div>
</SentryProvider>
);
const config = initSpy.mock.calls[0][0];
expect(config).toHaveProperty("beforeSend");
const beforeSend = config.beforeSend;
if (!beforeSend) {
throw new Error("beforeSend is not defined");
}
const dummyEvent = { some: "event" } as unknown as Sentry.ErrorEvent;
const hintWithString = { originalException: "string exception" };
expect(() => beforeSend(dummyEvent, hintWithString)).not.toThrow();
expect(beforeSend(dummyEvent, hintWithString)).toEqual(dummyEvent);
const hintWithNumber = { originalException: 123 };
expect(() => beforeSend(dummyEvent, hintWithNumber)).not.toThrow();
expect(beforeSend(dummyEvent, hintWithNumber)).toEqual(dummyEvent);
const hintWithNull = { originalException: null };
expect(() => beforeSend(dummyEvent, hintWithNull)).not.toThrow();
expect(beforeSend(dummyEvent, hintWithNull)).toEqual(dummyEvent);
});
});

View File

@@ -15,8 +15,8 @@ export const SentryProvider = ({ children, sentryDsn, isEnabled }: SentryProvide
Sentry.init({
dsn: sentryDsn,
// Adjust this value in production, or use tracesSampler for greater control
tracesSampleRate: 1,
// No tracing while Sentry doesn't update to telemetry 2.0.0 - https://github.com/getsentry/sentry-javascript/issues/15737
tracesSampleRate: 0,
// Setting this option to true will print useful information to the console while you're setting up Sentry.
debug: false,

View File

@@ -282,4 +282,4 @@ export const SENTRY_DSN = env.SENTRY_DSN;
export const PROMETHEUS_ENABLED = env.PROMETHEUS_ENABLED === "1";
export const DISABLE_USER_MANAGEMENT = env.DISABLE_USER_MANAGEMENT === "1";
export const USER_MANAGEMENT_MINIMUM_ROLE = env.USER_MANAGEMENT_MINIMUM_ROLE ?? "manager";

View File

@@ -104,7 +104,7 @@ export const env = createEnv({
NODE_ENV: z.enum(["development", "production", "test"]).optional(),
PROMETHEUS_EXPORTER_PORT: z.string().optional(),
PROMETHEUS_ENABLED: z.enum(["1", "0"]).optional(),
DISABLE_USER_MANAGEMENT: z.enum(["1", "0"]).optional(),
USER_MANAGEMENT_MINIMUM_ROLE: z.enum(["owner", "manager", "disabled"]).optional(),
},
/*
@@ -199,6 +199,6 @@ export const env = createEnv({
NODE_ENV: process.env.NODE_ENV,
PROMETHEUS_ENABLED: process.env.PROMETHEUS_ENABLED,
PROMETHEUS_EXPORTER_PORT: process.env.PROMETHEUS_EXPORTER_PORT,
DISABLE_USER_MANAGEMENT: process.env.DISABLE_USER_MANAGEMENT,
USER_MANAGEMENT_MINIMUM_ROLE: process.env.USER_MANAGEMENT_MINIMUM_ROLE,
},
});

View File

@@ -13,3 +13,21 @@ export const getAccessFlags = (role?: TOrganizationRole) => {
isMember,
};
};
export const getUserManagementAccess = (
role: TOrganizationRole,
minimumRole: "owner" | "manager" | "disabled"
): boolean => {
// If minimum role is "disabled", no one has access
if (minimumRole === "disabled") {
return false;
}
if (minimumRole === "owner") {
return role === "owner";
}
if (minimumRole === "manager") {
return role === "owner" || role === "manager";
}
return false;
};

View File

@@ -22,6 +22,43 @@ export const calculateTtcTotal = (ttc: TResponseTtc) => {
return result;
};
const createFilterTags = (tags: TResponseFilterCriteria["tags"]) => {
if (!tags) return [];
const filterTags: Record<string, any>[] = [];
if (tags?.applied) {
const appliedTags = tags.applied.map((name) => ({
tags: {
some: {
tag: {
name,
},
},
},
}));
filterTags.push(appliedTags);
}
if (tags?.notApplied) {
const notAppliedTags = {
tags: {
every: {
tag: {
name: {
notIn: tags.notApplied,
},
},
},
},
};
filterTags.push(notAppliedTags);
}
return filterTags.flat();
};
export const buildWhereClause = (survey: TSurvey, filterCriteria?: TResponseFilterCriteria) => {
const whereClause: Prisma.ResponseWhereInput["AND"] = [];
@@ -49,39 +86,9 @@ export const buildWhereClause = (survey: TSurvey, filterCriteria?: TResponseFilt
// For Tags
if (filterCriteria?.tags) {
const tags: Record<string, any>[] = [];
if (filterCriteria?.tags?.applied) {
const appliedTags = filterCriteria.tags.applied.map((name) => ({
tags: {
some: {
tag: {
name,
},
},
},
}));
tags.push(appliedTags);
}
if (filterCriteria?.tags?.notApplied) {
const notAppliedTags = {
tags: {
every: {
tag: {
name: {
notIn: filterCriteria.tags.notApplied,
},
},
},
},
};
tags.push(notAppliedTags);
}
const tagFilters = createFilterTags(filterCriteria.tags);
whereClause.push({
AND: tags.flat(),
AND: tagFilters,
});
}
@@ -442,6 +449,13 @@ export const buildWhereClause = (survey: TSurvey, filterCriteria?: TResponseFilt
AND: data,
});
}
// filter by explicit response IDs
if (filterCriteria?.responseIds) {
whereClause.push({
id: { in: filterCriteria.responseIds },
});
}
return { AND: whereClause };
};

View File

@@ -15,12 +15,20 @@ import {
describe("Time Utilities", () => {
describe("convertDateString", () => {
test("should format date string correctly", () => {
expect(convertDateString("2024-03-20")).toBe("Mar 20, 2024");
expect(convertDateString("2024-03-20:12:30:00")).toBe("Mar 20, 2024");
});
test("should return empty string for empty input", () => {
expect(convertDateString("")).toBe("");
});
test("should return null for null input", () => {
expect(convertDateString(null as any)).toBe(null);
});
test("should handle invalid date strings", () => {
expect(convertDateString("not-a-date")).toBe("Invalid Date");
});
});
describe("convertDateTimeString", () => {
@@ -73,7 +81,7 @@ describe("Time Utilities", () => {
describe("formatDate", () => {
test("should format date correctly", () => {
const date = new Date("2024-03-20");
const date = new Date(2024, 2, 20); // March is month 2 (0-based)
expect(formatDate(date)).toBe("March 20, 2024");
});
});

View File

@@ -2,11 +2,16 @@ import { formatDistance, intlFormat } from "date-fns";
import { de, enUS, fr, pt, ptBR, zhTW } from "date-fns/locale";
import { TUserLocale } from "@formbricks/types/user";
export const convertDateString = (dateString: string) => {
export const convertDateString = (dateString: string | null) => {
if (dateString === null) return null;
if (!dateString) {
return dateString;
}
const date = new Date(dateString);
if (isNaN(date.getTime())) {
return "Invalid Date";
}
return intlFormat(
date,
{

View File

@@ -1,5 +1,6 @@
import { getUser } from "@/lib/user/service";
import { authOptions } from "@/modules/auth/lib/authOptions";
import * as Sentry from "@sentry/nextjs";
import { getServerSession } from "next-auth";
import { DEFAULT_SERVER_ERROR_MESSAGE, createSafeActionClient } from "next-safe-action";
import { logger } from "@formbricks/logger";
@@ -14,6 +15,8 @@ import {
export const actionClient = createSafeActionClient({
handleServerError(e) {
Sentry.captureException(e);
if (
e instanceof ResourceNotFoundError ||
e instanceof AuthorizationError ||

View File

@@ -1,4 +1,4 @@
import { useEffect, useRef } from "react";
import { useCallback, useEffect, useRef } from "react";
export const useIntervalWhenFocused = (
callback: () => void,
@@ -8,7 +8,7 @@ export const useIntervalWhenFocused = (
) => {
const intervalRef = useRef<NodeJS.Timeout | null>(null);
const handleFocus = () => {
const handleFocus = useCallback(() => {
if (isActive) {
if (shouldExecuteImmediately) {
// Execute the callback immediately when the tab comes into focus
@@ -20,7 +20,7 @@ export const useIntervalWhenFocused = (
callback();
}, intervalDuration);
}
};
}, [isActive, intervalDuration, callback, shouldExecuteImmediately]);
const handleBlur = () => {
// Clear the interval when the tab loses focus
@@ -46,7 +46,7 @@ export const useIntervalWhenFocused = (
window.removeEventListener("focus", handleFocus);
window.removeEventListener("blur", handleBlur);
};
}, [isActive, intervalDuration]);
}, [isActive, intervalDuration, handleFocus]);
};
export default useIntervalWhenFocused;

View File

@@ -1667,6 +1667,7 @@
"device": "Gerät",
"device_info": "Geräteinfo",
"email": "E-Mail",
"error_downloading_responses": "Beim Herunterladen der Antworten ist ein Fehler aufgetreten",
"first_name": "Vorname",
"how_to_identify_users": "Wie man Benutzer identifiziert",
"last_name": "Nachname",
@@ -1764,6 +1765,8 @@
"quickstart_web_apps": "Schnellstart: Web-Apps",
"quickstart_web_apps_description": "Bitte folge der Schnellstartanleitung, um loszulegen:",
"results_are_public": "Ergebnisse sind öffentlich",
"selected_responses_csv": "Ausgewählte Antworten (CSV)",
"selected_responses_excel": "Ausgewählte Antworten (Excel)",
"send_preview": "Vorschau senden",
"send_to_panel": "An das Panel senden",
"setup_instructions": "Einrichtung",

View File

@@ -1667,6 +1667,7 @@
"device": "Device",
"device_info": "Device info",
"email": "Email",
"error_downloading_responses": "An error occured while downloading responses",
"first_name": "First Name",
"how_to_identify_users": "How to identify users",
"last_name": "Last Name",
@@ -1764,6 +1765,8 @@
"quickstart_web_apps": "Quickstart: Web apps",
"quickstart_web_apps_description": "Please follow the Quickstart guide to get started:",
"results_are_public": "Results are public",
"selected_responses_csv": "Selected responses (CSV)",
"selected_responses_excel": "Selected responses (Excel)",
"send_preview": "Send preview",
"send_to_panel": "Send to panel",
"setup_instructions": "Setup instructions",

View File

@@ -1667,6 +1667,7 @@
"device": "Dispositif",
"device_info": "Informations sur l'appareil",
"email": "Email",
"error_downloading_responses": "Une erreur s'est produite lors du téléchargement des réponses",
"first_name": "Prénom",
"how_to_identify_users": "Comment identifier les utilisateurs",
"last_name": "Nom de famille",
@@ -1764,6 +1765,8 @@
"quickstart_web_apps": "Démarrage rapide : Applications web",
"quickstart_web_apps_description": "Veuillez suivre le guide de démarrage rapide pour commencer :",
"results_are_public": "Les résultats sont publics.",
"selected_responses_csv": "Réponses sélectionnées (CSV)",
"selected_responses_excel": "Réponses sélectionnées (Excel)",
"send_preview": "Envoyer un aperçu",
"send_to_panel": "Envoyer au panneau",
"setup_instructions": "Instructions d'installation",

View File

@@ -1667,6 +1667,7 @@
"device": "dispositivo",
"device_info": "Informações do dispositivo",
"email": "Email",
"error_downloading_responses": "Ocorreu um erro ao baixar respostas",
"first_name": "Primeiro Nome",
"how_to_identify_users": "Como identificar usuários",
"last_name": "Sobrenome",
@@ -1764,6 +1765,8 @@
"quickstart_web_apps": "Início rápido: Aplicativos web",
"quickstart_web_apps_description": "Por favor, siga o guia de início rápido para começar:",
"results_are_public": "Os resultados são públicos",
"selected_responses_csv": "Respostas selecionadas (CSV)",
"selected_responses_excel": "Respostas selecionadas (Excel)",
"send_preview": "Enviar prévia",
"send_to_panel": "Enviar para o painel",
"setup_instructions": "Instruções de configuração",

View File

@@ -1667,6 +1667,7 @@
"device": "Dispositivo",
"device_info": "Informações do dispositivo",
"email": "Email",
"error_downloading_responses": "Ocorreu um erro ao transferir respostas",
"first_name": "Primeiro Nome",
"how_to_identify_users": "Como identificar utilizadores",
"last_name": "Apelido",
@@ -1764,6 +1765,8 @@
"quickstart_web_apps": "Início rápido: Aplicações web",
"quickstart_web_apps_description": "Por favor, siga o guia de início rápido para começar:",
"results_are_public": "Os resultados são públicos",
"selected_responses_csv": "Respostas selecionadas (CSV)",
"selected_responses_excel": "Respostas selecionadas (Excel)",
"send_preview": "Enviar pré-visualização",
"send_to_panel": "Enviar para painel",
"setup_instructions": "Instruções de configuração",

View File

@@ -1667,6 +1667,7 @@
"device": "裝置",
"device_info": "裝置資訊",
"email": "電子郵件",
"error_downloading_responses": "下載回應時發生錯誤",
"first_name": "名字",
"how_to_identify_users": "如何識別使用者",
"last_name": "姓氏",
@@ -1764,6 +1765,8 @@
"quickstart_web_apps": "快速入門Web apps",
"quickstart_web_apps_description": "請按照 Quickstart 指南開始:",
"results_are_public": "結果是公開的",
"selected_responses_csv": "選擇的回應 (CSV)",
"selected_responses_excel": "選擇的回應 (Excel)",
"send_preview": "發送預覽",
"send_to_panel": "發送到小組",
"setup_instructions": "設定說明",

View File

@@ -12,13 +12,12 @@ import {
isClientSideApiRoute,
isForgotPasswordRoute,
isLoginRoute,
isManagementApiRoute,
isShareUrlRoute,
isSignupRoute,
isSyncWithUserIdentificationEndpoint,
isVerifyEmailRoute,
} from "@/app/middleware/endpoint-validator";
import { E2E_TESTING, IS_PRODUCTION, RATE_LIMITING_DISABLED, SURVEY_URL, WEBAPP_URL } from "@/lib/constants";
import { IS_PRODUCTION, RATE_LIMITING_DISABLED, SURVEY_URL, WEBAPP_URL } from "@/lib/constants";
import { isValidCallbackUrl } from "@/lib/utils/url";
import { logApiError } from "@/modules/api/v2/lib/utils";
import { ApiErrorResponseV2 } from "@/modules/api/v2/types/api-error";
@@ -28,24 +27,6 @@ import { NextRequest, NextResponse } from "next/server";
import { v4 as uuidv4 } from "uuid";
import { logger } from "@formbricks/logger";
const enforceHttps = (request: NextRequest): Response | null => {
const forwardedProto = request.headers.get("x-forwarded-proto") ?? "http";
if (IS_PRODUCTION && !E2E_TESTING && forwardedProto !== "https") {
const apiError: ApiErrorResponseV2 = {
type: "forbidden",
details: [
{
field: "",
issue: "Only HTTPS connections are allowed on the management endpoints.",
},
],
};
logApiError(request, apiError);
return NextResponse.json(apiError, { status: 403 });
}
return null;
};
const handleAuth = async (request: NextRequest): Promise<Response | null> => {
const token = await getToken({ req: request as any });
@@ -132,12 +113,6 @@ export const middleware = async (originalRequest: NextRequest) => {
},
});
// Enforce HTTPS for management endpoints
if (isManagementApiRoute(request.nextUrl.pathname)) {
const httpsResponse = enforceHttps(request);
if (httpsResponse) return httpsResponse;
}
// Handle authentication
const authResponse = await handleAuth(request);
if (authResponse) return authResponse;

View File

@@ -240,4 +240,126 @@ describe("updateUser", () => {
expect(result.state.data).toEqual(expect.objectContaining(mockUserState));
expect(result.messages).toEqual([]);
});
test("should handle email attribute update with ignoreEmailAttribute flag", async () => {
vi.mocked(getContactByUserIdWithAttributes).mockResolvedValue(mockContact);
const newAttributes = { email: "new@example.com", name: "John Doe" };
vi.mocked(updateAttributes).mockResolvedValue({
success: true,
messages: [],
ignoreEmailAttribute: true,
});
vi.mocked(getUserState).mockResolvedValue({
...mockUserState,
});
const result = await updateUser(mockEnvironmentId, mockUserId, "desktop", newAttributes);
expect(updateAttributes).toHaveBeenCalledWith(
mockContactId,
mockUserId,
mockEnvironmentId,
newAttributes
);
// Email should not be included in the final attributes
expect(result.state.data).toEqual(
expect.objectContaining({
...mockUserState,
})
);
});
test("should handle failed attribute update gracefully", async () => {
vi.mocked(getContactByUserIdWithAttributes).mockResolvedValue(mockContact);
const newAttributes = { company: "Formbricks" };
vi.mocked(updateAttributes).mockResolvedValue({
success: false,
messages: ["Update failed"],
});
const result = await updateUser(mockEnvironmentId, mockUserId, "desktop", newAttributes);
expect(updateAttributes).toHaveBeenCalledWith(
mockContactId,
mockUserId,
mockEnvironmentId,
newAttributes
);
// Should still return state even if update failed
expect(result.state.data).toEqual(expect.objectContaining(mockUserState));
expect(result.messages).toEqual(["Update failed"]);
});
test("should handle multiple attribute updates correctly", async () => {
vi.mocked(getContactByUserIdWithAttributes).mockResolvedValue(mockContact);
const newAttributes = {
company: "Formbricks",
role: "Developer",
language: "en",
country: "US",
};
vi.mocked(updateAttributes).mockResolvedValue({
success: true,
messages: ["Attributes updated successfully"],
});
const result = await updateUser(mockEnvironmentId, mockUserId, "desktop", newAttributes);
expect(updateAttributes).toHaveBeenCalledWith(
mockContactId,
mockUserId,
mockEnvironmentId,
newAttributes
);
expect(result.state.data?.language).toBe("en");
expect(result.messages).toEqual(["Attributes updated successfully"]);
});
test("should handle contact creation with multiple initial attributes", async () => {
vi.mocked(getContactByUserIdWithAttributes).mockResolvedValue(null);
const initialAttributes = {
userId: mockUserId,
email: "test@example.com",
name: "Test User",
};
vi.mocked(prisma.contact.create).mockResolvedValue({
id: mockContactId,
attributes: [
{ attributeKey: { key: "userId" }, value: mockUserId },
{ attributeKey: { key: "email" }, value: "test@example.com" },
{ attributeKey: { key: "name" }, value: "Test User" },
],
} as any);
const result = await updateUser(mockEnvironmentId, mockUserId, "desktop", initialAttributes);
expect(prisma.contact.create).toHaveBeenCalledWith({
data: {
environment: { connect: { id: mockEnvironmentId } },
attributes: {
create: [
{
attributeKey: {
connect: { key_environmentId: { key: "userId", environmentId: mockEnvironmentId } },
},
value: mockUserId,
},
],
},
},
select: {
id: true,
attributes: {
select: { attributeKey: { select: { key: true } }, value: true },
},
},
});
expect(contactCache.revalidate).toHaveBeenCalledWith({
environmentId: mockEnvironmentId,
userId: mockUserId,
id: mockContactId,
});
expect(result.state.data).toEqual(expect.objectContaining(mockUserState));
});
});

View File

@@ -85,20 +85,26 @@ export const updateUser = async (
}
if (shouldUpdate) {
const { success, messages: updateAttrMessages } = await updateAttributes(
contact.id,
userId,
environmentId,
attributes
);
const {
success,
messages: updateAttrMessages,
ignoreEmailAttribute,
} = await updateAttributes(contact.id, userId, environmentId, attributes);
messages = updateAttrMessages ?? [];
// If the attributes update was successful and the language attribute was provided, set the language
if (success) {
let attributesToUpdate = { ...attributes };
if (ignoreEmailAttribute) {
const { email, ...rest } = attributes;
attributesToUpdate = rest;
}
contactAttributes = {
...contactAttributes,
...attributes,
...attributesToUpdate,
};
if (attributes.language) {

View File

@@ -236,7 +236,7 @@ export const ContactsTable = ({
setIsTableSettingsModalOpen={setIsTableSettingsModalOpen}
isExpanded={isExpanded ?? false}
table={table}
deleteRows={deleteContacts}
deleteRowsAction={deleteContacts}
type="contact"
deleteAction={deleteContact}
refreshContacts={refreshContacts}

View File

@@ -13,7 +13,7 @@ export const updateAttributes = async (
userId: string,
environmentId: string,
contactAttributesParam: TContactAttributes
): Promise<{ success: boolean; messages?: string[] }> => {
): Promise<{ success: boolean; messages?: string[]; ignoreEmailAttribute?: boolean }> => {
validateInputs(
[contactId, ZId],
[userId, ZString],
@@ -21,6 +21,8 @@ export const updateAttributes = async (
[contactAttributesParam, ZContactAttributes]
);
let ignoreEmailAttribute = false;
// Fetch contact attribute keys and email check in parallel
const [contactAttributeKeys, existingEmailAttribute] = await Promise.all([
getContactAttributeKeys(environmentId),
@@ -58,6 +60,10 @@ export const updateAttributes = async (
? ["The email already exists for this environment and was not updated."]
: [];
if (emailExists) {
ignoreEmailAttribute = true;
}
// First, update all existing attributes
if (existingAttributes.length > 0) {
await prisma.$transaction(
@@ -124,5 +130,6 @@ export const updateAttributes = async (
return {
success: true,
messages,
ignoreEmailAttribute,
};
};

View File

@@ -15,14 +15,14 @@ import { AuthenticationError, OperationNotAllowedError, ValidationError } from "
// Mock constants with getter functions to allow overriding in tests
let mockIsFormbricksCloud = false;
let mockDisableUserManagement = false;
let mockUserManagementMinimumRole = "owner";
vi.mock("@/lib/constants", () => ({
get IS_FORMBRICKS_CLOUD() {
return mockIsFormbricksCloud;
},
get DISABLE_USER_MANAGEMENT() {
return mockDisableUserManagement;
get USER_MANAGEMENT_MINIMUM_ROLE() {
return mockUserManagementMinimumRole;
},
}));
@@ -62,7 +62,7 @@ describe("Role Management Actions", () => {
afterEach(() => {
vi.resetAllMocks();
mockIsFormbricksCloud = false;
mockDisableUserManagement = false;
mockUserManagementMinimumRole = "owner";
});
describe("checkRoleManagementPermission", () => {
@@ -220,7 +220,7 @@ describe("Role Management Actions", () => {
test("throws error if user management is disabled", async () => {
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue({ role: "owner" } as any);
mockDisableUserManagement = true;
mockUserManagementMinimumRole = "disabled";
await expect(
updateMembershipAction({
@@ -231,12 +231,12 @@ describe("Role Management Actions", () => {
data: { role: "member" },
},
} as any)
).rejects.toThrow(new OperationNotAllowedError("User management is disabled"));
).rejects.toThrow(new OperationNotAllowedError("User management is not allowed for your role"));
});
test("throws error if billing role is not allowed in self-hosted", async () => {
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue({ role: "owner" } as any);
mockDisableUserManagement = false;
mockUserManagementMinimumRole = "owner";
vi.mocked(checkAuthorizationUpdated).mockResolvedValue(true);
await expect(
@@ -253,7 +253,7 @@ describe("Role Management Actions", () => {
test("allows billing role in cloud environment", async () => {
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue({ role: "owner" } as any);
mockDisableUserManagement = false;
mockUserManagementMinimumRole = "owner";
mockIsFormbricksCloud = true;
vi.mocked(checkAuthorizationUpdated).mockResolvedValue(true);
vi.mocked(getOrganization).mockResolvedValue({ billing: { plan: "pro" } } as any);
@@ -274,7 +274,7 @@ describe("Role Management Actions", () => {
test("throws error if manager tries to assign a role other than member", async () => {
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue({ role: "manager" } as any);
mockDisableUserManagement = false;
mockUserManagementMinimumRole = "manager";
vi.mocked(checkAuthorizationUpdated).mockResolvedValue(true);
await expect(
@@ -291,7 +291,7 @@ describe("Role Management Actions", () => {
test("allows manager to assign member role", async () => {
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue({ role: "manager" } as any);
mockDisableUserManagement = false;
mockUserManagementMinimumRole = "manager";
vi.mocked(checkAuthorizationUpdated).mockResolvedValue(true);
vi.mocked(getOrganization).mockResolvedValue({ billing: { plan: "pro" } } as any);
vi.mocked(getRoleManagementPermission).mockResolvedValue(true);
@@ -312,7 +312,7 @@ describe("Role Management Actions", () => {
test("successful membership update as owner", async () => {
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue({ role: "owner" } as any);
mockDisableUserManagement = false;
mockUserManagementMinimumRole = "owner";
vi.mocked(checkAuthorizationUpdated).mockResolvedValue(true);
vi.mocked(getOrganization).mockResolvedValue({ billing: { plan: "pro" } } as any);
vi.mocked(getRoleManagementPermission).mockResolvedValue(true);

View File

@@ -1,7 +1,8 @@
"use server";
import { DISABLE_USER_MANAGEMENT, IS_FORMBRICKS_CLOUD } from "@/lib/constants";
import { IS_FORMBRICKS_CLOUD, USER_MANAGEMENT_MINIMUM_ROLE } from "@/lib/constants";
import { getMembershipByUserIdOrganizationId } from "@/lib/membership/service";
import { getUserManagementAccess } from "@/lib/membership/utils";
import { getOrganization } from "@/lib/organization/service";
import { authenticatedActionClient } from "@/lib/utils/action-client";
import { checkAuthorizationUpdated } from "@/lib/utils/action-client-middleware";
@@ -87,8 +88,13 @@ export const updateMembershipAction = authenticatedActionClient
if (!currentUserMembership) {
throw new AuthenticationError("User not a member of this organization");
}
if (DISABLE_USER_MANAGEMENT) {
throw new OperationNotAllowedError("User management is disabled");
const hasUserManagementAccess = getUserManagementAccess(
currentUserMembership.role,
USER_MANAGEMENT_MINIMUM_ROLE
);
if (!hasUserManagementAccess) {
throw new OperationNotAllowedError("User management is not allowed for your role");
}
await checkAuthorizationUpdated({

View File

@@ -1,109 +0,0 @@
import { TInviteUpdateInput } from "@/modules/ee/role-management/types/invites";
import { Session } from "next-auth";
import { TMembership, TMembershipUpdateInput } from "@formbricks/types/memberships";
import { TOrganization, TOrganizationBillingPlan } from "@formbricks/types/organizations";
import { TUser } from "@formbricks/types/user";
// Common mock IDs
export const mockOrganizationId = "cblt7dwr7d0hvdifl4iw6d5x";
export const mockUserId = "wl43gybf3pxmqqx3fcmsk8eb";
export const mockInviteId = "dc0b6ea6-bb65-4a22-88e1-847df2e85af4";
export const mockTargetUserId = "vevt9qm7sqmh44e3za6a2vzd";
// Mock user
export const mockUser: TUser = {
id: mockUserId,
name: "Test User",
email: "test@example.com",
emailVerified: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
identityProvider: "email",
twoFactorEnabled: false,
objective: null,
notificationSettings: {
alert: {},
weeklySummary: {},
},
locale: "en-US",
imageUrl: null,
role: null,
lastLoginAt: new Date(),
isActive: true,
};
// Mock session
export const mockSession: Session = {
user: {
id: mockUserId,
},
expires: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
};
// Mock organizations
export const createMockOrganization = (plan: TOrganizationBillingPlan): TOrganization => ({
id: mockOrganizationId,
name: "Test Organization",
createdAt: new Date(),
updatedAt: new Date(),
isAIEnabled: false,
billing: {
stripeCustomerId: null,
plan,
period: "monthly",
periodStart: new Date(),
limits: {
projects: plan === "free" ? 3 : null,
monthly: {
responses: plan === "free" ? 1500 : null,
miu: plan === "free" ? 2000 : null,
},
},
},
});
export const mockOrganizationFree = createMockOrganization("free");
export const mockOrganizationStartup = createMockOrganization("startup");
export const mockOrganizationScale = createMockOrganization("scale");
// Mock membership data
export const createMockMembership = (role: TMembership["role"]): TMembership => ({
userId: mockUserId,
organizationId: mockOrganizationId,
role,
accepted: true,
});
export const mockMembershipMember = createMockMembership("member");
export const mockMembershipManager = createMockMembership("manager");
export const mockMembershipOwner = createMockMembership("owner");
// Mock data payloads
export const mockInviteDataMember: TInviteUpdateInput = { role: "member" };
export const mockInviteDataOwner: TInviteUpdateInput = { role: "owner" };
export const mockInviteDataBilling: TInviteUpdateInput = { role: "billing" };
export const mockMembershipUpdateMember: TMembershipUpdateInput = { role: "member" };
export const mockMembershipUpdateOwner: TMembershipUpdateInput = { role: "owner" };
export const mockMembershipUpdateBilling: TMembershipUpdateInput = { role: "billing" };
// Mock input objects for actions
export const mockUpdateInviteInput = {
inviteId: mockInviteId,
organizationId: mockOrganizationId,
data: mockInviteDataMember,
};
export const mockUpdateMembershipInput = {
userId: mockTargetUserId,
organizationId: mockOrganizationId,
data: mockMembershipUpdateMember,
};
// Mock responses
export const mockUpdatedMembership: TMembership = {
userId: mockTargetUserId,
organizationId: mockOrganizationId,
role: "member",
accepted: true,
};

View File

@@ -1,257 +0,0 @@
import {
mockInviteDataBilling,
mockInviteDataOwner,
mockMembershipManager,
mockMembershipMember,
mockMembershipUpdateBilling,
mockMembershipUpdateOwner,
mockOrganizationFree,
mockOrganizationId,
mockOrganizationScale,
mockOrganizationStartup,
mockSession,
mockUpdateInviteInput,
mockUpdateMembershipInput,
mockUpdatedMembership,
mockUser,
} from "./__mocks__/actions.mock";
import { getMembershipByUserIdOrganizationId } from "@/lib/membership/service";
import { getOrganization } from "@/lib/organization/service";
import { getUser } from "@/lib/user/service";
import "@/lib/utils/action-client-middleware";
import { checkAuthorizationUpdated } from "@/lib/utils/action-client-middleware";
import { getRoleManagementPermission } from "@/modules/ee/license-check/lib/utils";
import { updateInvite } from "@/modules/ee/role-management/lib/invite";
import { updateMembership } from "@/modules/ee/role-management/lib/membership";
import { getServerSession } from "next-auth";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { OperationNotAllowedError, ValidationError } from "@formbricks/types/errors";
import { checkRoleManagementPermission } from "../actions";
import { updateInviteAction, updateMembershipAction } from "../actions";
// Mock all external dependencies
vi.mock("@/modules/ee/license-check/lib/utils", () => ({
getRoleManagementPermission: vi.fn(),
}));
vi.mock("@/modules/ee/role-management/lib/invite", () => ({
updateInvite: vi.fn(),
}));
vi.mock("@/lib/user/service", () => ({
getUser: vi.fn(),
}));
vi.mock("@/modules/ee/role-management/lib/membership", () => ({
updateMembership: vi.fn(),
}));
vi.mock("@/lib/membership/service", () => ({
getMembershipByUserIdOrganizationId: vi.fn(),
}));
vi.mock("@/lib/organization/service", () => ({
getOrganization: vi.fn(),
}));
vi.mock("@/lib/utils/action-client-middleware", () => ({
checkAuthorizationUpdated: vi.fn(),
}));
vi.mock("next-auth", () => ({
getServerSession: vi.fn(),
}));
// Mock constants without importing the actual module
vi.mock("@/lib/constants", () => ({
IS_FORMBRICKS_CLOUD: false,
IS_MULTI_ORG_ENABLED: true,
ENCRYPTION_KEY: "test-encryption-key",
ENTERPRISE_LICENSE_KEY: "test-enterprise-license-key",
GITHUB_ID: "test-github-id",
GITHUB_SECRET: "test-github-secret",
GOOGLE_CLIENT_ID: "test-google-client-id",
GOOGLE_CLIENT_SECRET: "test-google-client-secret",
AZUREAD_CLIENT_ID: "test-azure-client-id",
AZUREAD_CLIENT_SECRET: "test-azure-client-secret",
AZUREAD_TENANT_ID: "test-azure-tenant-id",
OIDC_CLIENT_ID: "test-oidc-client-id",
OIDC_CLIENT_SECRET: "test-oidc-client-secret",
OIDC_ISSUER: "test-oidc-issuer",
OIDC_DISPLAY_NAME: "test-oidc-display-name",
OIDC_SIGNING_ALGORITHM: "test-oidc-algorithm",
SAML_DATABASE_URL: "test-saml-db-url",
NEXTAUTH_SECRET: "test-nextauth-secret",
WEBAPP_URL: "http://localhost:3000",
DISABLE_USER_MANAGEMENT: false,
}));
vi.mock("@/lib/utils/action-client-middleware", () => ({
checkAuthorizationUpdated: vi.fn(),
}));
vi.mock("@/lib/errors", () => ({
OperationNotAllowedError: vi.fn(),
ValidationError: vi.fn(),
}));
describe("role-management/actions.ts", () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.resetAllMocks();
});
describe("checkRoleManagementPermission", () => {
test("throws error when organization not found", async () => {
vi.mocked(getOrganization).mockResolvedValue(null);
await expect(checkRoleManagementPermission(mockOrganizationId)).rejects.toThrow(
"Organization not found"
);
expect(getOrganization).toHaveBeenCalledWith(mockOrganizationId);
});
test("throws error when role management is not allowed", async () => {
vi.mocked(getOrganization).mockResolvedValue(mockOrganizationFree);
vi.mocked(getRoleManagementPermission).mockResolvedValue(false);
await expect(checkRoleManagementPermission(mockOrganizationId)).rejects.toThrow(
new OperationNotAllowedError("Role management is not allowed for this organization")
);
expect(getRoleManagementPermission).toHaveBeenCalledWith("free");
expect(getOrganization).toHaveBeenCalledWith(mockOrganizationId);
});
test("succeeds when role management is allowed", async () => {
vi.mocked(getOrganization).mockResolvedValue(mockOrganizationStartup);
vi.mocked(getRoleManagementPermission).mockResolvedValue(true);
await expect(checkRoleManagementPermission(mockOrganizationId)).resolves.toBeUndefined();
await expect(getRoleManagementPermission).toHaveBeenCalledWith("startup");
expect(getOrganization).toHaveBeenCalledWith(mockOrganizationId);
});
});
describe("updateInviteAction", () => {
test("throws error when user is not a member of the organization", async () => {
vi.mocked(getServerSession).mockResolvedValue(mockSession);
vi.mocked(getUser).mockResolvedValue(mockUser);
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue(null);
expect(await updateInviteAction(mockUpdateInviteInput)).toStrictEqual({
serverError: "User not a member of this organization",
});
});
test("throws error when billing role is not allowed in self-hosted", async () => {
const inputWithBillingRole = {
...mockUpdateInviteInput,
data: mockInviteDataBilling,
};
vi.mocked(getServerSession).mockResolvedValue(mockSession);
vi.mocked(getUser).mockResolvedValue(mockUser);
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue(mockMembershipMember);
vi.mocked(checkAuthorizationUpdated).mockResolvedValue(true);
expect(await updateInviteAction(inputWithBillingRole)).toStrictEqual({
serverError: "Something went wrong while executing the operation.",
});
});
test("throws error when manager tries to assign non-member role", async () => {
const inputWithOwnerRole = {
...mockUpdateInviteInput,
data: mockInviteDataOwner,
};
vi.mocked(getServerSession).mockResolvedValue(mockSession);
vi.mocked(getUser).mockResolvedValue(mockUser);
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue(mockMembershipManager);
vi.mocked(checkAuthorizationUpdated).mockResolvedValue(true);
expect(await updateInviteAction(inputWithOwnerRole)).toStrictEqual({
serverError: "Managers can only invite members",
});
});
test("successfully updates invite", async () => {
vi.mocked(getServerSession).mockResolvedValue(mockSession);
vi.mocked(getUser).mockResolvedValue(mockUser);
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue(mockMembershipManager);
vi.mocked(checkAuthorizationUpdated).mockResolvedValue(true);
vi.mocked(getOrganization).mockResolvedValue(mockOrganizationScale);
vi.mocked(getRoleManagementPermission).mockResolvedValue(true);
vi.mocked(updateInvite).mockResolvedValue(true);
const result = await updateInviteAction(mockUpdateInviteInput);
expect(result).toEqual({ data: true });
});
});
describe("updateMembershipAction", () => {
test("throws error when user is not a member of the organization", async () => {
vi.mocked(getServerSession).mockResolvedValue(mockSession);
vi.mocked(getUser).mockResolvedValue(mockUser);
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue(null);
expect(await updateMembershipAction(mockUpdateMembershipInput)).toStrictEqual({
serverError: "User not a member of this organization",
});
});
test("throws error when billing role is not allowed in self-hosted", async () => {
const inputWithBillingRole = {
...mockUpdateMembershipInput,
data: mockMembershipUpdateBilling,
};
vi.mocked(getServerSession).mockResolvedValue(mockSession);
vi.mocked(getUser).mockResolvedValue(mockUser);
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue(mockMembershipMember);
vi.mocked(checkAuthorizationUpdated).mockResolvedValue(true);
expect(await updateMembershipAction(inputWithBillingRole)).toStrictEqual({
serverError: "Something went wrong while executing the operation.",
});
});
test("throws error when manager tries to assign non-member role", async () => {
const inputWithOwnerRole = {
...mockUpdateMembershipInput,
data: mockMembershipUpdateOwner,
};
vi.mocked(getServerSession).mockResolvedValue(mockSession);
vi.mocked(getUser).mockResolvedValue(mockUser);
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue(mockMembershipManager);
vi.mocked(checkAuthorizationUpdated).mockResolvedValue(true);
expect(await updateMembershipAction(inputWithOwnerRole)).toStrictEqual({
serverError: "Managers can only assign users to the member role",
});
});
test("successfully updates membership", async () => {
vi.mocked(getServerSession).mockResolvedValue(mockSession);
vi.mocked(getUser).mockResolvedValue(mockUser);
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue(mockMembershipManager);
vi.mocked(checkAuthorizationUpdated).mockResolvedValue(true);
vi.mocked(getOrganization).mockResolvedValue(mockOrganizationScale);
vi.mocked(getRoleManagementPermission).mockResolvedValue(true);
vi.mocked(updateMembership).mockResolvedValue(mockUpdatedMembership);
const result = await updateMembershipAction(mockUpdateMembershipInput);
expect(result).toEqual({
data: mockUpdatedMembership,
});
});
});
});

View File

@@ -13,7 +13,7 @@ vi.mock(
);
vi.mock("@/lib/constants", () => ({
DISABLE_USER_MANAGEMENT: 0,
USER_MANAGEMENT_MINIMUM_ROLE: "owner",
IS_FORMBRICKS_CLOUD: 1,
ENCRYPTION_KEY: "test-key",
ENTERPRISE_LICENSE_KEY: "test-enterprise-key",

View File

@@ -1,5 +1,6 @@
import { OrganizationSettingsNavbar } from "@/app/(app)/environments/[environmentId]/settings/(organization)/components/OrganizationSettingsNavbar";
import { DISABLE_USER_MANAGEMENT, IS_FORMBRICKS_CLOUD } from "@/lib/constants";
import { IS_FORMBRICKS_CLOUD, USER_MANAGEMENT_MINIMUM_ROLE } from "@/lib/constants";
import { getUserManagementAccess } from "@/lib/membership/utils";
import { getRoleManagementPermission } from "@/modules/ee/license-check/lib/utils";
import { TeamsView } from "@/modules/ee/teams/team-list/components/teams-view";
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
@@ -15,6 +16,10 @@ export const TeamsPage = async (props) => {
const { session, currentUserMembership, organization } = await getEnvironmentAuth(params.environmentId);
const canDoRoleManagement = await getRoleManagementPermission(organization.billing.plan);
const hasUserManagementAccess = getUserManagementAccess(
currentUserMembership?.role,
USER_MANAGEMENT_MINIMUM_ROLE
);
return (
<PageContentWrapper>
@@ -32,7 +37,7 @@ export const TeamsPage = async (props) => {
currentUserId={session.user.id}
environmentId={params.environmentId}
canDoRoleManagement={canDoRoleManagement}
isUserManagementDisabledFromUi={DISABLE_USER_MANAGEMENT}
isUserManagementDisabledFromUi={!hasUserManagementAccess}
/>
<TeamsView
organizationId={organization.id}

View File

@@ -87,21 +87,6 @@ export const CTAQuestionForm = ({
<div className="mt-2 flex justify-between gap-8">
<div className="flex w-full space-x-2">
<QuestionFormInput
id="buttonLabel"
value={question.buttonLabel}
label={t("environments.surveys.edit.next_button_label")}
localSurvey={localSurvey}
questionIdx={questionIdx}
maxLength={48}
placeholder={lastQuestion ? t("common.finish") : t("common.next")}
isInvalid={isInvalid}
updateQuestion={updateQuestion}
selectedLanguageCode={selectedLanguageCode}
setSelectedLanguageCode={setSelectedLanguageCode}
locale={locale}
/>
{questionIdx !== 0 && (
<QuestionFormInput
id="backButtonLabel"
@@ -118,6 +103,20 @@ export const CTAQuestionForm = ({
locale={locale}
/>
)}
<QuestionFormInput
id="buttonLabel"
value={question.buttonLabel}
label={t("environments.surveys.edit.next_button_label")}
localSurvey={localSurvey}
questionIdx={questionIdx}
maxLength={48}
placeholder={lastQuestion ? t("common.finish") : t("common.next")}
isInvalid={isInvalid}
updateQuestion={updateQuestion}
selectedLanguageCode={selectedLanguageCode}
setSelectedLanguageCode={setSelectedLanguageCode}
locale={locale}
/>
</div>
</div>

View File

@@ -1,15 +1,10 @@
import { QuestionCard } from "@/modules/survey/editor/components/question-card";
import { Project } from "@prisma/client";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
// Import waitFor
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, test, vi } from "vitest";
import {
TSurvey,
TSurveyAddressQuestion,
TSurveyQuestion,
TSurveyQuestionTypeEnum,
} from "@formbricks/types/surveys/types";
// Import waitFor
import { TSurvey, TSurveyQuestion, TSurveyQuestionTypeEnum } from "@formbricks/types/surveys/types";
// Mock child components
vi.mock("@/modules/survey/components/question-form-input", () => ({
@@ -371,8 +366,9 @@ describe("QuestionCard Component", () => {
test("applies invalid styling when isInvalid is true", () => {
render(<QuestionCard {...defaultProps} isInvalid={true} />);
const dragHandle = screen.getByRole("button", { name: "" }).parentElement; // Get the div containing the GripIcon
const dragHandle = screen.getByRole("button", { name: "Drag to reorder question" }).parentElement; // Get the div containing the GripIcon
expect(dragHandle).toHaveClass("bg-red-400");
expect(dragHandle).toHaveClass("hover:bg-red-600");
});
test("disables required toggle for Address question if all fields are optional", () => {
@@ -507,4 +503,94 @@ describe("QuestionCard Component", () => {
// First question should never have back button
expect(screen.queryByTestId("question-form-input-backButtonLabel")).not.toBeInTheDocument();
});
// Accessibility Tests
test("maintains proper focus management when toggling advanced settings", async () => {
const user = userEvent.setup();
render(<QuestionCard {...defaultProps} activeQuestionId="q1" />);
const advancedSettingsTrigger = screen.getByText("environments.surveys.edit.show_advanced_settings");
await user.click(advancedSettingsTrigger);
const closeTrigger = screen.getByText("environments.surveys.edit.hide_advanced_settings");
expect(closeTrigger).toBeInTheDocument();
});
test("ensures proper ARIA attributes for collapsible sections", () => {
render(<QuestionCard {...defaultProps} activeQuestionId="q1" />);
const collapsibleTrigger = screen.getByText("environments.surveys.edit.show_advanced_settings");
expect(collapsibleTrigger).toHaveAttribute("aria-expanded", "false");
fireEvent.click(collapsibleTrigger);
expect(collapsibleTrigger).toHaveAttribute("aria-expanded", "true");
});
test("maintains keyboard accessibility for required toggle", async () => {
const user = userEvent.setup();
render(<QuestionCard {...defaultProps} activeQuestionId="q1" />);
const requiredToggle = screen.getByRole("switch", { name: "environments.surveys.edit.required" });
await user.click(requiredToggle);
expect(mockUpdateQuestion).toHaveBeenCalledWith(0, { required: false });
});
test("provides screen reader text for drag handle", () => {
render(<QuestionCard {...defaultProps} />);
const dragHandle = screen.getByRole("button", { name: "Drag to reorder question" });
const svg = dragHandle.querySelector("svg");
expect(svg).toHaveAttribute("aria-hidden", "true");
});
test("maintains proper heading hierarchy", () => {
render(<QuestionCard {...defaultProps} activeQuestionId="q1" />);
const headline = screen.getByText("Question Headline");
expect(headline.tagName).toBe("H3");
expect(headline).toHaveClass("text-sm", "font-semibold");
});
test("ensures proper focus order for form elements", async () => {
const user = userEvent.setup();
render(<QuestionCard {...defaultProps} activeQuestionId="q1" />);
// Open advanced settings
fireEvent.click(screen.getByText("environments.surveys.edit.show_advanced_settings"));
const requiredToggle = screen.getByRole("switch", { name: "environments.surveys.edit.required" });
await user.click(requiredToggle);
expect(mockUpdateQuestion).toHaveBeenCalledWith(0, { required: false });
});
test("provides proper ARIA attributes for interactive elements", () => {
render(<QuestionCard {...defaultProps} activeQuestionId="q1" />);
const requiredToggle = screen.getByRole("switch", { name: "environments.surveys.edit.required" });
expect(requiredToggle).toHaveAttribute("aria-checked", "true");
const longAnswerToggle = screen.getByRole("switch", { name: "environments.surveys.edit.long_answer" });
expect(longAnswerToggle).toHaveAttribute("aria-checked", "false");
});
test("ensures proper role attributes for interactive elements", () => {
render(<QuestionCard {...defaultProps} activeQuestionId="q1" />);
const toggles = screen.getAllByRole("switch");
expect(toggles).toHaveLength(2); // Required and Long Answer toggles
const collapsibleTrigger = screen.getByText("environments.surveys.edit.show_advanced_settings");
expect(collapsibleTrigger).toHaveAttribute("type", "button");
});
test("maintains proper focus management when closing advanced settings", async () => {
const user = userEvent.setup();
render(<QuestionCard {...defaultProps} activeQuestionId="q1" />);
const advancedSettingsTrigger = screen.getByText("environments.surveys.edit.show_advanced_settings");
await user.click(advancedSettingsTrigger);
const closeTrigger = screen.getByText("environments.surveys.edit.hide_advanced_settings");
await user.click(closeTrigger);
expect(screen.getByText("environments.surveys.edit.show_advanced_settings")).toBeInTheDocument();
});
});

View File

@@ -196,7 +196,9 @@ export const QuestionCard = ({
)}>
<div className="mt-3 flex w-full justify-center">{QUESTIONS_ICON_MAP[question.type]}</div>
<button className="opacity-0 hover:cursor-move group-hover:opacity-100">
<button
className="opacity-0 hover:cursor-move group-hover:opacity-100"
aria-label="Drag to reorder question">
<GripIcon className="h-4 w-4" />
</button>
</div>
@@ -215,14 +217,15 @@ export const QuestionCard = ({
className={cn(
open ? "" : " ",
"flex cursor-pointer justify-between gap-4 rounded-r-lg p-4 hover:bg-slate-50"
)}>
)}
aria-label="Toggle question details">
<div>
<div className="flex grow">
{/* <div className="-ml-0.5 mr-3 h-6 min-w-[1.5rem] text-slate-400">
{QUESTIONS_ICON_MAP[question.type]}
</div> */}
<div className="flex grow flex-col justify-center" dir="auto">
<p className="text-sm font-semibold">
<h3 className="text-sm font-semibold">
{recallToHeadline(question.headline, localSurvey, true, selectedLanguageCode)[
selectedLanguageCode
]
@@ -232,7 +235,7 @@ export const QuestionCard = ({
] ?? ""
)
: getTSurveyQuestionTypeEnumName(question.type, t)}
</p>
</h3>
{!open && (
<p className="mt-1 truncate text-xs text-slate-500">
{question?.required
@@ -272,7 +275,7 @@ export const QuestionCard = ({
TSurveyQuestionTypeEnum.Ranking,
TSurveyQuestionTypeEnum.Matrix,
].includes(question.type) ? (
<Alert variant="warning" size="small" className="w-fill">
<Alert variant="warning" size="small" className="w-fill" role="alert">
<AlertTitle>{t("environments.surveys.edit.caution_text")}</AlertTitle>
<AlertButton onClick={() => onAlertTrigger()}>{t("common.learn_more")}</AlertButton>
</Alert>
@@ -457,7 +460,9 @@ export const QuestionCard = ({
) : null}
<div className="mt-4">
<Collapsible.Root open={openAdvanced} onOpenChange={setOpenAdvanced} className="mt-5">
<Collapsible.CollapsibleTrigger className="flex items-center text-sm text-slate-700">
<Collapsible.CollapsibleTrigger
className="flex items-center text-sm text-slate-700"
aria-label="Toggle advanced settings">
{openAdvanced ? (
<ChevronDownIcon className="mr-1 h-4 w-3" />
) : (
@@ -473,6 +478,30 @@ export const QuestionCard = ({
question.type !== TSurveyQuestionTypeEnum.Rating &&
question.type !== TSurveyQuestionTypeEnum.CTA ? (
<div className="mt-2 flex space-x-2">
{questionIdx !== 0 && (
<QuestionFormInput
id="backButtonLabel"
value={question.backButtonLabel}
label={t("environments.surveys.edit.back_button_label")}
localSurvey={localSurvey}
questionIdx={questionIdx}
maxLength={48}
placeholder={t("common.back")}
isInvalid={isInvalid}
updateQuestion={updateQuestion}
selectedLanguageCode={selectedLanguageCode}
setSelectedLanguageCode={setSelectedLanguageCode}
locale={locale}
onBlur={(e) => {
if (!question.backButtonLabel) return;
let translatedBackButtonLabel = {
...question.backButtonLabel,
[selectedLanguageCode]: e.target.value,
};
updateEmptyButtonLabels("backButtonLabel", translatedBackButtonLabel, 0);
}}
/>
)}
<div className="w-full">
<QuestionFormInput
id="buttonLabel"
@@ -503,30 +532,6 @@ export const QuestionCard = ({
locale={locale}
/>
</div>
{questionIdx !== 0 && (
<QuestionFormInput
id="backButtonLabel"
value={question.backButtonLabel}
label={t("environments.surveys.edit.back_button_label")}
localSurvey={localSurvey}
questionIdx={questionIdx}
maxLength={48}
placeholder={t("common.back")}
isInvalid={isInvalid}
updateQuestion={updateQuestion}
selectedLanguageCode={selectedLanguageCode}
setSelectedLanguageCode={setSelectedLanguageCode}
locale={locale}
onBlur={(e) => {
if (!question.backButtonLabel) return;
let translatedBackButtonLabel = {
...question.backButtonLabel,
[selectedLanguageCode]: e.target.value,
};
updateEmptyButtonLabels("backButtonLabel", translatedBackButtonLabel, 0);
}}
/>
)}
</div>
) : null}
{(question.type === TSurveyQuestionTypeEnum.Rating ||

View File

@@ -53,10 +53,10 @@ describe("SurveyCard", () => {
survey={{ ...dummySurvey, status: "draft" } as unknown as TSurvey}
environmentId={environmentId}
isReadOnly={false}
WEBAPP_URL={WEBAPP_URL}
duplicateSurvey={mockDuplicateSurvey}
deleteSurvey={mockDeleteSurvey}
locale="en-US"
surveyDomain={WEBAPP_URL}
/>
);
// Draft survey => link should point to edit
@@ -70,10 +70,10 @@ describe("SurveyCard", () => {
survey={{ ...dummySurvey, status: "draft" } as unknown as TSurvey}
environmentId={environmentId}
isReadOnly={true}
WEBAPP_URL={WEBAPP_URL}
duplicateSurvey={mockDuplicateSurvey}
deleteSurvey={mockDeleteSurvey}
locale="en-US"
surveyDomain={WEBAPP_URL}
/>
);
// When it's read only and draft, we expect no link
@@ -87,10 +87,10 @@ describe("SurveyCard", () => {
survey={{ ...dummySurvey, status: "inProgress" } as unknown as TSurvey}
environmentId={environmentId}
isReadOnly={false}
WEBAPP_URL={WEBAPP_URL}
duplicateSurvey={mockDuplicateSurvey}
deleteSurvey={mockDeleteSurvey}
locale="en-US"
surveyDomain={WEBAPP_URL}
/>
);
// For non-draft => link to summary

View File

@@ -4,195 +4,140 @@ import toast from "react-hot-toast";
import { afterEach, describe, expect, test, vi } from "vitest";
import { DataTableToolbar } from "./data-table-toolbar";
// Mock TooltipRenderer
vi.mock("@/modules/ui/components/tooltip", () => ({
TooltipRenderer: ({ children, tooltipContent }) => (
<div data-testid="tooltip-renderer" data-tooltip-content={tooltipContent}>
{children}
</div>
),
}));
// Mock SelectedRowSettings
vi.mock("./selected-row-settings", () => ({
SelectedRowSettings: vi.fn(() => <div data-testid="selected-row-settings"></div>),
}));
// Mock useTranslate
vi.mock("@tolgee/react", () => ({
useTranslate: () => ({
t: (key) => key,
}),
}));
// Mock toast
vi.mock("react-hot-toast", () => ({
default: {
success: vi.fn(),
error: vi.fn(),
},
}));
// Mock lucide-react icons
vi.mock("lucide-react", async () => {
const actual = await vi.importActual("lucide-react");
return {
...actual,
RefreshCcwIcon: vi.fn((props) => <div data-testid="refresh-ccw-icon" {...props} />),
SettingsIcon: vi.fn((props) => <div data-testid="settings-icon" {...props} />),
MoveVerticalIcon: vi.fn((props) => <div data-testid="move-vertical-icon" {...props} />),
};
});
const mockTable = {
getFilteredSelectedRowModel: vi.fn(() => ({ rows: [] })),
} as any;
const mockDeleteRowsAction = vi.fn();
const mockDeleteAction = vi.fn();
const mockDownloadRowsAction = vi.fn();
const mockRefreshContacts = vi.fn();
const mockSetIsExpanded = vi.fn();
const mockSetIsTableSettingsModalOpen = vi.fn();
const defaultProps = {
setIsExpanded: mockSetIsExpanded,
setIsTableSettingsModalOpen: mockSetIsTableSettingsModalOpen,
isExpanded: false,
table: mockTable,
deleteRowsAction: mockDeleteRowsAction,
type: "response" as "response" | "contact",
deleteAction: mockDeleteAction,
downloadRowAction: mockDownloadRowsAction,
refreshContacts: mockRefreshContacts,
};
describe("DataTableToolbar", () => {
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
test("renders selection settings when rows are selected", () => {
const mockTable = {
getFilteredSelectedRowModel: vi.fn().mockReturnValue({
rows: [{ id: "row1" }, { id: "row2" }],
}),
};
render(
<DataTableToolbar
setIsTableSettingsModalOpen={vi.fn()}
setIsExpanded={vi.fn()}
isExpanded={false}
table={mockTable as any}
deleteRows={vi.fn()}
type="response"
deleteAction={vi.fn()}
/>
);
// Check for the number of selected items instead of translation keys
const selectionInfo = screen.getByText(/2/);
expect(selectionInfo).toBeInTheDocument();
// Look for the exact text that appears in the component (which is the translation key)
expect(screen.getByText("common.select_all")).toBeInTheDocument();
expect(screen.getByText("common.clear_selection")).toBeInTheDocument();
test("renders correctly with no selected rows", () => {
render(<DataTableToolbar {...defaultProps} />);
expect(screen.queryByTestId("selected-row-settings")).not.toBeInTheDocument();
expect(screen.getByTestId("settings-icon")).toBeInTheDocument();
expect(screen.getByTestId("move-vertical-icon")).toBeInTheDocument();
expect(screen.queryByTestId("refresh-ccw-icon")).not.toBeInTheDocument();
});
test("renders settings and expand buttons", () => {
const mockTable = {
getFilteredSelectedRowModel: vi.fn().mockReturnValue({
rows: [],
}),
};
render(
<DataTableToolbar
setIsTableSettingsModalOpen={vi.fn()}
setIsExpanded={vi.fn()}
isExpanded={false}
table={mockTable as any}
deleteRows={vi.fn()}
type="response"
deleteAction={vi.fn()}
/>
);
// Look for SVG elements by their class names instead of role
const settingsIcon = document.querySelector(".lucide-settings");
const expandIcon = document.querySelector(".lucide-move-vertical");
expect(settingsIcon).toBeInTheDocument();
expect(expandIcon).toBeInTheDocument();
test("renders SelectedRowSettings when rows are selected", () => {
const tableWithSelectedRows = {
getFilteredSelectedRowModel: vi.fn(() => ({ rows: [{ id: "1" }] })),
} as any;
render(<DataTableToolbar {...defaultProps} table={tableWithSelectedRows} />);
expect(screen.getByTestId("selected-row-settings")).toBeInTheDocument();
});
test("calls setIsTableSettingsModalOpen when settings button is clicked", async () => {
const user = userEvent.setup();
const setIsTableSettingsModalOpen = vi.fn();
const mockTable = {
getFilteredSelectedRowModel: vi.fn().mockReturnValue({
rows: [],
}),
};
render(
<DataTableToolbar
setIsTableSettingsModalOpen={setIsTableSettingsModalOpen}
setIsExpanded={vi.fn()}
isExpanded={false}
table={mockTable as any}
deleteRows={vi.fn()}
type="response"
deleteAction={vi.fn()}
/>
test("renders refresh icon for contact type and calls refreshContacts on click", async () => {
mockRefreshContacts.mockResolvedValueOnce(undefined);
render(<DataTableToolbar {...defaultProps} type="contact" />);
const refreshIconContainer = screen.getByTestId("refresh-ccw-icon").parentElement;
expect(refreshIconContainer).toBeInTheDocument();
await userEvent.click(refreshIconContainer!);
expect(mockRefreshContacts).toHaveBeenCalledTimes(1);
expect(vi.mocked(toast.success)).toHaveBeenCalledWith(
"environments.contacts.contacts_table_refresh_success"
);
// Find the settings button by class and click it
const settingsIcon = document.querySelector(".lucide-settings");
const settingsButton = settingsIcon?.closest("div");
expect(settingsButton).toBeInTheDocument();
if (settingsButton) {
await user.click(settingsButton);
expect(setIsTableSettingsModalOpen).toHaveBeenCalledWith(true);
}
});
test("calls setIsExpanded when expand button is clicked", async () => {
const user = userEvent.setup();
const setIsExpanded = vi.fn();
const mockTable = {
getFilteredSelectedRowModel: vi.fn().mockReturnValue({
rows: [],
}),
};
render(
<DataTableToolbar
setIsTableSettingsModalOpen={vi.fn()}
setIsExpanded={setIsExpanded}
isExpanded={false}
table={mockTable as any}
deleteRows={vi.fn()}
type="response"
deleteAction={vi.fn()}
/>
);
// Find the expand button by class and click it
const expandIcon = document.querySelector(".lucide-move-vertical");
const expandButton = expandIcon?.closest("div");
expect(expandButton).toBeInTheDocument();
if (expandButton) {
await user.click(expandButton);
expect(setIsExpanded).toHaveBeenCalledWith(true);
}
test("handles refreshContacts failure", async () => {
mockRefreshContacts.mockRejectedValueOnce(new Error("Refresh failed"));
render(<DataTableToolbar {...defaultProps} type="contact" />);
const refreshIconContainer = screen.getByTestId("refresh-ccw-icon").parentElement;
await userEvent.click(refreshIconContainer!);
expect(mockRefreshContacts).toHaveBeenCalledTimes(1);
expect(vi.mocked(toast.error)).toHaveBeenCalledWith("environments.contacts.contacts_table_refresh_error");
});
test("shows refresh button and calls refreshContacts when type is contact", async () => {
const user = userEvent.setup();
const refreshContacts = vi.fn().mockResolvedValue(undefined);
const mockTable = {
getFilteredSelectedRowModel: vi.fn().mockReturnValue({
rows: [],
}),
};
render(
<DataTableToolbar
setIsTableSettingsModalOpen={vi.fn()}
setIsExpanded={vi.fn()}
isExpanded={false}
table={mockTable as any}
deleteRows={vi.fn()}
type="contact"
deleteAction={vi.fn()}
refreshContacts={refreshContacts}
/>
);
// Find the refresh button by class and click it
const refreshIcon = document.querySelector(".lucide-refresh-ccw");
const refreshButton = refreshIcon?.closest("div");
expect(refreshButton).toBeInTheDocument();
if (refreshButton) {
await user.click(refreshButton);
expect(refreshContacts).toHaveBeenCalled();
expect(toast.success).toHaveBeenCalledWith("environments.contacts.contacts_table_refresh_success");
}
test("does not render refresh icon for response type", () => {
render(<DataTableToolbar {...defaultProps} type="response" />);
expect(screen.queryByTestId("refresh-ccw-icon")).not.toBeInTheDocument();
});
test("shows error toast when refreshContacts fails", async () => {
const user = userEvent.setup();
const refreshContacts = vi.fn().mockRejectedValue(new Error("Failed to refresh"));
const mockTable = {
getFilteredSelectedRowModel: vi.fn().mockReturnValue({
rows: [],
}),
};
test("calls setIsTableSettingsModalOpen when settings icon is clicked", async () => {
render(<DataTableToolbar {...defaultProps} />);
const settingsIconContainer = screen.getByTestId("settings-icon").parentElement;
await userEvent.click(settingsIconContainer!);
expect(mockSetIsTableSettingsModalOpen).toHaveBeenCalledWith(true);
});
render(
<DataTableToolbar
setIsTableSettingsModalOpen={vi.fn()}
setIsExpanded={vi.fn()}
isExpanded={false}
table={mockTable as any}
deleteRows={vi.fn()}
type="contact"
deleteAction={vi.fn()}
refreshContacts={refreshContacts}
/>
);
test("calls setIsExpanded when move vertical icon is clicked (isExpanded false)", async () => {
render(<DataTableToolbar {...defaultProps} isExpanded={false} />);
const moveIconContainer = screen.getByTestId("move-vertical-icon").parentElement;
const tooltip = moveIconContainer?.closest('[data-testid="tooltip-renderer"]');
expect(tooltip).toHaveAttribute("data-tooltip-content", "common.expand_rows");
await userEvent.click(moveIconContainer!);
expect(mockSetIsExpanded).toHaveBeenCalledWith(true);
});
// Find the refresh button by class and click it
const refreshIcon = document.querySelector(".lucide-refresh-ccw");
const refreshButton = refreshIcon?.closest("div");
expect(refreshButton).toBeInTheDocument();
if (refreshButton) {
await user.click(refreshButton);
expect(refreshContacts).toHaveBeenCalled();
expect(toast.error).toHaveBeenCalledWith("environments.contacts.contacts_table_refresh_error");
}
test("calls setIsExpanded when move vertical icon is clicked (isExpanded true)", async () => {
render(<DataTableToolbar {...defaultProps} isExpanded={true} />);
const moveIconContainer = screen.getByTestId("move-vertical-icon").parentElement;
const tooltip = moveIconContainer?.closest('[data-testid="tooltip-renderer"]');
expect(tooltip).toHaveAttribute("data-tooltip-content", "common.collapse_rows");
await userEvent.click(moveIconContainer!);
expect(mockSetIsExpanded).toHaveBeenCalledWith(false);
expect(moveIconContainer).toHaveClass("bg-black text-white");
});
});

View File

@@ -13,9 +13,10 @@ interface DataTableToolbarProps<T> {
setIsExpanded: (isExpanded: boolean) => void;
isExpanded: boolean;
table: Table<T>;
deleteRows: (rowIds: string[]) => void;
deleteRowsAction: (rowIds: string[]) => void;
type: "response" | "contact";
deleteAction: (id: string) => Promise<void>;
downloadRowsAction?: (rowIds: string[], format: string) => void;
refreshContacts?: () => Promise<void>;
}
@@ -24,9 +25,10 @@ export const DataTableToolbar = <T,>({
setIsTableSettingsModalOpen,
isExpanded,
table,
deleteRows,
deleteRowsAction,
type,
deleteAction,
downloadRowsAction,
refreshContacts,
}: DataTableToolbarProps<T>) => {
const { t } = useTranslate();
@@ -34,7 +36,13 @@ export const DataTableToolbar = <T,>({
return (
<div className="sticky top-12 z-30 my-2 flex w-full items-center justify-between bg-slate-50 py-2">
{table.getFilteredSelectedRowModel().rows.length > 0 ? (
<SelectedRowSettings table={table} deleteRows={deleteRows} type={type} deleteAction={deleteAction} />
<SelectedRowSettings
table={table}
deleteRowsAction={deleteRowsAction}
type={type}
deleteAction={deleteAction}
downloadRowsAction={downloadRowsAction}
/>
) : (
<div></div>
)}

View File

@@ -1,192 +1,187 @@
import { cleanup, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import toast from "react-hot-toast";
import { afterEach, describe, expect, test, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { toast } from "react-hot-toast";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { SelectedRowSettings } from "./selected-row-settings";
// Mock the toast functions directly since they're causing issues
vi.mock("react-hot-toast", () => ({
default: {
success: vi.fn(),
error: vi.fn(),
},
// Mock translation
vi.mock("@tolgee/react", () => ({
useTranslate: () => ({ t: (key: string) => key }),
}));
// Instead of mocking @radix-ui/react-dialog, we'll test the component's behavior
// by checking if the appropriate actions are performed after clicking the buttons
// Mock DeleteDialog to reveal confirm button when open
vi.mock("@/modules/ui/components/delete-dialog", () => ({
DeleteDialog: ({ open, onDelete }: any) =>
open ? <button onClick={() => onDelete()}>Confirm Delete</button> : null,
}));
// Mock dropdown-menu components to render their children
vi.mock("@/modules/ui/components/dropdown-menu", () => ({
DropdownMenu: ({ children }: any) => <>{children}</>,
DropdownMenuTrigger: ({ children }: any) => <>{children}</>,
DropdownMenuContent: ({ children }: any) => <>{children}</>,
DropdownMenuItem: ({ children, onClick }: any) => <button onClick={onClick}>{children}</button>,
}));
// Mock Button
vi.mock("@/modules/ui/components/button", () => ({
Button: ({ children, ...props }: any) => <button {...props}>{children}</button>,
}));
describe("SelectedRowSettings", () => {
const rows = [{ id: "r1" }, { id: "r2" }];
let table: any;
let deleteRowsAction: ReturnType<typeof vi.fn>;
let deleteAction: ReturnType<typeof vi.fn>;
let downloadRowsAction: ReturnType<typeof vi.fn>;
beforeEach(() => {
table = {
getFilteredSelectedRowModel: () => ({ rows }),
toggleAllPageRowsSelected: vi.fn(),
};
deleteRowsAction = vi.fn();
deleteAction = vi.fn(() => Promise.resolve());
downloadRowsAction = vi.fn();
// Reset all toast mocks before each test
vi.mocked(toast.error).mockClear();
vi.mocked(toast.success).mockClear();
});
afterEach(() => {
vi.resetAllMocks();
vi.clearAllMocks();
cleanup();
});
test("renders correct number of selected rows for responses", () => {
const mockTable = {
getFilteredSelectedRowModel: vi.fn().mockReturnValue({
rows: [{ id: "row1" }, { id: "row2" }],
}),
toggleAllPageRowsSelected: vi.fn(),
};
test("renders selected count and handles select all/clear selection", () => {
render(
<SelectedRowSettings
table={mockTable as any}
deleteRows={vi.fn()}
type="response"
deleteAction={vi.fn()}
/>
);
// We need to look for a text node that contains "2" but might have other text around it
const selectionText = screen.getByText((content) => content.includes("2"));
expect(selectionText).toBeInTheDocument();
// Check that we have the correct number of common text items
expect(screen.getByText("common.select_all")).toBeInTheDocument();
expect(screen.getByText("common.clear_selection")).toBeInTheDocument();
});
test("renders correct number of selected rows for contacts", () => {
const mockTable = {
getFilteredSelectedRowModel: vi.fn().mockReturnValue({
rows: [{ id: "contact1" }, { id: "contact2" }, { id: "contact3" }],
}),
toggleAllPageRowsSelected: vi.fn(),
};
render(
<SelectedRowSettings
table={mockTable as any}
deleteRows={vi.fn()}
table={table}
deleteRowsAction={deleteRowsAction}
deleteAction={deleteAction}
downloadRowsAction={downloadRowsAction}
type="contact"
deleteAction={vi.fn()}
/>
);
expect(screen.getByText("2 common.contacts common.selected")).toBeInTheDocument();
// We need to look for a text node that contains "3" but might have other text around it
const selectionText = screen.getByText((content) => content.includes("3"));
expect(selectionText).toBeInTheDocument();
fireEvent.click(screen.getByText("common.select_all"));
expect(table.toggleAllPageRowsSelected).toHaveBeenCalledWith(true);
// Check that the text contains contacts (using a function matcher)
const textWithContacts = screen.getByText((content) => content.includes("common.contacts"));
expect(textWithContacts).toBeInTheDocument();
fireEvent.click(screen.getByText("common.clear_selection"));
expect(table.toggleAllPageRowsSelected).toHaveBeenCalledWith(false);
});
test("select all option calls toggleAllPageRowsSelected with true", async () => {
const user = userEvent.setup();
const toggleAllPageRowsSelectedMock = vi.fn();
const mockTable = {
getFilteredSelectedRowModel: vi.fn().mockReturnValue({
rows: [{ id: "row1" }],
}),
toggleAllPageRowsSelected: toggleAllPageRowsSelectedMock,
};
test("does not render download when downloadRows prop is undefined", () => {
render(
<SelectedRowSettings
table={mockTable as any}
deleteRows={vi.fn()}
table={table}
deleteRowsAction={deleteRowsAction}
deleteAction={deleteAction}
type="response"
deleteAction={vi.fn()}
/>
);
await user.click(screen.getByText("common.select_all"));
expect(toggleAllPageRowsSelectedMock).toHaveBeenCalledWith(true);
expect(screen.queryByText("common.download")).toBeNull();
});
test("clear selection option calls toggleAllPageRowsSelected with false", async () => {
const user = userEvent.setup();
const toggleAllPageRowsSelectedMock = vi.fn();
const mockTable = {
getFilteredSelectedRowModel: vi.fn().mockReturnValue({
rows: [{ id: "row1" }],
}),
toggleAllPageRowsSelected: toggleAllPageRowsSelectedMock,
};
test("invokes downloadRows with correct formats", () => {
render(
<SelectedRowSettings
table={mockTable as any}
deleteRows={vi.fn()}
table={table}
deleteRowsAction={deleteRowsAction}
deleteAction={deleteAction}
downloadRowsAction={downloadRowsAction}
type="response"
deleteAction={vi.fn()}
/>
);
fireEvent.click(screen.getByText("common.download"));
fireEvent.click(screen.getByText("environments.surveys.summary.selected_responses_csv"));
expect(downloadRowsAction).toHaveBeenCalledWith(["r1", "r2"], "csv");
await user.click(screen.getByText("common.clear_selection"));
expect(toggleAllPageRowsSelectedMock).toHaveBeenCalledWith(false);
fireEvent.click(screen.getByText("common.download"));
fireEvent.click(screen.getByText("environments.surveys.summary.selected_responses_excel"));
expect(downloadRowsAction).toHaveBeenCalledWith(["r1", "r2"], "xlsx");
});
// For the tests that involve the modal dialog, we'll test the underlying functionality
// directly by mocking the deleteAction and deleteRows functions
test("deleteAction is called with the row ID when deleting", async () => {
const deleteActionMock = vi.fn().mockResolvedValue(undefined);
const deleteRowsMock = vi.fn();
// Create a spy for the deleteRows function
const mockTable = {
getFilteredSelectedRowModel: vi.fn().mockReturnValue({
rows: [{ id: "test-id-123" }],
}),
toggleAllPageRowsSelected: vi.fn(),
};
const { rerender } = render(
test("deletes rows successfully and shows success toast for contact", async () => {
deleteAction = vi.fn(() => Promise.resolve());
render(
<SelectedRowSettings
table={mockTable as any}
deleteRows={deleteRowsMock}
type="response"
deleteAction={deleteActionMock}
table={table}
deleteRowsAction={deleteRowsAction}
deleteAction={deleteAction}
downloadRowsAction={downloadRowsAction}
type="contact"
/>
);
// Test that the component renders the trash icon button
const trashIcon = document.querySelector(".lucide-trash2");
expect(trashIcon).toBeInTheDocument();
// Since we can't easily test the dialog interaction without mocking a lot of components,
// we can test the core functionality by calling the handlers directly
// We know that the deleteAction is called with the row ID
await deleteActionMock("test-id-123");
expect(deleteActionMock).toHaveBeenCalledWith("test-id-123");
// We know that deleteRows is called with an array of row IDs
deleteRowsMock(["test-id-123"]);
expect(deleteRowsMock).toHaveBeenCalledWith(["test-id-123"]);
// open delete dialog
fireEvent.click(screen.getAllByText("common.delete")[0]);
fireEvent.click(screen.getByText("Confirm Delete"));
await waitFor(() => {
expect(deleteAction).toHaveBeenCalledTimes(2);
expect(deleteRowsAction).toHaveBeenCalledWith(["r1", "r2"]);
expect(toast.success).toHaveBeenCalledWith("common.table_items_deleted_successfully");
});
});
test("toast.success is called on successful deletion", async () => {
const deleteActionMock = vi.fn().mockResolvedValue(undefined);
// We can test the toast directly
await deleteActionMock();
// In the component, after the deleteAction succeeds, it should call toast.success
toast.success("common.table_items_deleted_successfully");
// Verify that toast.success was called with the right message
expect(toast.success).toHaveBeenCalledWith("common.table_items_deleted_successfully");
test("handles delete error and shows error toast for response", async () => {
deleteAction = vi.fn(() => Promise.reject(new Error("fail delete")));
render(
<SelectedRowSettings
table={table}
deleteRowsAction={deleteRowsAction}
deleteAction={deleteAction}
downloadRowsAction={downloadRowsAction}
type="response"
/>
);
// open delete menu (trigger button)
const deleteTriggers = screen.getAllByText("common.delete");
fireEvent.click(deleteTriggers[0]);
fireEvent.click(screen.getByText("Confirm Delete"));
await waitFor(() => {
expect(toast.error).toHaveBeenCalledWith("fail delete");
});
});
test("toast.error is called on deletion error", async () => {
const errorMessage = "Failed to delete";
// We can test the error path directly
toast.error(errorMessage);
// Verify that toast.error was called with the right message
expect(toast.error).toHaveBeenCalledWith(errorMessage);
test("deletes rows successfully and shows success toast for response", async () => {
deleteAction = vi.fn(() => Promise.resolve());
render(
<SelectedRowSettings
table={table}
deleteRowsAction={deleteRowsAction}
deleteAction={deleteAction}
downloadRowsAction={downloadRowsAction}
type="response"
/>
);
// open delete dialog
fireEvent.click(screen.getAllByText("common.delete")[0]);
fireEvent.click(screen.getByText("Confirm Delete"));
await waitFor(() => {
expect(deleteAction).toHaveBeenCalledTimes(2);
expect(deleteRowsAction).toHaveBeenCalledWith(["r1", "r2"]);
expect(toast.success).toHaveBeenCalledWith("common.table_items_deleted_successfully");
});
});
test("toast.error is called with generic message on unknown error", async () => {
// We can test the unknown error path directly
toast.error("common.an_unknown_error_occurred_while_deleting_table_items");
// Verify that toast.error was called with the generic message
expect(toast.error).toHaveBeenCalledWith("common.an_unknown_error_occurred_while_deleting_table_items");
test("handles delete error for non-Error and shows generic error toast", async () => {
deleteAction = vi.fn(() => Promise.reject("fail nonerror")); // Changed from Error to string
render(
<SelectedRowSettings
table={table}
deleteRowsAction={deleteRowsAction}
deleteAction={deleteAction}
downloadRowsAction={downloadRowsAction}
type="contact"
/>
);
// open delete menu (trigger button)
const deleteTriggers = screen.getAllByText("common.delete");
fireEvent.click(deleteTriggers[0]);
fireEvent.click(screen.getByText("Confirm Delete"));
await waitFor(() => {
expect(toast.error).toHaveBeenCalledWith("common.an_unknown_error_occurred_while_deleting_table_items");
});
});
});

View File

@@ -1,25 +1,34 @@
"use client";
import { capitalizeFirstLetter } from "@/lib/utils/strings";
import { Button } from "@/modules/ui/components/button";
import { DeleteDialog } from "@/modules/ui/components/delete-dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/modules/ui/components/dropdown-menu";
import { Table } from "@tanstack/react-table";
import { useTranslate } from "@tolgee/react";
import { Trash2Icon } from "lucide-react";
import { ArrowDownToLineIcon, Trash2Icon } from "lucide-react";
import { useCallback, useState } from "react";
import { toast } from "react-hot-toast";
interface SelectedRowSettingsProps<T> {
table: Table<T>;
deleteRows: (rowId: string[]) => void;
deleteRowsAction: (rowId: string[]) => void;
type: "response" | "contact";
deleteAction: (id: string) => Promise<void>;
downloadRowsAction?: (rowIds: string[], format: string) => void;
}
export const SelectedRowSettings = <T,>({
table,
deleteRows,
deleteRowsAction,
type,
deleteAction,
downloadRowsAction,
}: SelectedRowSettingsProps<T>) => {
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
@@ -40,13 +49,11 @@ export const SelectedRowSettings = <T,>({
setIsDeleting(true);
const rowsToBeDeleted = table.getFilteredSelectedRowModel().rows.map((row) => row.id);
if (type === "response") {
await Promise.all(rowsToBeDeleted.map((responseId) => deleteAction(responseId)));
} else if (type === "contact") {
await Promise.all(rowsToBeDeleted.map((responseId) => deleteAction(responseId)));
if (type === "response" || type === "contact") {
await Promise.all(rowsToBeDeleted.map((rowId) => deleteAction(rowId)));
}
deleteRows(rowsToBeDeleted);
deleteRowsAction(rowsToBeDeleted);
toast.success(t("common.table_items_deleted_successfully", { type: capitalizeFirstLetter(type) }));
} catch (error) {
if (error instanceof Error) {
@@ -64,34 +71,72 @@ export const SelectedRowSettings = <T,>({
}
};
// Handle download selected rows
const handleDownloadSelectedRows = async (format: string) => {
const rowsToDownload = table.getFilteredSelectedRowModel().rows.map((row) => row.id);
if (downloadRowsAction && rowsToDownload.length > 0) {
downloadRowsAction(rowsToDownload, format);
}
};
// Helper component for the separator
const Separator = () => <div>|</div>;
// Helper component for selectable options
const SelectableOption = ({ label, onClick }: { label: string; onClick: () => void }) => (
<div className="cursor-pointer rounded-md p-1 hover:bg-slate-500" onClick={onClick}>
{label}
</div>
);
return (
<div className="flex items-center gap-x-2 rounded-md bg-slate-900 p-1 px-2 text-xs text-white">
<div className="lowercase">
{selectedRowCount} {type === "response" ? t("common.responses") : t("common.contacts")}
{t("common.selected")}
</div>
<Separator />
<SelectableOption label={t("common.select_all")} onClick={() => handleToggleAllRowsSelection(true)} />
<Separator />
<SelectableOption
label={t("common.clear_selection")}
onClick={() => handleToggleAllRowsSelection(false)}
/>
<Separator />
<div
className="cursor-pointer rounded-md bg-slate-500 p-1 hover:bg-slate-600"
onClick={() => setIsDeleteDialogOpen(true)}>
<Trash2Icon strokeWidth={1.5} className="h-4 w-4" />
<>
<div className="bg-primary flex items-center gap-x-2 rounded-md p-1 px-2 text-xs text-white">
<div className="lowercase">
{selectedRowCount} {t(`common.${type}`)}s {t("common.selected")}
</div>
<Separator />
<Button
variant="outline"
size="sm"
className="h-6 border-none px-2"
onClick={() => handleToggleAllRowsSelection(true)}>
{t("common.select_all")}
</Button>
<Button
variant="outline"
size="sm"
className="h-6 border-none px-2"
onClick={() => handleToggleAllRowsSelection(false)}>
{t("common.clear_selection")}
</Button>
<Separator />
{downloadRowsAction && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" className="h-6 gap-1 border-none px-2">
{t("common.download")}
<ArrowDownToLineIcon />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem
onClick={() => {
handleDownloadSelectedRows("csv");
}}>
<p className="text-slate-700">{t("environments.surveys.summary.selected_responses_csv")}</p>
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
handleDownloadSelectedRows("xlsx");
}}>
<p>{t("environments.surveys.summary.selected_responses_excel")}</p>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
<Button
variant="secondary"
size="sm"
className="h-6 gap-1 px-2"
onClick={() => setIsDeleteDialogOpen(true)}>
{t("common.delete")}
<Trash2Icon />
</Button>
</div>
<DeleteDialog
open={isDeleteDialogOpen}
@@ -100,6 +145,6 @@ export const SelectedRowSettings = <T,>({
onDelete={handleDelete}
isDeleting={isDeleting}
/>
</div>
</>
);
};

View File

@@ -4,8 +4,8 @@ export const NetPromoterScoreIcon: React.FC<React.SVGProps<SVGSVGElement>> = (pr
<g id="Frame">
<path
id="Vector"
fill-rule="evenodd"
clip-rule="evenodd"
fillRule="evenodd"
clipRule="evenodd"
d="M2.25 2.25C2.05109 2.25 1.86032 2.32902 1.71967 2.46967C1.57902 2.61032 1.5 2.80109 1.5 3C1.5 3.19891 1.57902 3.38968 1.71967 3.53033C1.86032 3.67098 2.05109 3.75 2.25 3.75H3V14.25C3 15.0456 3.31607 15.8087 3.87868 16.3713C4.44129 16.9339 5.20435 17.25 6 17.25H7.21L6.038 20.763C5.97514 20.9518 5.98988 21.1579 6.07896 21.3359C6.16804 21.5138 6.32417 21.6491 6.513 21.712C6.70183 21.7749 6.9079 21.7601 7.08588 21.671C7.26385 21.582 7.39914 21.4258 7.462 21.237L7.791 20.25H16.209L16.539 21.237C16.6073 21.4186 16.7433 21.5666 16.9184 21.6501C17.0935 21.7335 17.2941 21.7459 17.4782 21.6845C17.6622 21.6232 17.8153 21.4929 17.9053 21.3211C17.9954 21.1493 18.0153 20.9492 17.961 20.763L16.791 17.25H18C18.7956 17.25 19.5587 16.9339 20.1213 16.3713C20.6839 15.8087 21 15.0456 21 14.25V3.75H21.75C21.9489 3.75 22.1397 3.67098 22.2803 3.53033C22.421 3.38968 22.5 3.19891 22.5 3C22.5 2.80109 22.421 2.61032 22.2803 2.46967C22.1397 2.32902 21.9489 2.25 21.75 2.25H2.25ZM8.29 18.75L8.79 17.25H15.21L15.71 18.75H8.29ZM15.75 6.75C15.75 6.55109 15.671 6.36032 15.5303 6.21967C15.3897 6.07902 15.1989 6 15 6C14.8011 6 14.6103 6.07902 14.4697 6.21967C14.329 6.36032 14.25 6.55109 14.25 6.75V12.75C14.25 12.9489 14.329 13.1397 14.4697 13.2803C14.6103 13.421 14.8011 13.5 15 13.5C15.1989 13.5 15.3897 13.421 15.5303 13.2803C15.671 13.1397 15.75 12.9489 15.75 12.75V6.75ZM12.75 9C12.75 8.80109 12.671 8.61032 12.5303 8.46967C12.3897 8.32902 12.1989 8.25 12 8.25C11.8011 8.25 11.6103 8.32902 11.4697 8.46967C11.329 8.61032 11.25 8.80109 11.25 9V12.75C11.25 12.9489 11.329 13.1397 11.4697 13.2803C11.6103 13.421 11.8011 13.5 12 13.5C12.1989 13.5 12.3897 13.421 12.5303 13.2803C12.671 13.1397 12.75 12.9489 12.75 12.75V9ZM9.75 11.25C9.75 11.0511 9.67098 10.8603 9.53033 10.7197C9.38968 10.579 9.19891 10.5 9 10.5C8.80109 10.5 8.61032 10.579 8.46967 10.7197C8.32902 10.8603 8.25 11.0511 8.25 11.25V12.75C8.25 12.9489 8.32902 13.1397 8.46967 13.2803C8.61032 13.421 8.80109 13.5 9 13.5C9.19891 13.5 9.38968 13.421 9.53033 13.2803C9.67098 13.1397 9.75 12.9489 9.75 12.75V11.25Z"
fill="white"
/>

View File

@@ -127,9 +127,9 @@ input[type="search"]::-ms-reveal {
}
input[type="range"]::-webkit-slider-thumb {
background: #0f172a;
height: 20px;
width: 20px;
border-radius: 50%;
-webkit-appearance: none;
background: #0f172a;
}

View File

@@ -26,11 +26,6 @@ const nextConfig = {
"app/api/packages": ["../../packages/js-core/dist/*", "../../packages/surveys/dist/*"],
"/api/auth/**/*": ["../../node_modules/jose/**/*"],
},
i18n: {
locales: ["en-US", "de-DE", "fr-FR", "pt-BR", "zh-Hant-TW", "pt-PT"],
localeDetection: false,
defaultLocale: "en-US",
},
experimental: {},
transpilePackages: ["@formbricks/database"],
images: {

View File

@@ -117,11 +117,9 @@
"prismjs": "1.30.0",
"qr-code-styling": "1.9.2",
"qrcode": "1.5.4",
"react": "19.1.0",
"react-colorful": "5.6.1",
"react-confetti": "6.4.0",
"react-day-picker": "9.6.7",
"react-dom": "19.1.0",
"react-hook-form": "7.56.2",
"react-hot-toast": "2.5.2",
"react-turnstile": "1.1.4",

View File

@@ -181,7 +181,7 @@ export const createSurvey = async (page: Page, params: CreateSurveyParams) => {
await page.locator('input[name="subheader"]').fill(params.openTextQuestion.description);
await page.getByLabel("Placeholder").fill(params.openTextQuestion.placeholder);
await page.locator("p").filter({ hasText: params.openTextQuestion.question }).click();
await page.locator("h3").filter({ hasText: params.openTextQuestion.question }).click();
// Single Select Question
await page
@@ -403,7 +403,7 @@ export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWith
await page.locator('input[name="subheader"]').fill(params.openTextQuestion.description);
await page.getByLabel("Placeholder").fill(params.openTextQuestion.placeholder);
await page.locator("p").filter({ hasText: params.openTextQuestion.question }).click();
await page.locator("h3").filter({ hasText: params.openTextQuestion.question }).click();
// Single Select Question
await page
@@ -606,8 +606,8 @@ export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWith
// Adding logic
// Open Text Question
await page.locator("p", { hasText: params.openTextQuestion.question }).click();
await page.getByRole("button", { name: "Show Advanced Settings" }).click();
await page.getByRole("heading", { name: params.openTextQuestion.question }).click();
await page.getByRole("button", { name: "Toggle advanced settings" }).click();
await page.getByRole("button", { name: "Add logic" }).click();
await page.locator("#condition-0-0-conditionOperator").click();
await page.getByRole("option", { name: "is submitted" }).click();
@@ -637,8 +637,8 @@ export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWith
await page.getByRole("textbox", { name: "Value" }).fill("This ");
// Single Select Question
await page.locator("p", { hasText: params.singleSelectQuestion.question }).click();
await page.getByRole("button", { name: "Show Advanced Settings" }).click();
await page.getByRole("heading", { name: params.singleSelectQuestion.question }).click();
await page.getByRole("button", { name: "Toggle advanced settings" }).click();
await page.getByRole("button", { name: "Add logic" }).click();
await page.locator("#condition-0-0-conditionOperator").click();
await page.getByRole("option", { name: "Equals one of" }).click();
@@ -665,8 +665,8 @@ export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWith
await page.getByRole("textbox", { name: "Value" }).fill("is ");
// Multi Select Question
await page.locator("p", { hasText: params.multiSelectQuestion.question }).click();
await page.getByRole("button", { name: "Show Advanced Settings" }).click();
await page.getByRole("heading", { name: params.multiSelectQuestion.question }).click();
await page.getByRole("button", { name: "Toggle advanced settings" }).click();
await page.getByRole("button", { name: "Add logic" }).click();
await page.locator("#condition-0-0-conditionOperator").click();
await page.getByRole("option", { name: "Includes all of" }).click();
@@ -706,8 +706,8 @@ export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWith
await page.getByRole("textbox", { name: "Value" }).fill("a ");
// Picture Select Question
await page.locator("p", { hasText: params.pictureSelectQuestion.question }).click();
await page.getByRole("button", { name: "Show Advanced Settings" }).click();
await page.getByRole("heading", { name: params.pictureSelectQuestion.question }).click();
await page.getByRole("button", { name: "Toggle advanced settings" }).click();
await page.getByRole("button", { name: "Add logic" }).click();
await page.locator("#condition-0-0-conditionOperator").click();
await page.getByRole("option", { name: "is submitted" }).click();
@@ -731,8 +731,8 @@ export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWith
await page.getByRole("textbox", { name: "Value" }).fill("secret ");
// Rating Question
await page.locator("p", { hasText: params.ratingQuestion.question }).click();
await page.getByRole("button", { name: "Show Advanced Settings" }).click();
await page.getByRole("heading", { name: params.ratingQuestion.question }).click();
await page.getByRole("button", { name: "Toggle advanced settings" }).click();
await page.getByRole("button", { name: "Add logic" }).click();
await page.locator("#condition-0-0-conditionOperator").click();
await page.getByRole("option", { name: ">=" }).click();
@@ -758,8 +758,8 @@ export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWith
await page.getByRole("textbox", { name: "Value" }).fill("message ");
// NPS Question
await page.locator("p", { hasText: params.npsQuestion.question }).click();
await page.getByRole("button", { name: "Show Advanced Settings" }).click();
await page.getByRole("heading", { name: params.npsQuestion.question }).click();
await page.getByRole("button", { name: "Toggle advanced settings" }).click();
await page.getByRole("button", { name: "Add logic" }).click();
await page.locator("#condition-0-0-conditionOperator").click();
await page.getByRole("option", { name: ">", exact: true }).click();
@@ -819,8 +819,8 @@ export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWith
await page.getByRole("textbox", { name: "Value" }).fill("for ");
// Ranking Question
await page.locator("p", { hasText: params.ranking.question }).click();
await page.getByRole("button", { name: "Show Advanced Settings" }).click();
await page.getByRole("heading", { name: params.ranking.question }).click();
await page.getByRole("button", { name: "Toggle advanced settings" }).click();
await page.getByRole("button", { name: "Add logic" }).click();
await page.locator("#condition-0-0-conditionOperator").click();
await page.getByRole("option", { name: "is skipped" }).click();
@@ -844,8 +844,8 @@ export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWith
await page.getByRole("textbox", { name: "Value" }).fill("e2e ");
// Matrix Question
await page.locator("p", { hasText: params.matrix.question }).click();
await page.getByRole("button", { name: "Show Advanced Settings" }).click();
await page.getByRole("heading", { name: params.matrix.question }).click();
await page.getByRole("button", { name: "Toggle advanced settings" }).click();
await page.getByRole("button", { name: "Add logic" }).click();
await page.locator("#condition-0-0-conditionOperator").click();
await page.getByRole("option", { name: "is completely submitted" }).click();
@@ -877,8 +877,8 @@ export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWith
await page.getByRole("option", { name: params.ctaQuestion.question }).click();
// CTA Question
await page.locator("p", { hasText: params.ctaQuestion.question }).click();
await page.getByRole("button", { name: "Show Advanced Settings" }).click();
await page.getByRole("heading", { name: params.ctaQuestion.question }).click();
await page.getByRole("button", { name: "Toggle advanced settings" }).click();
await page.getByRole("button", { name: "Add logic" }).click();
await page.locator("#condition-0-0-conditionOperator").click();
await page.getByRole("option", { name: "is skipped" }).click();
@@ -905,8 +905,8 @@ export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWith
await page.locator("#action-0-value-input").fill("1");
// Consent Question
await page.locator("p", { hasText: params.consentQuestion.question }).click();
await page.getByRole("button", { name: "Show Advanced Settings" }).click();
await page.getByRole("heading", { name: params.consentQuestion.question }).click();
await page.getByRole("button", { name: "Toggle advanced settings" }).click();
await page.getByRole("button", { name: "Add logic" }).click();
await page.locator("#action-0-objective").click();
await page.getByRole("option", { name: "Calculate" }).click();
@@ -918,8 +918,8 @@ export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWith
await page.locator("#action-0-value-input").fill("2");
// File Upload Question
await page.locator("p", { hasText: params.fileUploadQuestion.question }).click();
await page.getByRole("button", { name: "Show Advanced Settings" }).click();
await page.getByRole("heading", { name: params.fileUploadQuestion.question }).click();
await page.getByRole("button", { name: "Toggle advanced settings" }).click();
await page.getByRole("button", { name: "Add logic" }).click();
await page.locator("#action-0-objective").click();
await page.getByRole("option", { name: "Calculate" }).click();
@@ -936,7 +936,7 @@ export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWith
const tomorrow = new Date(new Date().setDate(new Date().getDate() + 1)).toISOString().split("T")[0];
await page.getByRole("main").getByText(params.date.question).click();
await page.getByRole("button", { name: "Show Advanced Settings" }).click();
await page.getByRole("button", { name: "Toggle advanced settings" }).click();
await page.getByRole("button", { name: "Add logic" }).click();
await page.getByPlaceholder("Value").fill(today);
@@ -965,8 +965,8 @@ export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWith
await page.locator("#action-0-value-input").fill("1");
// Cal Question
await page.locator("p", { hasText: params.cal.question }).click();
await page.getByRole("button", { name: "Show Advanced Settings" }).click();
await page.getByRole("heading", { name: params.cal.question }).click();
await page.getByRole("button", { name: "Toggle advanced settings" }).click();
await page.getByRole("button", { name: "Add logic" }).click();
await page.locator("#condition-0-0-conditionOperator").click();
await page.getByRole("option", { name: "is skipped" }).click();
@@ -980,8 +980,8 @@ export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWith
await page.locator("#action-0-value-input").fill("1");
// Address Question
await page.locator("p", { hasText: params.address.question }).click();
await page.getByRole("button", { name: "Show Advanced Settings" }).click();
await page.getByRole("heading", { name: params.address.question }).click();
await page.getByRole("button", { name: "Toggle advanced settings" }).click();
await page.getByRole("button", { name: "Add logic" }).click();
await page.locator("#action-0-objective").click();
await page.getByRole("option", { name: "Calculate" }).click();

View File

@@ -12,8 +12,8 @@ if (SENTRY_DSN) {
Sentry.init({
dsn: SENTRY_DSN,
// Adjust this value in production, or use tracesSampler for greater control
tracesSampleRate: 1,
// No tracing while Sentry doesn't update to telemetry 2.0.0 - https://github.com/getsentry/sentry-javascript/issues/15737
tracesSampleRate: 0,
// Setting this option to true will print useful information to the console while you're setting up Sentry.
debug: false,

View File

@@ -11,8 +11,8 @@ if (SENTRY_DSN) {
Sentry.init({
dsn: SENTRY_DSN,
// Adjust this value in production, or use tracesSampler for greater control
tracesSampleRate: 1,
// No tracing while Sentry doesn't update to telemetry 2.0.0 - https://github.com/getsentry/sentry-javascript/issues/15737
tracesSampleRate: 0,
// Setting this option to true will print useful information to the console while you're setting up Sentry.
debug: false,

View File

@@ -187,8 +187,8 @@ x-environment: &environment
# (Role Management is an Enterprise feature)
# AUTH_SSO_DEFAULT_TEAM_ID=
# Set the below to 1 to disable the user management UI
# DISABLE_USER_MANAGEMENT: 0
# Configure the minimum role for user management from UI(owner, manager, disabled)
# USER_MANAGEMENT_MINIMUM_ROLE="manager"
services:
postgres:

View File

@@ -8,67 +8,67 @@ icon: "code"
These variables are present inside your machine's docker-compose file. Restart the docker containers if you change any variables for them to take effect.
| Variable | Description | Required | Default |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------- |
| WEBAPP_URL | Base URL of the site. | required | http://localhost:3000 |
| NEXTAUTH_URL | Location of the auth server. This should normally be the same as WEBAPP_URL | required | http://localhost:3000 |
| DATABASE_URL | Database URL with credentials. | required | |
| NEXTAUTH_SECRET | Secret for NextAuth, used for session signing and encryption. | required | (Generated by the user, must not exceed 32 bytes, `openssl rand -hex 32`) |
| ENCRYPTION_KEY | Secret for used by Formbricks for data encryption | required | (Generated by the user, must not exceed 32 bytes, `openssl rand -hex 32`) |
| CRON_SECRET | API Secret for running cron jobs. | required | (Generated by the user, must not exceed 32 bytes, `openssl rand -hex 32`) |
| LOG_LEVEL | Minimum log level (debug, info, warn, error, fatal) | optional | info |
| UPLOADS_DIR | Local directory for storing uploads. | optional | ./uploads |
| S3_ACCESS_KEY | Access key for S3. | optional | (resolved by the AWS SDK) |
| S3_SECRET_KEY | Secret key for S3. | optional | (resolved by the AWS SDK) |
| S3_REGION | Region for S3. | optional | (resolved by the AWS SDK) |
| S3_BUCKET_NAME | S3 bucket name for data storage. Formbricks enables S3 storage when this is set. | optional (required if S3 is enabled) | |
| S3_ENDPOINT_URL | Endpoint for S3. | optional | (resolved by the AWS SDK) |
| SAML_DATABASE_URL | Database URL for SAML. | optional | postgres://postgres:@localhost:5432/formbricks-saml |
| PRIVACY_URL | URL for privacy policy. | optional | |
| TERMS_URL | URL for terms of service. | optional | |
| IMPRINT_URL | URL for imprint. | optional | |
| IMPRINT_ADDRESS | Address for imprint. | optional | |
| EMAIL_AUTH_DISABLED | Disables the ability for users to signup or login via email and password if set to 1. | optional | |
| PASSWORD_RESET_DISABLED | Disables password reset functionality if set to 1. | optional | |
| EMAIL_VERIFICATION_DISABLED | Disables email verification if set to 1. | optional | |
| RATE_LIMITING_DISABLED | Disables rate limiting if set to 1. | optional | |
| INVITE_DISABLED | Disables the ability for invited users to create an account if set to 1. | optional | |
| MAIL_FROM | Email address to send emails from. | optional (required if email services are to be enabled) | |
| MAIL_FROM_NAME | Email name/title to send emails from. | optional (required if email services are to be enabled) | |
| SMTP_HOST | Host URL of your SMTP server. | optional (required if email services are to be enabled) | |
| SMTP_PORT | Host Port of your SMTP server. | optional (required if email services are to be enabled) | |
| SMTP_USER | Username for your SMTP Server. | optional (required if email services are to be enabled) | |
| SMTP_PASSWORD | Password for your SMTP Server. | optional (required if email services are to be enabled) | |
| SMTP_AUTHENTICATED | If set to 0, the server will not require SMTP_USER and SMTP_PASSWORD(default is 1) | optional | |
| SMTP_SECURE_ENABLED | SMTP secure connection. For using TLS, set to 1 else to 0. | optional (required if email services are to be enabled) | |
| SMTP_REJECT_UNAUTHORIZED_TLS | If set to 0, the server will accept connections without requiring authorization from the list of supplied CAs. | optional | 1 |
| TURNSTILE_SITE_KEY | Site key for Turnstile. | optional | |
| TURNSTILE_SECRET_KEY | Secret key for Turnstile. | optional | |
| RECAPTCHA_SITE_KEY | Site key for survey responses recaptcha bot protection | optional | |
| RECAPTCHA_SECRET_KEY | Secret key for recaptcha bot protection. | optional | |
| GITHUB_ID | Client ID for GitHub. | optional (required if GitHub auth is enabled) | |
| GITHUB_SECRET | Secret for GitHub. | optional (required if GitHub auth is enabled) | |
| GOOGLE_CLIENT_ID | Client ID for Google. | optional (required if Google auth is enabled) | |
| GOOGLE_CLIENT_SECRET | Secret for Google. | optional (required if Google auth is enabled) | |
| STRIPE_SECRET_KEY | Secret key for Stripe integration. | optional | |
| STRIPE_WEBHOOK_SECRET | Webhook secret for Stripe integration. | optional | |
| TELEMETRY_DISABLED | Disables telemetry if set to 1. | optional | |
| DEFAULT_BRAND_COLOR | Default brand color for your app (Can be overwritten from the UI as well). | optional | #64748b |
| DEFAULT_ORGANIZATION_ID | Automatically assign new users to a specific organization when joining | optional | |
| OIDC_DISPLAY_NAME | Display name for Custom OpenID Connect Provider | optional | |
| OIDC_CLIENT_ID | Client ID for Custom OpenID Connect Provider | optional (required if OIDC auth is enabled) | |
| OIDC_CLIENT_SECRET | Secret for Custom OpenID Connect Provider | optional (required if OIDC auth is enabled) | |
| OIDC_ISSUER | Issuer URL for Custom OpenID Connect Provider (should have .well-known configured at this) | optional (required if OIDC auth is enabled) | |
| OIDC_SIGNING_ALGORITHM | Signing Algorithm for Custom OpenID Connect Provider | optional | RS256 |
| OPENTELEMETRY_LISTENER_URL | URL for OpenTelemetry listener inside Formbricks. | optional | |
| UNKEY_ROOT_KEY | Key for the [Unkey](https://www.unkey.com/) service. This is used for Rate Limiting for management API. | optional | |
| PROMETHEUS_ENABLED | Enables Prometheus metrics if set to 1. | optional | |
| PROMETHEUS_EXPORTER_PORT | Port for Prometheus metrics. | optional | 9090 |
| DOCKER_CRON_ENABLED | Controls whether cron jobs run in the Docker image. Set to 0 to disable (useful for cluster setups). | optional | 1 |
| DEFAULT_TEAM_ID | Default team ID for new users. | optional | |
| SURVEY_URL | Set this to change the domain of the survey. | optional | WEBAPP_URL |
| SENTRY_DSN | Set this to track errors and monitor performance in Sentry. | optional |
| SENTRY_AUTH_TOKEN | Set this if you want to make errors more readable in Sentry. | optional |
| DISABLE_USER_MANAGEMENT | Set this to hide the user management UI. | optional |
| Variable | Description | Required | Default |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------- |
| WEBAPP_URL | Base URL of the site. | required | http://localhost:3000 |
| NEXTAUTH_URL | Location of the auth server. This should normally be the same as WEBAPP_URL | required | http://localhost:3000 |
| DATABASE_URL | Database URL with credentials. | required | |
| NEXTAUTH_SECRET | Secret for NextAuth, used for session signing and encryption. | required | (Generated by the user, must not exceed 32 bytes, `openssl rand -hex 32`) |
| ENCRYPTION_KEY | Secret for used by Formbricks for data encryption | required | (Generated by the user, must not exceed 32 bytes, `openssl rand -hex 32`) |
| CRON_SECRET | API Secret for running cron jobs. | required | (Generated by the user, must not exceed 32 bytes, `openssl rand -hex 32`) |
| LOG_LEVEL | Minimum log level (debug, info, warn, error, fatal) | optional | info |
| UPLOADS_DIR | Local directory for storing uploads. | optional | ./uploads |
| S3_ACCESS_KEY | Access key for S3. | optional | (resolved by the AWS SDK) |
| S3_SECRET_KEY | Secret key for S3. | optional | (resolved by the AWS SDK) |
| S3_REGION | Region for S3. | optional | (resolved by the AWS SDK) |
| S3_BUCKET_NAME | S3 bucket name for data storage. Formbricks enables S3 storage when this is set. | optional (required if S3 is enabled) | |
| S3_ENDPOINT_URL | Endpoint for S3. | optional | (resolved by the AWS SDK) |
| SAML_DATABASE_URL | Database URL for SAML. | optional | postgres://postgres:@localhost:5432/formbricks-saml |
| PRIVACY_URL | URL for privacy policy. | optional | |
| TERMS_URL | URL for terms of service. | optional | |
| IMPRINT_URL | URL for imprint. | optional | |
| IMPRINT_ADDRESS | Address for imprint. | optional | |
| EMAIL_AUTH_DISABLED | Disables the ability for users to signup or login via email and password if set to 1. | optional | |
| PASSWORD_RESET_DISABLED | Disables password reset functionality if set to 1. | optional | |
| EMAIL_VERIFICATION_DISABLED | Disables email verification if set to 1. | optional | |
| RATE_LIMITING_DISABLED | Disables rate limiting if set to 1. | optional | |
| INVITE_DISABLED | Disables the ability for invited users to create an account if set to 1. | optional | |
| MAIL_FROM | Email address to send emails from. | optional (required if email services are to be enabled) | |
| MAIL_FROM_NAME | Email name/title to send emails from. | optional (required if email services are to be enabled) | |
| SMTP_HOST | Host URL of your SMTP server. | optional (required if email services are to be enabled) | |
| SMTP_PORT | Host Port of your SMTP server. | optional (required if email services are to be enabled) | |
| SMTP_USER | Username for your SMTP Server. | optional (required if email services are to be enabled) | |
| SMTP_PASSWORD | Password for your SMTP Server. | optional (required if email services are to be enabled) | |
| SMTP_AUTHENTICATED | If set to 0, the server will not require SMTP_USER and SMTP_PASSWORD(default is 1) | optional | |
| SMTP_SECURE_ENABLED | SMTP secure connection. For using TLS, set to 1 else to 0. | optional (required if email services are to be enabled) | |
| SMTP_REJECT_UNAUTHORIZED_TLS | If set to 0, the server will accept connections without requiring authorization from the list of supplied CAs. | optional | 1 |
| TURNSTILE_SITE_KEY | Site key for Turnstile. | optional | |
| TURNSTILE_SECRET_KEY | Secret key for Turnstile. | optional | |
| RECAPTCHA_SITE_KEY | Site key for survey responses recaptcha bot protection | optional | |
| RECAPTCHA_SECRET_KEY | Secret key for recaptcha bot protection. | optional | |
| GITHUB_ID | Client ID for GitHub. | optional (required if GitHub auth is enabled) | |
| GITHUB_SECRET | Secret for GitHub. | optional (required if GitHub auth is enabled) | |
| GOOGLE_CLIENT_ID | Client ID for Google. | optional (required if Google auth is enabled) | |
| GOOGLE_CLIENT_SECRET | Secret for Google. | optional (required if Google auth is enabled) | |
| STRIPE_SECRET_KEY | Secret key for Stripe integration. | optional | |
| STRIPE_WEBHOOK_SECRET | Webhook secret for Stripe integration. | optional | |
| TELEMETRY_DISABLED | Disables telemetry if set to 1. | optional | |
| DEFAULT_BRAND_COLOR | Default brand color for your app (Can be overwritten from the UI as well). | optional | #64748b |
| DEFAULT_ORGANIZATION_ID | Automatically assign new users to a specific organization when joining | optional | |
| OIDC_DISPLAY_NAME | Display name for Custom OpenID Connect Provider | optional | |
| OIDC_CLIENT_ID | Client ID for Custom OpenID Connect Provider | optional (required if OIDC auth is enabled) | |
| OIDC_CLIENT_SECRET | Secret for Custom OpenID Connect Provider | optional (required if OIDC auth is enabled) | |
| OIDC_ISSUER | Issuer URL for Custom OpenID Connect Provider (should have .well-known configured at this) | optional (required if OIDC auth is enabled) | |
| OIDC_SIGNING_ALGORITHM | Signing Algorithm for Custom OpenID Connect Provider | optional | RS256 |
| OPENTELEMETRY_LISTENER_URL | URL for OpenTelemetry listener inside Formbricks. | optional | |
| UNKEY_ROOT_KEY | Key for the [Unkey](https://www.unkey.com/) service. This is used for Rate Limiting for management API. | optional | |
| PROMETHEUS_ENABLED | Enables Prometheus metrics if set to 1. | optional | |
| PROMETHEUS_EXPORTER_PORT | Port for Prometheus metrics. | optional | 9090 |
| DOCKER_CRON_ENABLED | Controls whether cron jobs run in the Docker image. Set to 0 to disable (useful for cluster setups). | optional | 1 |
| DEFAULT_TEAM_ID | Default team ID for new users. | optional | |
| SURVEY_URL | Set this to change the domain of the survey. | optional | WEBAPP_URL |
| SENTRY_DSN | Set this to track errors and monitor performance in Sentry. | optional |
| SENTRY_AUTH_TOKEN | Set this if you want to make errors more readable in Sentry. | optional |
| USER_MANAGEMENT_MINIMUM_ROLE | Set this to control which roles can access user management features. Accepted values: "owner", "manager", "disabled" | optional | manager |
Note: If you want to configure something that is not possible via above, please open an issue on our GitHub repo here or reach out to us on Github Discussions and well try our best to work out a solution with you.
Note: If you want to configure something that is not possible via above, please open an issue on our GitHub repo here or reach out to us on Github Discussions and we'll try our best to work out a solution with you.

View File

@@ -10,6 +10,7 @@
"schema": "packages/database/schema.prisma"
},
"scripts": {
"clean:all": "turbo run clean && rimraf node_modules pnpm-lock.yaml .turbo coverage out",
"clean": "turbo run clean && rimraf node_modules .turbo coverage out",
"build": "turbo run build",
"build:dev": "turbo run build:dev",
@@ -35,6 +36,10 @@
"fb-migrate-dev": "pnpm --filter @formbricks/database create-migration && pnpm prisma generate",
"tolgee-pull": "BRANCH_NAME=$(node -p \"require('./branch.json').branchName\") && tolgee pull --tags \"draft:$BRANCH_NAME\" \"production\" && prettier --write ./apps/web/locales/*.json"
},
"dependencies": {
"react": "19.1.0",
"react-dom": "19.1.0"
},
"devDependencies": {
"@azure/microsoft-playwright-testing": "1.0.0-beta.7",
"@formbricks/eslint-config": "workspace:*",

View File

@@ -2,10 +2,13 @@ import Pino, { type Logger, type LoggerOptions, stdSerializers } from "pino";
import { type TLogLevel, ZLogLevel } from "../types/logger";
const IS_PRODUCTION = !process.env.NODE_ENV || process.env.NODE_ENV === "production";
const IS_BUILD = process.env.NEXT_PHASE === "phase-production-build";
const getLogLevel = (): TLogLevel => {
let logLevel: TLogLevel = "info";
if (IS_PRODUCTION) logLevel = "warn";
if (IS_BUILD) logLevel = "error"; // Only show errors during build
const envLogLevel = process.env.LOG_LEVEL;

View File

@@ -57,7 +57,7 @@ export function QuestionMedia({ imgUrl, videoUrl, altText = "Image" }: QuestionM
setIsLoading(false);
}}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share"
referrerpolicy="strict-origin-when-cross-origin"
referrerPolicy="strict-origin-when-cross-origin"
/>
</div>
</div>

View File

@@ -1,5 +1,5 @@
import "@testing-library/jest-dom/vitest";
import { cleanup, render, screen } from "@testing-library/preact";
import { cleanup, fireEvent, render, screen } from "@testing-library/preact";
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, test, vi } from "vitest";
import { type TSurveyOpenTextQuestion, TSurveyQuestionTypeEnum } from "@formbricks/types/surveys/types";
@@ -76,10 +76,7 @@ describe("OpenTextQuestion", () => {
render(<OpenTextQuestion {...defaultProps} onChange={onChange} />);
const input = screen.getByPlaceholderText("Type here...");
// Directly set the input value and trigger the input event
Object.defineProperty(input, "value", { value: "Hello" });
input.dispatchEvent(new Event("input", { bubbles: true }));
fireEvent.input(input, { target: { value: "Hello" } });
expect(onChange).toHaveBeenCalledWith({ q1: "Hello" });
});
@@ -163,4 +160,291 @@ describe("OpenTextQuestion", () => {
expect(focusMock).toHaveBeenCalled();
});
test("handles input change for textarea with resize functionality", async () => {
// Create a spy on the Element.prototype to monitor style changes
const styleSpy = vi.spyOn(HTMLElement.prototype, "style", "get").mockImplementation(
() =>
({
height: "",
overflow: "",
}) as CSSStyleDeclaration
);
const onChange = vi.fn();
render(
<OpenTextQuestion
{...defaultProps}
onChange={onChange}
question={{ ...defaultQuestion, longAnswer: true }}
/>
);
const textarea = screen.getByRole("textbox");
// Only trigger a regular input event without trying to modify scrollHeight
fireEvent.input(textarea, { target: { value: "Test value for textarea" } });
// Check that onChange was called with the correct value
expect(onChange).toHaveBeenCalledWith({ q1: "Test value for textarea" });
// Clean up the spy
styleSpy.mockRestore();
});
test("handles textarea resize with different heights", async () => {
// Mock styles and scrollHeight for handleInputResize testing
let heightValue = "";
let overflowValue = "";
// Mock style setter to capture values
const originalSetProperty = CSSStyleDeclaration.prototype.setProperty;
CSSStyleDeclaration.prototype.setProperty = vi.fn();
// Mock to capture style changes
Object.defineProperty(HTMLElement.prototype, "style", {
get: vi.fn(() => ({
height: heightValue,
overflow: overflowValue,
setProperty: (prop: string, value: string) => {
if (prop === "height") heightValue = value;
if (prop === "overflow") overflowValue = value;
},
})),
});
const onChange = vi.fn();
render(
<OpenTextQuestion
{...defaultProps}
onChange={onChange}
question={{ ...defaultQuestion, longAnswer: true }}
/>
);
const textarea = screen.getByRole("textbox");
// Simulate normal height (less than max)
const mockNormalEvent = {
target: {
style: { height: "", overflow: "" },
scrollHeight: 100, // Less than max 160px
},
};
// Get the event handler
const inputHandler = textarea.oninput as EventListener;
if (inputHandler) {
inputHandler(mockNormalEvent as unknown as Event);
}
// Now simulate text that exceeds max height
const mockOverflowEvent = {
target: {
style: { height: "", overflow: "" },
scrollHeight: 200, // More than max 160px
},
};
if (inputHandler) {
inputHandler(mockOverflowEvent as unknown as Event);
}
// Restore the original method
CSSStyleDeclaration.prototype.setProperty = originalSetProperty;
});
test("handles form submission by enter key", async () => {
const onSubmit = vi.fn();
const setTtc = vi.fn();
const { container } = render(
<OpenTextQuestion {...defaultProps} value="Test submission" onSubmit={onSubmit} setTtc={setTtc} />
);
// Get the form element using container query
const form = container.querySelector("form");
expect(form).toBeInTheDocument();
// Simulate form submission
fireEvent.submit(form!);
expect(onSubmit).toHaveBeenCalledWith({ q1: "Test submission" }, {});
expect(setTtc).toHaveBeenCalled();
});
test("applies minLength constraint when configured", () => {
render(
<OpenTextQuestion
{...defaultProps}
question={{ ...defaultQuestion, charLimit: { min: 5, max: 100 } }}
/>
);
const input = screen.getByPlaceholderText("Type here...");
expect(input).toHaveAttribute("minLength", "5");
expect(input).toHaveAttribute("maxLength", "100");
});
test("handles video URL in media", () => {
render(
<OpenTextQuestion
{...defaultProps}
question={{ ...defaultQuestion, videoUrl: "https://example.com/video.mp4" }}
/>
);
expect(screen.getByTestId("question-media")).toBeInTheDocument();
});
test("doesn't autofocus when not current question", () => {
const focusMock = vi.fn();
window.HTMLElement.prototype.focus = focusMock;
render(
<OpenTextQuestion
{...defaultProps}
autoFocusEnabled={true}
currentQuestionId="q2" // Different from question id (q1)
/>
);
expect(focusMock).not.toHaveBeenCalled();
});
test("handles input change for textarea", async () => {
const onChange = vi.fn();
render(
<OpenTextQuestion
{...defaultProps}
onChange={onChange}
question={{ ...defaultQuestion, longAnswer: true }}
/>
);
const textarea = screen.getByRole("textbox");
fireEvent.input(textarea, { target: { value: "Long text response" } });
expect(onChange).toHaveBeenCalledWith({ q1: "Long text response" });
});
test("applies phone number maxLength constraint", () => {
render(<OpenTextQuestion {...defaultProps} question={{ ...defaultQuestion, inputType: "phone" }} />);
const input = screen.getByPlaceholderText("Type here...");
expect(input).toHaveAttribute("maxLength", "30");
});
test("renders without subheader when not provided", () => {
const questionWithoutSubheader = {
...defaultQuestion,
subheader: undefined,
};
render(<OpenTextQuestion {...defaultProps} question={questionWithoutSubheader} />);
expect(screen.getByTestId("mock-subheader")).toHaveTextContent("");
});
test("sets correct tabIndex based on current question status", () => {
// When it's the current question
render(<OpenTextQuestion {...defaultProps} currentQuestionId="q1" />);
const inputCurrent = screen.getByPlaceholderText("Type here...");
const submitCurrent = screen.getByRole("button", { name: "Submit" });
expect(inputCurrent).toHaveAttribute("tabIndex", "0");
expect(submitCurrent).toHaveAttribute("tabIndex", "0");
// When it's not the current question
cleanup();
render(<OpenTextQuestion {...defaultProps} currentQuestionId="q2" />);
const inputNotCurrent = screen.getByPlaceholderText("Type here...");
const submitNotCurrent = screen.getByRole("button", { name: "Submit" });
expect(inputNotCurrent).toHaveAttribute("tabIndex", "-1");
expect(submitNotCurrent).toHaveAttribute("tabIndex", "-1");
});
test("applies title attribute for phone input in textarea", () => {
render(
<OpenTextQuestion
{...defaultProps}
question={{
...defaultQuestion,
longAnswer: true,
inputType: "phone",
}}
/>
);
const textarea = screen.getByRole("textbox");
expect(textarea).toHaveAttribute("title", "Please enter a valid phone number");
});
test("applies character limits for textarea", () => {
render(
<OpenTextQuestion
{...defaultProps}
question={{
...defaultQuestion,
longAnswer: true,
inputType: "text",
charLimit: { min: 10, max: 200 },
}}
/>
);
const textarea = screen.getByRole("textbox");
expect(textarea).toHaveAttribute("minLength", "10");
expect(textarea).toHaveAttribute("maxLength", "200");
});
test("renders input with no maxLength for other input types", () => {
render(
<OpenTextQuestion
{...defaultProps}
question={{
...defaultQuestion,
inputType: "email",
}}
/>
);
const input = screen.getByPlaceholderText("Type here...");
// Should be undefined for non-text, non-phone types
expect(input).not.toHaveAttribute("maxLength");
});
test("applies autofocus attribute to textarea when enabled", () => {
render(
<OpenTextQuestion
{...defaultProps}
autoFocusEnabled={true}
question={{
...defaultQuestion,
longAnswer: true,
}}
/>
);
const textarea = screen.getByRole("textbox");
expect(textarea).toHaveAttribute("autoFocus");
});
test("does not apply autofocus attribute to textarea when not current question", () => {
render(
<OpenTextQuestion
{...defaultProps}
autoFocusEnabled={true}
currentQuestionId="q2" // different from question.id (q1)
question={{
...defaultQuestion,
longAnswer: true,
}}
/>
);
const textarea = screen.getByRole("textbox");
expect(textarea).not.toHaveAttribute("autoFocus");
});
});

View File

@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { describe, expect, test, vi } from "vitest";
import { type TResponseData, type TResponseVariables } from "@formbricks/types/responses";
import { type TSurveyQuestion, TSurveyQuestionTypeEnum } from "../../../types/surveys/types";
import { parseRecallInformation, replaceRecallInfo } from "./recall";
@@ -15,7 +15,7 @@ vi.mock("./i18n", () => ({
vi.mock("./date-time", () => ({
isValidDateString: (val: string) => /^\d{4}-\d{2}-\d{2}$/.test(val) || /^\d{2}-\d{2}-\d{4}$/.test(val),
formatDateWithOrdinal: (date: Date) =>
`${date.getFullYear()}-${("0" + (date.getMonth() + 1)).slice(-2)}-${("0" + date.getDate()).slice(-2)}_formatted`,
`${date.getUTCFullYear()}-${("0" + (date.getUTCMonth() + 1)).slice(-2)}-${("0" + date.getUTCDate()).slice(-2)}_formatted`,
}));
describe("replaceRecallInfo", () => {
@@ -34,79 +34,73 @@ describe("replaceRecallInfo", () => {
lastLogin: "2024-03-10",
};
it("should replace recall info from responseData", () => {
test("should replace recall info from responseData", () => {
const text = "Welcome, #recall:name/fallback:Guest#! Your email is #recall:email/fallback:N/A#.";
const expected = "Welcome, John Doe! Your email is john.doe@example.com.";
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
it("should replace recall info from variables if not in responseData", () => {
test("should replace recall info from variables if not in responseData", () => {
const text = "Product: #recall:productName/fallback:N/A#. Role: #recall:userRole/fallback:User#.";
const expected = "Product: Formbricks. Role: Admin.";
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
it("should use fallback if value is not found in responseData or variables", () => {
test("should use fallback if value is not found in responseData or variables", () => {
const text = "Your organization is #recall:orgName/fallback:DefaultOrg#.";
const expected = "Your organization is DefaultOrg.";
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
it("should handle nbsp in fallback", () => {
const text = "Status: #recall:status/fallback:PendingnbspReview#.";
const expected = "Status: Pending Review.";
test("should handle nbsp in fallback", () => {
const text = "Status: #recall:status/fallback:Pending&nbsp;Review#.";
const expected = "Status: Pending& ;Review.";
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
it("should format date strings from responseData", () => {
test("should format date strings from responseData", () => {
const text = "Registered on: #recall:registrationDate/fallback:N/A#.";
const expected = "Registered on: 2023-01-15_formatted.";
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
it("should format date strings from variables", () => {
test("should format date strings from variables", () => {
const text = "Last login: #recall:lastLogin/fallback:N/A#.";
const expected = "Last login: 2024-03-10_formatted.";
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
it("should join array values with a comma and space", () => {
test("should join array values with a comma and space", () => {
const text = "Tags: #recall:tags/fallback:none#.";
const expected = "Tags: beta, user.";
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
it("should handle empty array values, replacing with fallback", () => {
test("should handle empty array values, replacing with fallback", () => {
const text = "Categories: #recall:emptyArray/fallback:No&nbsp;Categories#.";
const expected = "Categories: No& ;Categories.";
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
it("should handle null values from responseData, replacing with fallback", () => {
const text = "Preference: #recall:nullValue/fallback:Not&nbsp;Set#.";
const expected = "Preference: Not& ;Set.";
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
it("should handle multiple recall patterns in a single string", () => {
test("should handle multiple recall patterns in a single string", () => {
const text =
"Hi #recall:name/fallback:User#, welcome to #recall:productName/fallback:Our Product#. Your role is #recall:userRole/fallback:Member#.";
const expected = "Hi John Doe, welcome to #recall:productName/fallback:Our Product#. Your role is Admin.";
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
it("should return original text if no recall pattern is found", () => {
test("should return original text if no recall pattern is found", () => {
const text = "This is a normal text without recall info.";
expect(replaceRecallInfo(text, responseData, variables)).toBe(text);
});
it("should handle recall ID not found, using fallback", () => {
test("should handle recall ID not found, using fallback", () => {
const text = "Value: #recall:nonExistent/fallback:FallbackValue#.";
const expected = "Value: FallbackValue.";
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
it("should handle if recall info is incomplete (e.g. missing fallback part), effectively using empty fallback", () => {
test("should handle if recall info is incomplete (e.g. missing fallback part), effectively using empty fallback", () => {
// This specific pattern is not fully matched by extractRecallInfo, leading to no replacement.
// The current extractRecallInfo expects #recall:ID/fallback:VALUE#
const text = "Test: #recall:name#";
@@ -114,10 +108,28 @@ describe("replaceRecallInfo", () => {
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
it("should handle complex fallback with spaces and special characters encoded as nbsp", () => {
test("should handle complex fallback with spaces and special characters encoded as nbsp", () => {
const text =
"Details: #recall:extraInfo/fallback:ValuenbspWithnbspSpaces# and #recall:anotherInfo/fallback:Default#";
const expected = "Details: Value With Spaces and Default";
"Details: #recall:extraInfo/fallback:Value&nbsp;With&nbsp;Spaces# and #recall:anotherInfo/fallback:Default#";
const expected = "Details: Value& ;With& ;Spaces and Default";
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
test("should handle fallback with only 'nbsp'", () => {
const text = "Note: #recall:note/fallback:nbsp#.";
const expected = "Note: .";
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
test("should handle fallback with only '&nbsp;'", () => {
const text = "Note: #recall:note/fallback:&nbsp;#.";
const expected = "Note: & ;.";
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
test("should handle fallback with '$nbsp;' (should not replace '$nbsp;')", () => {
const text = "Note: #recall:note/fallback:$nbsp;#.";
const expected = "Note: $ ;.";
expect(replaceRecallInfo(text, responseData, variables)).toBe(expected);
});
});
@@ -151,7 +163,7 @@ describe("parseRecallInformation", () => {
// other necessary TSurveyQuestion fields can be added here with default values
};
it("should replace recall info in headline", () => {
test("should replace recall info in headline", () => {
const question: TSurveyQuestion = {
...baseQuestion,
headline: { en: "Welcome, #recall:name/fallback:Guest#!" },
@@ -161,7 +173,7 @@ describe("parseRecallInformation", () => {
expect(result.headline.en).toBe(expectedHeadline);
});
it("should replace recall info in subheader", () => {
test("should replace recall info in subheader", () => {
const question: TSurveyQuestion = {
...baseQuestion,
headline: { en: "Main Question" },
@@ -172,7 +184,7 @@ describe("parseRecallInformation", () => {
expect(result.subheader?.en).toBe(expectedSubheader);
});
it("should replace recall info in both headline and subheader", () => {
test("should replace recall info in both headline and subheader", () => {
const question: TSurveyQuestion = {
...baseQuestion,
headline: { en: "User: #recall:name/fallback:User#" },
@@ -183,7 +195,7 @@ describe("parseRecallInformation", () => {
expect(result.subheader?.en).toBe("Survey: Onboarding");
});
it("should not change text if no recall info is present", () => {
test("should not change text if no recall info is present", () => {
const question: TSurveyQuestion = {
...baseQuestion,
headline: { en: "A simple question." },
@@ -199,7 +211,7 @@ describe("parseRecallInformation", () => {
expect(result.subheader?.en).toBe(question.subheader?.en);
});
it("should handle undefined subheader gracefully", () => {
test("should handle undefined subheader gracefully", () => {
const question: TSurveyQuestion = {
...baseQuestion,
headline: { en: "Question with #recall:name/fallback:User#" },
@@ -210,7 +222,7 @@ describe("parseRecallInformation", () => {
expect(result.subheader).toBeUndefined();
});
it("should not modify subheader if languageCode content is missing, even if recall is in other lang", () => {
test("should not modify subheader if languageCode content is missing, even if recall is in other lang", () => {
const question: TSurveyQuestion = {
...baseQuestion,
headline: { en: "Hello #recall:name/fallback:User#" },
@@ -222,7 +234,7 @@ describe("parseRecallInformation", () => {
expect(result.subheader?.fr).toBe("Bonjour #recall:name/fallback:Utilisateur#");
});
it("should handle malformed recall string (empty ID) leading to no replacement for that pattern", () => {
test("should handle malformed recall string (empty ID) leading to no replacement for that pattern", () => {
// This tests extractId returning null because extractRecallInfo won't match '#recall:/fallback:foo#'
// due to idPattern requiring at least one char for ID.
const question: TSurveyQuestion = {
@@ -233,7 +245,7 @@ describe("parseRecallInformation", () => {
expect(result.headline.en).toBe("Malformed: #recall:/fallback:foo# and valid: John Doe");
});
it("should use empty string for empty fallback value", () => {
test("should use empty string for empty fallback value", () => {
// This tests extractFallbackValue returning ""
const question: TSurveyQuestion = {
...baseQuestion,
@@ -243,7 +255,7 @@ describe("parseRecallInformation", () => {
expect(result.headline.en).toBe("Data: "); // nonExistentData not found, empty fallback used
});
it("should handle recall info if subheader is present but no text for languageCode", () => {
test("should handle recall info if subheader is present but no text for languageCode", () => {
const question: TSurveyQuestion = {
...baseQuestion,
headline: { en: "Headline #recall:name/fallback:User#" },

View File

@@ -7,27 +7,19 @@ import { type TSurveyQuestion } from "@formbricks/types/surveys/types";
const extractId = (text: string): string | null => {
const pattern = /#recall:([A-Za-z0-9_-]+)/;
const match = text.match(pattern);
if (match && match[1]) {
return match[1];
} else {
return null;
}
return match?.[1] ?? null;
};
// Extracts the fallback value from a string containing the "fallback" pattern.
const extractFallbackValue = (text: string): string => {
const pattern = /fallback:(\S*)#/;
const match = text.match(pattern);
if (match && match[1]) {
return match[1];
} else {
return "";
}
return match?.[1] ?? "";
};
// Extracts the complete recall information (ID and fallback) from a headline string.
const extractRecallInfo = (headline: string, id?: string): string | null => {
const idPattern = id ? id : "[A-Za-z0-9_-]+";
const idPattern = id ?? "[A-Za-z0-9_-]+";
const pattern = new RegExp(`#recall:(${idPattern})\\/fallback:(\\S*)#`);
const match = headline.match(pattern);
return match ? match[0] : null;
@@ -47,7 +39,7 @@ export const replaceRecallInfo = (
const recallItemId = extractId(recallInfo);
if (!recallItemId) return modifiedText; // Return the text if no ID could be extracted
const fallback = extractFallbackValue(recallInfo).replaceAll("nbsp", " ");
const fallback = extractFallbackValue(recallInfo).replace(/nbsp/g, " ").trim();
let value: string | null = null;
// Fetching value from variables based on recallItemId

View File

@@ -1,10 +1,11 @@
import preact from "@preact/preset-vite";
import { fileURLToPath } from "url";
import { dirname, resolve } from "path";
import { defineConfig, loadEnv } from "vite";
import { loadEnv } from "vite";
import dts from "vite-plugin-dts";
import tsconfigPaths from "vite-tsconfig-paths";
import { copyCompiledAssetsPlugin } from "../vite-plugins/copy-compiled-assets";
import { defineConfig } from "vitest/config";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -29,7 +30,7 @@ const config = ({ mode }) => {
},
},
define: {
"process.env": env,
"process.env.NODE_ENV": JSON.stringify(mode),
},
build: {
emptyOutDir: false,

View File

@@ -155,6 +155,7 @@ const ZResponseFilterCriteriaFilledOut = z.object({
export const ZResponseFilterCriteria = z.object({
finished: z.boolean().optional(),
responseIds: z.array(ZId).optional(),
createdAt: z
.object({
min: z.date().optional(),

2708
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -170,7 +170,7 @@
"UNKEY_ROOT_KEY",
"PROMETHEUS_ENABLED",
"PROMETHEUS_EXPORTER_PORT",
"DISABLE_USER_MANAGEMENT"
"USER_MANAGEMENT_MINIMUM_ROLE"
],
"outputs": ["dist/**", ".next/**"]
},