mirror of
https://github.com/formbricks/formbricks.git
synced 2025-12-29 09:50:10 -06:00
Compare commits
91 Commits
v3.16.0-rc
...
fix/github
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe15f6b7bd | ||
|
|
1091b40bd1 | ||
|
|
87a2d727ed | ||
|
|
4786ab61e7 | ||
|
|
819380d21c | ||
|
|
fd3fedb6ed | ||
|
|
88b1e63771 | ||
|
|
3132fe74f1 | ||
|
|
a27a2a67c8 | ||
|
|
4a7ace5a0a | ||
|
|
43628caa3b | ||
|
|
9d84bc0c8d | ||
|
|
babc020085 | ||
|
|
95ee83ef31 | ||
|
|
d994af2dfd | ||
|
|
4b5b5bf59f | ||
|
|
62166dc4b1 | ||
|
|
ec6d88bf11 | ||
|
|
c0240d60a1 | ||
|
|
cd2884d83e | ||
|
|
f7aea2e706 | ||
|
|
e80fc2ee61 | ||
|
|
9b489b0682 | ||
|
|
2ee0efa1c2 | ||
|
|
9ffd67262c | ||
|
|
68dc63ce0b | ||
|
|
f239ee9697 | ||
|
|
282b3e070c | ||
|
|
b5f0bd8f9a | ||
|
|
3784bd6b5e | ||
|
|
41d27c2093 | ||
|
|
7400ce2e67 | ||
|
|
355782f404 | ||
|
|
de70e97940 | ||
|
|
287c45f996 | ||
|
|
3b07a6d013 | ||
|
|
0cc2606ec6 | ||
|
|
0fada94b80 | ||
|
|
a59ede20c7 | ||
|
|
84294f9df2 | ||
|
|
855e7c78ce | ||
|
|
6c506d90c7 | ||
|
|
53f6e02ca1 | ||
|
|
14de2eab42 | ||
|
|
ad1f80331a | ||
|
|
3527ac337b | ||
|
|
23c2d3dce9 | ||
|
|
da652bd860 | ||
|
|
6f88dde1a0 | ||
|
|
3b90223101 | ||
|
|
e29a67b1f6 | ||
|
|
78f5de2f35 | ||
|
|
b1a35d4a69 | ||
|
|
2166c44470 | ||
|
|
080cf741e9 | ||
|
|
8881691509 | ||
|
|
3045f4437f | ||
|
|
91ace0e821 | ||
|
|
6ef281647a | ||
|
|
0aaaaa54ee | ||
|
|
b1f78e7bf2 | ||
|
|
7086ce2ca3 | ||
|
|
8f8b549b1d | ||
|
|
28514487e0 | ||
|
|
ee20af54c3 | ||
|
|
d08ec4c9ab | ||
|
|
891c83e232 | ||
|
|
0b02b00b72 | ||
|
|
a217cdd501 | ||
|
|
ebe50a4821 | ||
|
|
cb68d9defc | ||
|
|
c42a706789 | ||
|
|
3803111b19 | ||
|
|
30fdcff737 | ||
|
|
e83cfa85a4 | ||
|
|
eee9ee8995 | ||
|
|
ed89f12af8 | ||
|
|
f043314537 | ||
|
|
2ce842dd8d | ||
|
|
43b43839c5 | ||
|
|
8b6e3fec37 | ||
|
|
31bcf98779 | ||
|
|
b35cabcbcc | ||
|
|
4f435f1a1f | ||
|
|
99c1e434df | ||
|
|
b13699801b | ||
|
|
ceb2e85d96 | ||
|
|
c5f8b5ec32 | ||
|
|
bdbd57c2fc | ||
|
|
d44aa17814 | ||
|
|
23d38b4c5b |
@@ -18,7 +18,6 @@ apps/web/
|
|||||||
│ ├── (app)/ # Main application routes
|
│ ├── (app)/ # Main application routes
|
||||||
│ ├── (auth)/ # Authentication routes
|
│ ├── (auth)/ # Authentication routes
|
||||||
│ ├── api/ # API routes
|
│ ├── api/ # API routes
|
||||||
│ └── share/ # Public sharing routes
|
|
||||||
├── components/ # Shared components
|
├── components/ # Shared components
|
||||||
├── lib/ # Utility functions and services
|
├── lib/ # Utility functions and services
|
||||||
└── modules/ # Feature-specific modules
|
└── modules/ # Feature-specific modules
|
||||||
@@ -43,7 +42,6 @@ The application uses Next.js 13+ app router with route groups:
|
|||||||
### Dynamic Routes
|
### Dynamic Routes
|
||||||
- `[environmentId]` - Environment-specific routes
|
- `[environmentId]` - Environment-specific routes
|
||||||
- `[surveyId]` - Survey-specific routes
|
- `[surveyId]` - Survey-specific routes
|
||||||
- `[sharingKey]` - Public sharing routes
|
|
||||||
|
|
||||||
## Service Layer Pattern
|
## Service Layer Pattern
|
||||||
|
|
||||||
|
|||||||
232
.cursor/rules/github-actions-security.mdc
Normal file
232
.cursor/rules/github-actions-security.mdc
Normal file
@@ -0,0 +1,232 @@
|
|||||||
|
---
|
||||||
|
description: Security best practices and guidelines for writing GitHub Actions and workflows
|
||||||
|
globs: .github/workflows/*.yml,.github/workflows/*.yaml,.github/actions/*/action.yml,.github/actions/*/action.yaml
|
||||||
|
---
|
||||||
|
|
||||||
|
# GitHub Actions Security Best Practices
|
||||||
|
|
||||||
|
## Required Security Measures
|
||||||
|
|
||||||
|
### 1. Set Minimum GITHUB_TOKEN Permissions
|
||||||
|
|
||||||
|
Always explicitly set the minimum required permissions for GITHUB_TOKEN:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
# Only add additional permissions if absolutely necessary:
|
||||||
|
# pull-requests: write # for commenting on PRs
|
||||||
|
# issues: write # for creating/updating issues
|
||||||
|
# checks: write # for publishing check results
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Add Harden-Runner as First Step
|
||||||
|
|
||||||
|
For **every job** on `ubuntu-latest`, add Harden-Runner as the first step:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- name: Harden the runner
|
||||||
|
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
||||||
|
with:
|
||||||
|
egress-policy: audit # or 'block' for stricter security
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Pin Actions to Full Commit SHA
|
||||||
|
|
||||||
|
**Always** pin third-party actions to their full commit SHA, not tags:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# ❌ BAD - uses mutable tag
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# ✅ GOOD - pinned to immutable commit SHA
|
||||||
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Secure Variable Handling
|
||||||
|
|
||||||
|
Prevent command injection by properly quoting variables:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# ❌ BAD - potential command injection
|
||||||
|
run: echo "Processing ${{ inputs.user_input }}"
|
||||||
|
|
||||||
|
# ✅ GOOD - properly quoted
|
||||||
|
env:
|
||||||
|
USER_INPUT: ${{ inputs.user_input }}
|
||||||
|
run: echo "Processing ${USER_INPUT}"
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `${VARIABLE}` syntax in shell scripts instead of `$VARIABLE`.
|
||||||
|
|
||||||
|
### 5. Environment Variables for Secrets
|
||||||
|
|
||||||
|
Store sensitive data in environment variables, not inline:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# ❌ BAD
|
||||||
|
run: curl -H "Authorization: Bearer ${{ secrets.TOKEN }}" api.example.com
|
||||||
|
|
||||||
|
# ✅ GOOD
|
||||||
|
env:
|
||||||
|
API_TOKEN: ${{ secrets.TOKEN }}
|
||||||
|
run: curl -H "Authorization: Bearer ${API_TOKEN}" api.example.com
|
||||||
|
```
|
||||||
|
|
||||||
|
## Workflow Structure Best Practices
|
||||||
|
|
||||||
|
### Required Workflow Elements
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
name: "Descriptive Workflow Name"
|
||||||
|
|
||||||
|
on:
|
||||||
|
# Define specific triggers
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
# Always set explicit permissions
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
job-name:
|
||||||
|
name: "Descriptive Job Name"
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 30 # tune per job; standardize repo-wide
|
||||||
|
|
||||||
|
# Set job-level permissions if different from workflow level
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
steps:
|
||||||
|
# Always start with Harden-Runner on ubuntu-latest
|
||||||
|
- name: Harden the runner
|
||||||
|
uses: step-security/harden-runner@v2
|
||||||
|
with:
|
||||||
|
egress-policy: audit
|
||||||
|
|
||||||
|
# Pin all actions to commit SHA
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
```
|
||||||
|
|
||||||
|
### Input Validation for Actions
|
||||||
|
|
||||||
|
For composite actions, always validate inputs:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
inputs:
|
||||||
|
user_input:
|
||||||
|
description: "User provided input"
|
||||||
|
required: true
|
||||||
|
|
||||||
|
runs:
|
||||||
|
using: "composite"
|
||||||
|
steps:
|
||||||
|
- name: Validate input
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
# Harden shell and validate input format/content before use
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
USER_INPUT="${{ inputs.user_input }}"
|
||||||
|
|
||||||
|
if [[ ! "${USER_INPUT}" =~ ^[A-Za-z0-9._-]+$ ]]; then
|
||||||
|
echo "❌ Invalid input format"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
```
|
||||||
|
|
||||||
|
## Docker Security in Actions
|
||||||
|
|
||||||
|
### Pin Docker Images to Digests
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# ❌ BAD - mutable tag
|
||||||
|
container: node:18
|
||||||
|
|
||||||
|
# ✅ GOOD - pinned to digest
|
||||||
|
container: node:18@sha256:a1ba21bf0c92931d02a8416f0a54daad66cb36a85d6a37b82dfe1604c4c09cad
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common Patterns
|
||||||
|
|
||||||
|
### Secure File Operations
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- name: Process files securely
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
FILE_PATH: ${{ inputs.file_path }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail # Fail on errors, undefined vars, pipe failures
|
||||||
|
|
||||||
|
# Use absolute paths and validate
|
||||||
|
SAFE_PATH=$(realpath "${FILE_PATH}")
|
||||||
|
if [[ "$SAFE_PATH" != "${GITHUB_WORKSPACE}"/* ]]; then
|
||||||
|
echo "❌ Path outside workspace"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
```
|
||||||
|
|
||||||
|
### Artifact Handling
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- name: Upload artifacts securely
|
||||||
|
uses: actions/upload-artifact@50769540e7f4bd5e21e526ee35c689e35e0d6874 # v4.4.0
|
||||||
|
with:
|
||||||
|
name: build-artifacts
|
||||||
|
path: |
|
||||||
|
dist/
|
||||||
|
!dist/**/*.log # Exclude sensitive files
|
||||||
|
retention-days: 30
|
||||||
|
```
|
||||||
|
|
||||||
|
### GHCR authentication for pulls/scans
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# Minimal permissions required for GHCR pulls/scans
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: read
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Log in to GitHub Container Registry
|
||||||
|
uses: docker/login-action@184bdaa0721073962dff0199f1fb9940f07167d1 # v3.5.0
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.actor }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Security Checklist
|
||||||
|
|
||||||
|
- [ ] Minimum GITHUB_TOKEN permissions set
|
||||||
|
- [ ] Harden-Runner added to all ubuntu-latest jobs
|
||||||
|
- [ ] All third-party actions pinned to commit SHA
|
||||||
|
- [ ] Input validation implemented for custom actions
|
||||||
|
- [ ] Variables properly quoted in shell scripts
|
||||||
|
- [ ] Secrets stored in environment variables
|
||||||
|
- [ ] Docker images pinned to digests (if used)
|
||||||
|
- [ ] Error handling with `set -euo pipefail`
|
||||||
|
- [ ] File paths validated and sanitized
|
||||||
|
- [ ] No sensitive data in logs or outputs
|
||||||
|
- [ ] GHCR login performed before pulls/scans (packages: read)
|
||||||
|
- [ ] Job timeouts configured (`timeout-minutes`)
|
||||||
|
|
||||||
|
## Recommended Additional Workflows
|
||||||
|
|
||||||
|
Consider adding these security-focused workflows to your repository:
|
||||||
|
|
||||||
|
1. **CodeQL Analysis** - Static Application Security Testing (SAST)
|
||||||
|
2. **Dependency Review** - Scan for vulnerable dependencies in PRs
|
||||||
|
3. **Dependabot Configuration** - Automated dependency updates
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
- [GitHub Security Hardening Guide](https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions)
|
||||||
|
- [Step Security Harden-Runner](https://github.com/step-security/harden-runner)
|
||||||
|
- [Secure-Repo Best Practices](https://github.com/step-security/secure-repo)
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
description:
|
description: Migrate deprecated UI components to a unified component
|
||||||
globs:
|
globs:
|
||||||
alwaysApply: false
|
alwaysApply: false
|
||||||
---
|
---
|
||||||
177
.cursor/rules/storybook-create-new-story.mdc
Normal file
177
.cursor/rules/storybook-create-new-story.mdc
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
---
|
||||||
|
description: Create a story in Storybook for a given component
|
||||||
|
globs:
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# Formbricks Storybook Stories
|
||||||
|
|
||||||
|
## When generating Storybook stories for Formbricks components:
|
||||||
|
|
||||||
|
### 1. **File Structure**
|
||||||
|
- Create `stories.tsx` (not `.stories.tsx`) in component directory
|
||||||
|
- Use exact import: `import { Meta, StoryObj } from "@storybook/react-vite";`
|
||||||
|
- Import component from `"./index"`
|
||||||
|
|
||||||
|
### 2. **Story Structure Template**
|
||||||
|
```tsx
|
||||||
|
import { Meta, StoryObj } from "@storybook/react-vite";
|
||||||
|
import { ComponentName } from "./index";
|
||||||
|
|
||||||
|
// For complex components with configurable options
|
||||||
|
// consider this as an example the options need to reflect the props types
|
||||||
|
interface StoryOptions {
|
||||||
|
showIcon: boolean;
|
||||||
|
numberOfElements: number;
|
||||||
|
customLabels: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
type StoryProps = React.ComponentProps<typeof ComponentName> & StoryOptions;
|
||||||
|
|
||||||
|
const meta: Meta<StoryProps> = {
|
||||||
|
title: "UI/ComponentName",
|
||||||
|
component: ComponentName,
|
||||||
|
tags: ["autodocs"],
|
||||||
|
parameters: {
|
||||||
|
layout: "centered",
|
||||||
|
controls: { sort: "alpha", exclude: [] },
|
||||||
|
docs: {
|
||||||
|
description: {
|
||||||
|
component: "The **ComponentName** component provides [description].",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
argTypes: {
|
||||||
|
// Organize in exactly these categories: Behavior, Appearance, Content
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof ComponentName> & { args: StoryOptions };
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. **ArgTypes Organization**
|
||||||
|
Organize ALL argTypes into exactly three categories:
|
||||||
|
- **Behavior**: disabled, variant, onChange, etc.
|
||||||
|
- **Appearance**: size, color, layout, styling, etc.
|
||||||
|
- **Content**: text, icons, numberOfElements, etc.
|
||||||
|
|
||||||
|
Format:
|
||||||
|
```tsx
|
||||||
|
argTypes: {
|
||||||
|
propName: {
|
||||||
|
control: "select" | "boolean" | "text" | "number",
|
||||||
|
options: ["option1", "option2"], // for select
|
||||||
|
description: "Clear description",
|
||||||
|
table: {
|
||||||
|
category: "Behavior" | "Appearance" | "Content",
|
||||||
|
type: { summary: "string" },
|
||||||
|
defaultValue: { summary: "default" },
|
||||||
|
},
|
||||||
|
order: 1,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. **Required Stories**
|
||||||
|
Every component must include:
|
||||||
|
- `Default`: Most common use case
|
||||||
|
- `Disabled`: If component supports disabled state
|
||||||
|
- `WithIcon`: If component supports icons
|
||||||
|
- Variant stories for each variant (Primary, Secondary, Error, etc.)
|
||||||
|
- Edge case stories (ManyElements, LongText, CustomStyling)
|
||||||
|
|
||||||
|
### 5. **Story Format**
|
||||||
|
```tsx
|
||||||
|
export const Default: Story = {
|
||||||
|
args: {
|
||||||
|
// Props with realistic values
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const EdgeCase: Story = {
|
||||||
|
args: { /* ... */ },
|
||||||
|
parameters: {
|
||||||
|
docs: {
|
||||||
|
description: {
|
||||||
|
story: "Use this when [specific scenario].",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. **Dynamic Content Pattern**
|
||||||
|
For components with dynamic content, create render function:
|
||||||
|
```tsx
|
||||||
|
const renderComponent = (args: StoryProps) => {
|
||||||
|
const { numberOfElements, showIcon, customLabels } = args;
|
||||||
|
|
||||||
|
// Generate dynamic content
|
||||||
|
const elements = Array.from({ length: numberOfElements }, (_, i) => ({
|
||||||
|
id: `element-${i}`,
|
||||||
|
label: customLabels[i] || `Element ${i + 1}`,
|
||||||
|
icon: showIcon ? <IconComponent /> : undefined,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return <ComponentName {...args} elements={elements} />;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const Dynamic: Story = {
|
||||||
|
render: renderComponent,
|
||||||
|
args: {
|
||||||
|
numberOfElements: 3,
|
||||||
|
showIcon: true,
|
||||||
|
customLabels: ["First", "Second", "Third"],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7. **State Management**
|
||||||
|
For interactive components:
|
||||||
|
```tsx
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
const ComponentWithState = (args: any) => {
|
||||||
|
const [value, setValue] = useState(args.defaultValue);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ComponentName
|
||||||
|
{...args}
|
||||||
|
value={value}
|
||||||
|
onChange={(newValue) => {
|
||||||
|
setValue(newValue);
|
||||||
|
args.onChange?.(newValue);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const Interactive: Story = {
|
||||||
|
render: ComponentWithState,
|
||||||
|
args: { defaultValue: "initial" },
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8. **Quality Requirements**
|
||||||
|
- Include component description in parameters.docs
|
||||||
|
- Add story documentation for non-obvious use cases
|
||||||
|
- Test edge cases (overflow, empty states, many elements)
|
||||||
|
- Ensure no TypeScript errors
|
||||||
|
- Use realistic prop values
|
||||||
|
- Include at least 3-5 story variants
|
||||||
|
- Example values need to be in the context of survey application
|
||||||
|
|
||||||
|
### 9. **Naming Conventions**
|
||||||
|
- **Story titles**: "UI/ComponentName"
|
||||||
|
- **Story exports**: PascalCase (Default, WithIcon, ManyElements)
|
||||||
|
- **Categories**: "Behavior", "Appearance", "Content" (exact spelling)
|
||||||
|
- **Props**: camelCase matching component props
|
||||||
|
|
||||||
|
### 10. **Special Cases**
|
||||||
|
- **Generic components**: Remove `component` from meta if type conflicts
|
||||||
|
- **Form components**: Include Invalid, WithValue stories
|
||||||
|
- **Navigation**: Include ManyItems stories
|
||||||
|
- **Modals, Dropdowns and Popups **: Include trigger and content structure
|
||||||
|
|
||||||
|
## Generate stories that are comprehensive, well-documented, and reflect all component states and edge cases.
|
||||||
@@ -90,7 +90,7 @@ When testing hooks that use React Context:
|
|||||||
vi.mocked(useResponseFilter).mockReturnValue({
|
vi.mocked(useResponseFilter).mockReturnValue({
|
||||||
selectedFilter: {
|
selectedFilter: {
|
||||||
filter: [],
|
filter: [],
|
||||||
onlyComplete: false,
|
responseStatus: "all",
|
||||||
},
|
},
|
||||||
setSelectedFilter: vi.fn(),
|
setSelectedFilter: vi.fn(),
|
||||||
selectedOptions: {
|
selectedOptions: {
|
||||||
@@ -291,11 +291,6 @@ test("handles different modes", async () => {
|
|||||||
expect(vi.mocked(regularApi)).toHaveBeenCalled();
|
expect(vi.mocked(regularApi)).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Test sharing mode
|
|
||||||
vi.mocked(useParams).mockReturnValue({
|
|
||||||
surveyId: "123",
|
|
||||||
sharingKey: "share-123"
|
|
||||||
});
|
|
||||||
rerender();
|
rerender();
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|||||||
@@ -194,9 +194,6 @@ REDIS_URL=redis://localhost:6379
|
|||||||
# The below is used for Rate Limiting (uses In-Memory LRU Cache if not provided) (You can use a service like Webdis for this)
|
# The below is used for Rate Limiting (uses In-Memory LRU Cache if not provided) (You can use a service like Webdis for this)
|
||||||
# REDIS_HTTP_URL:
|
# REDIS_HTTP_URL:
|
||||||
|
|
||||||
# The below is used for Rate Limiting for management API
|
|
||||||
UNKEY_ROOT_KEY=
|
|
||||||
|
|
||||||
# INTERCOM_APP_ID=
|
# INTERCOM_APP_ID=
|
||||||
# INTERCOM_SECRET_KEY=
|
# INTERCOM_SECRET_KEY=
|
||||||
|
|
||||||
|
|||||||
1
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
1
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@@ -1,6 +1,7 @@
|
|||||||
name: Bug report
|
name: Bug report
|
||||||
description: "Found a bug? Please fill out the sections below. \U0001F44D"
|
description: "Found a bug? Please fill out the sections below. \U0001F44D"
|
||||||
type: bug
|
type: bug
|
||||||
|
projects: "formbricks/8"
|
||||||
labels: ["bug"]
|
labels: ["bug"]
|
||||||
body:
|
body:
|
||||||
- type: textarea
|
- type: textarea
|
||||||
|
|||||||
2
.github/ISSUE_TEMPLATE/config.yml
vendored
2
.github/ISSUE_TEMPLATE/config.yml
vendored
@@ -1,4 +1,4 @@
|
|||||||
blank_issues_enabled: false
|
blank_issues_enabled: true
|
||||||
contact_links:
|
contact_links:
|
||||||
- name: Questions
|
- name: Questions
|
||||||
url: https://github.com/formbricks/formbricks/discussions
|
url: https://github.com/formbricks/formbricks/discussions
|
||||||
|
|||||||
4
.github/actions/cache-build-web/action.yml
vendored
4
.github/actions/cache-build-web/action.yml
vendored
@@ -62,10 +62,12 @@ runs:
|
|||||||
shell: bash
|
shell: bash
|
||||||
|
|
||||||
- name: Fill ENCRYPTION_KEY, ENTERPRISE_LICENSE_KEY and E2E_TESTING in .env
|
- name: Fill ENCRYPTION_KEY, ENTERPRISE_LICENSE_KEY and E2E_TESTING in .env
|
||||||
|
env:
|
||||||
|
E2E_TESTING_MODE: ${{ inputs.e2e_testing_mode }}
|
||||||
run: |
|
run: |
|
||||||
RANDOM_KEY=$(openssl rand -hex 32)
|
RANDOM_KEY=$(openssl rand -hex 32)
|
||||||
sed -i "s/ENCRYPTION_KEY=.*/ENCRYPTION_KEY=${RANDOM_KEY}/" .env
|
sed -i "s/ENCRYPTION_KEY=.*/ENCRYPTION_KEY=${RANDOM_KEY}/" .env
|
||||||
echo "E2E_TESTING=${{ inputs.e2e_testing_mode }}" >> .env
|
echo "E2E_TESTING=$E2E_TESTING_MODE" >> .env
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|
||||||
- run: |
|
- run: |
|
||||||
|
|||||||
@@ -1,66 +1,49 @@
|
|||||||
name: 'Upload Sentry Sourcemaps'
|
name: "Upload Sentry Sourcemaps"
|
||||||
description: 'Extract sourcemaps from Docker image and upload to Sentry'
|
description: "Extract sourcemaps from Docker image and upload to Sentry"
|
||||||
|
|
||||||
inputs:
|
inputs:
|
||||||
docker_image:
|
docker_image:
|
||||||
description: 'Docker image to extract sourcemaps from'
|
description: "Docker image to extract sourcemaps from"
|
||||||
required: true
|
required: true
|
||||||
release_version:
|
release_version:
|
||||||
description: 'Sentry release version (e.g., v1.2.3)'
|
description: "Sentry release version (e.g., v1.2.3)"
|
||||||
required: true
|
required: true
|
||||||
sentry_auth_token:
|
sentry_auth_token:
|
||||||
description: 'Sentry authentication token'
|
description: "Sentry authentication token"
|
||||||
required: true
|
required: true
|
||||||
|
environment:
|
||||||
|
description: "Sentry environment (e.g., production, staging)"
|
||||||
|
required: false
|
||||||
|
default: "staging"
|
||||||
|
|
||||||
runs:
|
runs:
|
||||||
using: 'composite'
|
using: "composite"
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- name: Validate Sentry auth token
|
- name: Extract sourcemaps from Docker image
|
||||||
shell: bash
|
shell: bash
|
||||||
|
env:
|
||||||
|
DOCKER_IMAGE: ${{ inputs.docker_image }}
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
echo "🔐 Validating Sentry authentication token..."
|
|
||||||
|
|
||||||
# Assign token to local variable for secure handling
|
# Validate docker image format (basic validation)
|
||||||
SENTRY_TOKEN="${{ inputs.sentry_auth_token }}"
|
if [[ ! "$DOCKER_IMAGE" =~ ^[a-zA-Z0-9._/-]+:[a-zA-Z0-9._-]+$ ]] && [[ ! "$DOCKER_IMAGE" =~ ^[a-zA-Z0-9._/-]+@sha256:[A-Fa-f0-9]{64}$ ]]; then
|
||||||
|
echo "❌ Error: Invalid docker image format. Must be in format 'image:tag' or 'image@sha256:hash'"
|
||||||
# Test the token by making a simple API call to Sentry
|
echo "Provided: ${DOCKER_IMAGE}"
|
||||||
response=$(curl -s -w "%{http_code}" -o /tmp/sentry_response.json \
|
|
||||||
-H "Authorization: Bearer $SENTRY_TOKEN" \
|
|
||||||
"https://sentry.io/api/0/organizations/formbricks/")
|
|
||||||
|
|
||||||
http_code=$(echo "$response" | tail -n1)
|
|
||||||
|
|
||||||
if [ "$http_code" != "200" ]; then
|
|
||||||
echo "❌ Error: Invalid Sentry auth token (HTTP $http_code)"
|
|
||||||
echo "Please check your SENTRY_AUTH_TOKEN is correct and has the necessary permissions."
|
|
||||||
if [ -f /tmp/sentry_response.json ]; then
|
|
||||||
echo "Response body:"
|
|
||||||
cat /tmp/sentry_response.json
|
|
||||||
fi
|
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "✅ Sentry auth token validated successfully"
|
echo "📦 Extracting sourcemaps from Docker image: ${DOCKER_IMAGE}"
|
||||||
|
|
||||||
# Clean up temp file
|
|
||||||
rm -f /tmp/sentry_response.json
|
|
||||||
|
|
||||||
- name: Extract sourcemaps from Docker image
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
echo "📦 Extracting sourcemaps from Docker image: ${{ inputs.docker_image }}"
|
|
||||||
|
|
||||||
# Create temporary container from the image and capture its ID
|
# Create temporary container from the image and capture its ID
|
||||||
echo "Creating temporary container..."
|
echo "Creating temporary container..."
|
||||||
CONTAINER_ID=$(docker create "${{ inputs.docker_image }}")
|
CONTAINER_ID=$(docker create "$DOCKER_IMAGE")
|
||||||
echo "Container created with ID: $CONTAINER_ID"
|
echo "Container created with ID: ${CONTAINER_ID}"
|
||||||
|
|
||||||
# Set up cleanup function to ensure container is removed on script exit
|
# Set up cleanup function to ensure container is removed on script exit
|
||||||
cleanup_container() {
|
cleanup_container() {
|
||||||
@@ -72,13 +55,13 @@ runs:
|
|||||||
# Remove the container if it exists (ignore errors if already removed)
|
# Remove the container if it exists (ignore errors if already removed)
|
||||||
if [ -n "$CONTAINER_ID" ]; then
|
if [ -n "$CONTAINER_ID" ]; then
|
||||||
docker rm -f "$CONTAINER_ID" 2>/dev/null || true
|
docker rm -f "$CONTAINER_ID" 2>/dev/null || true
|
||||||
echo "Container $CONTAINER_ID removed"
|
echo "Container ${CONTAINER_ID} removed"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Exit with the original exit code to preserve script success/failure status
|
# Exit with the original exit code to preserve script success/failure status
|
||||||
exit $original_exit_code
|
exit $original_exit_code
|
||||||
}
|
}
|
||||||
|
|
||||||
# Register cleanup function to run on script exit (success or failure)
|
# Register cleanup function to run on script exit (success or failure)
|
||||||
trap cleanup_container EXIT
|
trap cleanup_container EXIT
|
||||||
|
|
||||||
@@ -93,7 +76,7 @@ runs:
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
sourcemap_count=$(find ./extracted-next/static/chunks -name "*.map" | wc -l)
|
sourcemap_count=$(find ./extracted-next/static/chunks -name "*.map" | wc -l)
|
||||||
echo "✅ Found $sourcemap_count sourcemap files"
|
echo "✅ Found ${sourcemap_count} sourcemap files"
|
||||||
|
|
||||||
if [ "$sourcemap_count" -eq 0 ]; then
|
if [ "$sourcemap_count" -eq 0 ]; then
|
||||||
echo "❌ Error: No sourcemap files found. Check that productionBrowserSourceMaps is enabled."
|
echo "❌ Error: No sourcemap files found. Check that productionBrowserSourceMaps is enabled."
|
||||||
@@ -107,9 +90,9 @@ runs:
|
|||||||
SENTRY_ORG: formbricks
|
SENTRY_ORG: formbricks
|
||||||
SENTRY_PROJECT: formbricks-cloud
|
SENTRY_PROJECT: formbricks-cloud
|
||||||
with:
|
with:
|
||||||
environment: production
|
environment: ${{ inputs.environment }}
|
||||||
version: ${{ inputs.release_version }}
|
version: ${{ inputs.release_version }}
|
||||||
sourcemaps: './extracted-next/'
|
sourcemaps: "./extracted-next/"
|
||||||
|
|
||||||
- name: Clean up extracted files
|
- name: Clean up extracted files
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|||||||
82
.github/workflows/apply-issue-labels-to-pr.yml
vendored
82
.github/workflows/apply-issue-labels-to-pr.yml
vendored
@@ -1,82 +0,0 @@
|
|||||||
name: "Apply issue labels to PR"
|
|
||||||
|
|
||||||
on:
|
|
||||||
pull_request_target:
|
|
||||||
types:
|
|
||||||
- opened
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
label_on_pr:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: none
|
|
||||||
issues: read
|
|
||||||
pull-requests: write
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Harden the runner (Audit all outbound calls)
|
|
||||||
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
|
||||||
with:
|
|
||||||
egress-policy: audit
|
|
||||||
|
|
||||||
- name: Apply labels from linked issue to PR
|
|
||||||
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
|
||||||
with:
|
|
||||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
script: |
|
|
||||||
async function getLinkedIssues(owner, repo, prNumber) {
|
|
||||||
const query = `query GetLinkedIssues($owner: String!, $repo: String!, $prNumber: Int!) {
|
|
||||||
repository(owner: $owner, name: $repo) {
|
|
||||||
pullRequest(number: $prNumber) {
|
|
||||||
closingIssuesReferences(first: 10) {
|
|
||||||
nodes {
|
|
||||||
number
|
|
||||||
labels(first: 10) {
|
|
||||||
nodes {
|
|
||||||
name
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}`;
|
|
||||||
|
|
||||||
const variables = {
|
|
||||||
owner: owner,
|
|
||||||
repo: repo,
|
|
||||||
prNumber: prNumber,
|
|
||||||
};
|
|
||||||
|
|
||||||
const result = await github.graphql(query, variables);
|
|
||||||
return result.repository.pullRequest.closingIssuesReferences.nodes;
|
|
||||||
}
|
|
||||||
|
|
||||||
const pr = context.payload.pull_request;
|
|
||||||
const linkedIssues = await getLinkedIssues(
|
|
||||||
context.repo.owner,
|
|
||||||
context.repo.repo,
|
|
||||||
pr.number
|
|
||||||
);
|
|
||||||
|
|
||||||
const labelsToAdd = new Set();
|
|
||||||
for (const issue of linkedIssues) {
|
|
||||||
if (issue.labels && issue.labels.nodes) {
|
|
||||||
for (const label of issue.labels.nodes) {
|
|
||||||
labelsToAdd.add(label.name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (labelsToAdd.size) {
|
|
||||||
await github.rest.issues.addLabels({
|
|
||||||
owner: context.repo.owner,
|
|
||||||
repo: context.repo.repo,
|
|
||||||
issue_number: pr.number,
|
|
||||||
labels: Array.from(labelsToAdd),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
4
.github/workflows/chromatic.yml
vendored
4
.github/workflows/chromatic.yml
vendored
@@ -6,12 +6,14 @@ on:
|
|||||||
- main
|
- main
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
chromatic:
|
chromatic:
|
||||||
name: Run Chromatic
|
name: Run Chromatic
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
|
||||||
packages: write
|
packages: write
|
||||||
id-token: write
|
id-token: write
|
||||||
actions: read
|
actions: read
|
||||||
|
|||||||
27
.github/workflows/dependency-review.yml
vendored
27
.github/workflows/dependency-review.yml
vendored
@@ -1,27 +0,0 @@
|
|||||||
# Dependency Review Action
|
|
||||||
#
|
|
||||||
# This Action will scan dependency manifest files that change as part of a Pull Request,
|
|
||||||
# surfacing known-vulnerable versions of the packages declared or updated in the PR.
|
|
||||||
# Once installed, if the workflow run is marked as required,
|
|
||||||
# PRs introducing known-vulnerable packages will be blocked from merging.
|
|
||||||
#
|
|
||||||
# Source repository: https://github.com/actions/dependency-review-action
|
|
||||||
name: 'Dependency Review'
|
|
||||||
on: [pull_request]
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
dependency-review:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Harden the runner (Audit all outbound calls)
|
|
||||||
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
|
||||||
with:
|
|
||||||
egress-policy: audit
|
|
||||||
|
|
||||||
- name: 'Checkout Repository'
|
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
|
||||||
- name: 'Dependency Review'
|
|
||||||
uses: actions/dependency-review-action@38ecb5b593bf0eb19e335c03f97670f792489a8b # v4.7.0
|
|
||||||
35
.github/workflows/deploy-formbricks-cloud.yml
vendored
35
.github/workflows/deploy-formbricks-cloud.yml
vendored
@@ -17,8 +17,8 @@ on:
|
|||||||
required: true
|
required: true
|
||||||
type: choice
|
type: choice
|
||||||
options:
|
options:
|
||||||
- stage
|
- staging
|
||||||
- prod
|
- production
|
||||||
workflow_call:
|
workflow_call:
|
||||||
inputs:
|
inputs:
|
||||||
VERSION:
|
VERSION:
|
||||||
@@ -37,21 +37,27 @@ on:
|
|||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
id-token: write
|
id-token: write
|
||||||
contents: write
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
helmfile-deploy:
|
helmfile-deploy:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
|
- name: Harden the runner (Audit all outbound calls)
|
||||||
|
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
||||||
|
with:
|
||||||
|
egress-policy: audit
|
||||||
|
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4.2.2
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
|
||||||
- name: Tailscale
|
- name: Tailscale
|
||||||
uses: tailscale/github-action@v3
|
uses: tailscale/github-action@84a3f23bb4d843bcf4da6cf824ec1be473daf4de # v3.2.3
|
||||||
with:
|
with:
|
||||||
oauth-client-id: ${{ secrets.TS_OAUTH_CLIENT_ID }}
|
oauth-client-id: ${{ secrets.TS_OAUTH_CLIENT_ID }}
|
||||||
oauth-secret: ${{ secrets.TS_OAUTH_SECRET }}
|
oauth-secret: ${{ secrets.TS_OAUTH_SECRET }}
|
||||||
tags: tag:github
|
tags: tag:github
|
||||||
|
args: --accept-routes
|
||||||
|
|
||||||
- name: Configure AWS Credentials
|
- name: Configure AWS Credentials
|
||||||
uses: aws-actions/configure-aws-credentials@f24d7193d98baebaeacc7e2227925dd47cc267f5 # v4.2.0
|
uses: aws-actions/configure-aws-credentials@f24d7193d98baebaeacc7e2227925dd47cc267f5 # v4.2.0
|
||||||
@@ -65,9 +71,9 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
AWS_REGION: eu-central-1
|
AWS_REGION: eu-central-1
|
||||||
|
|
||||||
- uses: helmfile/helmfile-action@v2
|
- uses: helmfile/helmfile-action@712000e3d4e28c72778ecc53857746082f555ef3 # v2.0.4
|
||||||
name: Deploy Formbricks Cloud Prod
|
name: Deploy Formbricks Cloud Production
|
||||||
if: inputs.ENVIRONMENT == 'prod'
|
if: inputs.ENVIRONMENT == 'production'
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ inputs.VERSION }}
|
VERSION: ${{ inputs.VERSION }}
|
||||||
REPOSITORY: ${{ inputs.REPOSITORY }}
|
REPOSITORY: ${{ inputs.REPOSITORY }}
|
||||||
@@ -83,9 +89,9 @@ jobs:
|
|||||||
helmfile-auto-init: "false"
|
helmfile-auto-init: "false"
|
||||||
helmfile-workdirectory: infra/formbricks-cloud-helm
|
helmfile-workdirectory: infra/formbricks-cloud-helm
|
||||||
|
|
||||||
- uses: helmfile/helmfile-action@v2
|
- uses: helmfile/helmfile-action@712000e3d4e28c72778ecc53857746082f555ef3 # v2.0.4
|
||||||
name: Deploy Formbricks Cloud Stage
|
name: Deploy Formbricks Cloud Staging
|
||||||
if: inputs.ENVIRONMENT == 'stage'
|
if: inputs.ENVIRONMENT == 'staging'
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ inputs.VERSION }}
|
VERSION: ${{ inputs.VERSION }}
|
||||||
REPOSITORY: ${{ inputs.REPOSITORY }}
|
REPOSITORY: ${{ inputs.REPOSITORY }}
|
||||||
@@ -101,19 +107,20 @@ jobs:
|
|||||||
helmfile-workdirectory: infra/formbricks-cloud-helm
|
helmfile-workdirectory: infra/formbricks-cloud-helm
|
||||||
|
|
||||||
- name: Purge Cloudflare Cache
|
- name: Purge Cloudflare Cache
|
||||||
if: ${{ inputs.ENVIRONMENT == 'prod' || inputs.ENVIRONMENT == 'stage' }}
|
if: ${{ inputs.ENVIRONMENT == 'production' || inputs.ENVIRONMENT == 'staging' }}
|
||||||
env:
|
env:
|
||||||
CF_ZONE_ID: ${{ secrets.CLOUDFLARE_ZONE_ID }}
|
CF_ZONE_ID: ${{ secrets.CLOUDFLARE_ZONE_ID }}
|
||||||
CF_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
CF_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||||
|
ENVIRONMENT: ${{ inputs.ENVIRONMENT }}
|
||||||
run: |
|
run: |
|
||||||
# Set hostname based on environment
|
# Set hostname based on environment
|
||||||
if [[ "${{ inputs.ENVIRONMENT }}" == "prod" ]]; then
|
if [[ "$ENVIRONMENT" == "production" ]]; then
|
||||||
PURGE_HOST="app.formbricks.com"
|
PURGE_HOST="app.formbricks.com"
|
||||||
else
|
else
|
||||||
PURGE_HOST="stage.app.formbricks.com"
|
PURGE_HOST="stage.app.formbricks.com"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "Purging Cloudflare cache for host: $PURGE_HOST (environment: ${{ inputs.ENVIRONMENT }}, zone: $CF_ZONE_ID)"
|
echo "Purging Cloudflare cache for host: $PURGE_HOST (environment: $ENVIRONMENT, zone: $CF_ZONE_ID)"
|
||||||
|
|
||||||
# Prepare JSON payload for selective cache purge
|
# Prepare JSON payload for selective cache purge
|
||||||
json_payload=$(cat << EOF
|
json_payload=$(cat << EOF
|
||||||
|
|||||||
125
.github/workflows/docker-build-validation.yml
vendored
125
.github/workflows/docker-build-validation.yml
vendored
@@ -39,42 +39,68 @@ jobs:
|
|||||||
--health-retries 5
|
--health-retries 5
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
|
- name: Harden the runner (Audit all outbound calls)
|
||||||
|
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
||||||
|
with:
|
||||||
|
egress-policy: audit
|
||||||
|
|
||||||
- name: Checkout Repository
|
- name: Checkout Repository
|
||||||
uses: actions/checkout@v4.2.2
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
|
||||||
|
|
||||||
- name: Build Docker Image
|
- name: Build Docker Image
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||||
|
env:
|
||||||
|
GITHUB_SHA: ${{ github.sha }}
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
file: ./apps/web/Dockerfile
|
file: ./apps/web/Dockerfile
|
||||||
push: false
|
push: false
|
||||||
load: true
|
load: true
|
||||||
tags: formbricks-test:${{ github.sha }}
|
tags: formbricks-test:${{ env.GITHUB_SHA }}
|
||||||
cache-from: type=gha
|
cache-from: type=gha
|
||||||
cache-to: type=gha,mode=max
|
cache-to: type=gha,mode=max
|
||||||
secrets: |
|
secrets: |
|
||||||
database_url=${{ secrets.DUMMY_DATABASE_URL }}
|
database_url=${{ secrets.DUMMY_DATABASE_URL }}
|
||||||
encryption_key=${{ secrets.DUMMY_ENCRYPTION_KEY }}
|
encryption_key=${{ secrets.DUMMY_ENCRYPTION_KEY }}
|
||||||
|
|
||||||
- name: Verify PostgreSQL Connection
|
- name: Verify and Initialize PostgreSQL
|
||||||
run: |
|
run: |
|
||||||
echo "Verifying PostgreSQL connection..."
|
echo "Verifying PostgreSQL connection..."
|
||||||
# Install PostgreSQL client to test connection
|
# Install PostgreSQL client to test connection
|
||||||
sudo apt-get update && sudo apt-get install -y postgresql-client
|
sudo apt-get update && sudo apt-get install -y postgresql-client
|
||||||
|
|
||||||
# Test connection using psql
|
# Test connection using psql with timeout and proper error handling
|
||||||
PGPASSWORD=test psql -h localhost -U test -d formbricks -c "\dt" || echo "Failed to connect to PostgreSQL"
|
echo "Testing PostgreSQL connection with 30 second timeout..."
|
||||||
|
if timeout 30 bash -c 'until PGPASSWORD=test psql -h localhost -U test -d formbricks -c "\dt" >/dev/null 2>&1; do
|
||||||
|
echo "Waiting for PostgreSQL to be ready..."
|
||||||
|
sleep 2
|
||||||
|
done'; then
|
||||||
|
echo "✅ PostgreSQL connection successful"
|
||||||
|
PGPASSWORD=test psql -h localhost -U test -d formbricks -c "SELECT version();"
|
||||||
|
|
||||||
|
# Enable necessary extensions that might be required by migrations
|
||||||
|
echo "Enabling required PostgreSQL extensions..."
|
||||||
|
PGPASSWORD=test psql -h localhost -U test -d formbricks -c "CREATE EXTENSION IF NOT EXISTS vector;" || echo "Vector extension already exists or not available"
|
||||||
|
|
||||||
|
else
|
||||||
|
echo "❌ PostgreSQL connection failed after 30 seconds"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
# Show network configuration
|
# Show network configuration
|
||||||
echo "Network configuration:"
|
echo "Network configuration:"
|
||||||
ip addr show
|
|
||||||
netstat -tulpn | grep 5432 || echo "No process listening on port 5432"
|
netstat -tulpn | grep 5432 || echo "No process listening on port 5432"
|
||||||
|
|
||||||
- name: Test Docker Image with Health Check
|
- name: Test Docker Image with Health Check
|
||||||
shell: bash
|
shell: bash
|
||||||
|
env:
|
||||||
|
GITHUB_SHA: ${{ github.sha }}
|
||||||
|
DUMMY_ENCRYPTION_KEY: ${{ secrets.DUMMY_ENCRYPTION_KEY }}
|
||||||
run: |
|
run: |
|
||||||
echo "🧪 Testing if the Docker image starts correctly..."
|
echo "🧪 Testing if the Docker image starts correctly..."
|
||||||
|
|
||||||
@@ -86,29 +112,12 @@ jobs:
|
|||||||
$DOCKER_RUN_ARGS \
|
$DOCKER_RUN_ARGS \
|
||||||
-p 3000:3000 \
|
-p 3000:3000 \
|
||||||
-e DATABASE_URL="postgresql://test:test@host.docker.internal:5432/formbricks" \
|
-e DATABASE_URL="postgresql://test:test@host.docker.internal:5432/formbricks" \
|
||||||
-e ENCRYPTION_KEY="${{ secrets.DUMMY_ENCRYPTION_KEY }}" \
|
-e ENCRYPTION_KEY="$DUMMY_ENCRYPTION_KEY" \
|
||||||
-d formbricks-test:${{ github.sha }}
|
-d "formbricks-test:$GITHUB_SHA"
|
||||||
|
|
||||||
# Give it more time to start up
|
# Start health check polling immediately (every 5 seconds for up to 5 minutes)
|
||||||
echo "Waiting 45 seconds for application to start..."
|
echo "🏥 Polling /health endpoint every 5 seconds for up to 5 minutes..."
|
||||||
sleep 45
|
MAX_RETRIES=60 # 60 attempts × 5 seconds = 5 minutes
|
||||||
|
|
||||||
# Check if the container is running
|
|
||||||
if [ "$(docker inspect -f '{{.State.Running}}' formbricks-test)" != "true" ]; then
|
|
||||||
echo "❌ Container failed to start properly!"
|
|
||||||
docker logs formbricks-test
|
|
||||||
exit 1
|
|
||||||
else
|
|
||||||
echo "✅ Container started successfully!"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Try connecting to PostgreSQL from inside the container
|
|
||||||
echo "Testing PostgreSQL connection from inside container..."
|
|
||||||
docker exec formbricks-test sh -c 'apt-get update && apt-get install -y postgresql-client && PGPASSWORD=test psql -h host.docker.internal -U test -d formbricks -c "\dt" || echo "Failed to connect to PostgreSQL from container"'
|
|
||||||
|
|
||||||
# Try to access the health endpoint
|
|
||||||
echo "🏥 Testing /health endpoint..."
|
|
||||||
MAX_RETRIES=10
|
|
||||||
RETRY_COUNT=0
|
RETRY_COUNT=0
|
||||||
HEALTH_CHECK_SUCCESS=false
|
HEALTH_CHECK_SUCCESS=false
|
||||||
|
|
||||||
@@ -116,38 +125,32 @@ jobs:
|
|||||||
|
|
||||||
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
|
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
|
||||||
RETRY_COUNT=$((RETRY_COUNT + 1))
|
RETRY_COUNT=$((RETRY_COUNT + 1))
|
||||||
echo "Attempt $RETRY_COUNT of $MAX_RETRIES..."
|
|
||||||
|
# Check if container is still running
|
||||||
# Show container logs before each attempt to help debugging
|
if [ "$(docker inspect -f '{{.State.Running}}' formbricks-test 2>/dev/null)" != "true" ]; then
|
||||||
if [ $RETRY_COUNT -gt 1 ]; then
|
echo "❌ Container stopped running after $((RETRY_COUNT * 5)) seconds!"
|
||||||
echo "📋 Current container logs:"
|
echo "📋 Container logs:"
|
||||||
docker logs --tail 20 formbricks-test
|
docker logs formbricks-test
|
||||||
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Get detailed curl output for debugging
|
# Show progress and diagnostic info every 12 attempts (1 minute intervals)
|
||||||
HTTP_OUTPUT=$(curl -v -s -m 30 http://localhost:3000/health 2>&1)
|
if [ $((RETRY_COUNT % 12)) -eq 0 ] || [ $RETRY_COUNT -eq 1 ]; then
|
||||||
CURL_EXIT_CODE=$?
|
echo "Health check attempt $RETRY_COUNT of $MAX_RETRIES ($(($RETRY_COUNT * 5)) seconds elapsed)..."
|
||||||
|
echo "📋 Recent container logs:"
|
||||||
echo "Curl exit code: $CURL_EXIT_CODE"
|
docker logs --tail 10 formbricks-test
|
||||||
echo "Curl output: $HTTP_OUTPUT"
|
|
||||||
|
|
||||||
if [ $CURL_EXIT_CODE -eq 0 ]; then
|
|
||||||
STATUS_CODE=$(echo "$HTTP_OUTPUT" | grep -oP "HTTP/\d(\.\d)? \K\d+")
|
|
||||||
echo "Status code detected: $STATUS_CODE"
|
|
||||||
|
|
||||||
if [ "$STATUS_CODE" = "200" ]; then
|
|
||||||
echo "✅ Health check successful!"
|
|
||||||
HEALTH_CHECK_SUCCESS=true
|
|
||||||
break
|
|
||||||
else
|
|
||||||
echo "❌ Health check returned non-200 status code: $STATUS_CODE"
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
echo "❌ Curl command failed with exit code: $CURL_EXIT_CODE"
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "Waiting 15 seconds before next attempt..."
|
# Try health endpoint with shorter timeout for faster polling
|
||||||
sleep 15
|
# Use -f flag to make curl fail on HTTP error status codes (4xx, 5xx)
|
||||||
|
if curl -f -s -m 10 http://localhost:3000/health >/dev/null 2>&1; then
|
||||||
|
echo "✅ Health check successful after $((RETRY_COUNT * 5)) seconds!"
|
||||||
|
HEALTH_CHECK_SUCCESS=true
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Wait 5 seconds before next attempt
|
||||||
|
sleep 5
|
||||||
done
|
done
|
||||||
|
|
||||||
# Show full container logs for debugging
|
# Show full container logs for debugging
|
||||||
@@ -160,7 +163,7 @@ jobs:
|
|||||||
|
|
||||||
# Exit with failure if health check did not succeed
|
# Exit with failure if health check did not succeed
|
||||||
if [ "$HEALTH_CHECK_SUCCESS" != "true" ]; then
|
if [ "$HEALTH_CHECK_SUCCESS" != "true" ]; then
|
||||||
echo "❌ Health check failed after $MAX_RETRIES attempts"
|
echo "❌ Health check failed after $((MAX_RETRIES * 5)) seconds (5 minutes)"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|||||||
40
.github/workflows/docker-security-scan.yml
vendored
Normal file
40
.github/workflows/docker-security-scan.yml
vendored
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
name: Docker Security Scan
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 2 * * *" # Daily at 2 AM UTC
|
||||||
|
workflow_dispatch:
|
||||||
|
workflow_run:
|
||||||
|
workflows: ["Docker Release to Github"]
|
||||||
|
types: [completed]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: read
|
||||||
|
security-events: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
scan:
|
||||||
|
name: Vulnerability Scan
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Log in to GitHub Container Registry
|
||||||
|
uses: docker/login-action@184bdaa0721073962dff0199f1fb9940f07167d1 # v3.5.0
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.actor }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Run Trivy vulnerability scanner
|
||||||
|
uses: aquasecurity/trivy-action@dc5a429b52fcf669ce959baa2c2dd26090d2a6c4 # v0.32.0
|
||||||
|
with:
|
||||||
|
image-ref: "ghcr.io/${{ github.repository }}:latest"
|
||||||
|
format: "sarif"
|
||||||
|
output: "trivy-results.sarif"
|
||||||
|
severity: "CRITICAL,HIGH,MEDIUM,LOW"
|
||||||
|
|
||||||
|
- name: Upload Trivy scan results to GitHub Security tab
|
||||||
|
uses: github/codeql-action/upload-sarif@a4e1a019f5e24960714ff6296aee04b736cbc3cf # v3.29.6
|
||||||
|
if: ${{ always() && hashFiles('trivy-results.sarif') != '' }}
|
||||||
|
with:
|
||||||
|
sarif_file: "trivy-results.sarif"
|
||||||
34
.github/workflows/formbricks-release.yml
vendored
34
.github/workflows/formbricks-release.yml
vendored
@@ -1,20 +1,29 @@
|
|||||||
name: Build, release & deploy Formbricks images
|
name: Build, release & deploy Formbricks images
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
release:
|
||||||
push:
|
types: [published]
|
||||||
tags:
|
|
||||||
- "v*"
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
docker-build:
|
docker-build:
|
||||||
name: Build & release stable docker image
|
name: Build & release docker image
|
||||||
if: startsWith(github.ref, 'refs/tags/v')
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
id-token: write
|
||||||
uses: ./.github/workflows/release-docker-github.yml
|
uses: ./.github/workflows/release-docker-github.yml
|
||||||
secrets: inherit
|
secrets: inherit
|
||||||
|
with:
|
||||||
|
IS_PRERELEASE: ${{ github.event.release.prerelease }}
|
||||||
|
|
||||||
helm-chart-release:
|
helm-chart-release:
|
||||||
name: Release Helm Chart
|
name: Release Helm Chart
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
uses: ./.github/workflows/release-helm-chart.yml
|
uses: ./.github/workflows/release-helm-chart.yml
|
||||||
secrets: inherit
|
secrets: inherit
|
||||||
needs:
|
needs:
|
||||||
@@ -24,6 +33,9 @@ jobs:
|
|||||||
|
|
||||||
deploy-formbricks-cloud:
|
deploy-formbricks-cloud:
|
||||||
name: Deploy Helm Chart to Formbricks Cloud
|
name: Deploy Helm Chart to Formbricks Cloud
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
id-token: write
|
||||||
secrets: inherit
|
secrets: inherit
|
||||||
uses: ./.github/workflows/deploy-formbricks-cloud.yml
|
uses: ./.github/workflows/deploy-formbricks-cloud.yml
|
||||||
needs:
|
needs:
|
||||||
@@ -31,7 +43,7 @@ jobs:
|
|||||||
- helm-chart-release
|
- helm-chart-release
|
||||||
with:
|
with:
|
||||||
VERSION: v${{ needs.docker-build.outputs.VERSION }}
|
VERSION: v${{ needs.docker-build.outputs.VERSION }}
|
||||||
ENVIRONMENT: "prod"
|
ENVIRONMENT: ${{ github.event.release.prerelease && 'staging' || 'production' }}
|
||||||
|
|
||||||
upload-sentry-sourcemaps:
|
upload-sentry-sourcemaps:
|
||||||
name: Upload Sentry Sourcemaps
|
name: Upload Sentry Sourcemaps
|
||||||
@@ -42,8 +54,13 @@ jobs:
|
|||||||
- docker-build
|
- docker-build
|
||||||
- deploy-formbricks-cloud
|
- deploy-formbricks-cloud
|
||||||
steps:
|
steps:
|
||||||
|
- name: Harden the runner (Audit all outbound calls)
|
||||||
|
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
||||||
|
with:
|
||||||
|
egress-policy: audit
|
||||||
|
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4.2.2
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
@@ -54,3 +71,4 @@ jobs:
|
|||||||
docker_image: ghcr.io/formbricks/formbricks:v${{ needs.docker-build.outputs.VERSION }}
|
docker_image: ghcr.io/formbricks/formbricks:v${{ needs.docker-build.outputs.VERSION }}
|
||||||
release_version: v${{ needs.docker-build.outputs.VERSION }}
|
release_version: v${{ needs.docker-build.outputs.VERSION }}
|
||||||
sentry_auth_token: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
sentry_auth_token: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||||
|
environment: ${{ github.event.release.prerelease && 'staging' || 'production' }}
|
||||||
|
|||||||
@@ -29,6 +29,10 @@ jobs:
|
|||||||
# with sigstore/fulcio when running outside of PRs.
|
# with sigstore/fulcio when running outside of PRs.
|
||||||
id-token: write
|
id-token: write
|
||||||
|
|
||||||
|
outputs:
|
||||||
|
DOCKER_IMAGE: ${{ steps.extract_image_info.outputs.DOCKER_IMAGE }}
|
||||||
|
RELEASE_VERSION: ${{ steps.extract_image_info.outputs.RELEASE_VERSION }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Harden the runner (Audit all outbound calls)
|
- name: Harden the runner (Audit all outbound calls)
|
||||||
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
||||||
@@ -37,6 +41,55 @@ jobs:
|
|||||||
|
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Generate SemVer version from branch or tag
|
||||||
|
id: generate_version
|
||||||
|
env:
|
||||||
|
REF_NAME: ${{ github.ref_name }}
|
||||||
|
REF_TYPE: ${{ github.ref_type }}
|
||||||
|
run: |
|
||||||
|
# Get reference name and type from environment variables
|
||||||
|
echo "Reference type: $REF_TYPE"
|
||||||
|
echo "Reference name: $REF_NAME"
|
||||||
|
|
||||||
|
if [[ "$REF_TYPE" == "tag" ]]; then
|
||||||
|
# If running from a tag, use the tag name
|
||||||
|
if [[ "$REF_NAME" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+.*$ ]]; then
|
||||||
|
# Tag looks like a SemVer, use it directly (remove 'v' prefix if present)
|
||||||
|
VERSION=$(echo "$REF_NAME" | sed 's/^v//')
|
||||||
|
echo "Using SemVer tag: $VERSION"
|
||||||
|
else
|
||||||
|
# Tag is not SemVer, treat as prerelease
|
||||||
|
SANITIZED_TAG=$(echo "$REF_NAME" | sed 's/[^a-zA-Z0-9.-]/-/g' | sed 's/--*/-/g' | sed 's/^-\|-$//g')
|
||||||
|
VERSION="0.0.0-$SANITIZED_TAG"
|
||||||
|
echo "Using tag as prerelease: $VERSION"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
# Running from branch, use branch name as prerelease
|
||||||
|
SANITIZED_BRANCH=$(echo "$REF_NAME" | sed 's/[^a-zA-Z0-9.-]/-/g' | sed 's/--*/-/g' | sed 's/^-\|-$//g')
|
||||||
|
VERSION="0.0.0-$SANITIZED_BRANCH"
|
||||||
|
echo "Using branch as prerelease: $VERSION"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "VERSION=$VERSION" >> $GITHUB_ENV
|
||||||
|
echo "VERSION=$VERSION" >> $GITHUB_OUTPUT
|
||||||
|
echo "Generated SemVer version: $VERSION"
|
||||||
|
|
||||||
|
- name: Update package.json version
|
||||||
|
run: |
|
||||||
|
sed -i "s/\"version\": \"0.0.0\"/\"version\": \"${{ env.VERSION }}\"/" ./apps/web/package.json
|
||||||
|
cat ./apps/web/package.json | grep version
|
||||||
|
|
||||||
|
- name: Set Sentry environment in .env
|
||||||
|
run: |
|
||||||
|
if ! grep -q "^SENTRY_ENVIRONMENT=staging$" .env 2>/dev/null; then
|
||||||
|
echo "SENTRY_ENVIRONMENT=staging" >> .env
|
||||||
|
echo "Added SENTRY_ENVIRONMENT=staging to .env file"
|
||||||
|
else
|
||||||
|
echo "SENTRY_ENVIRONMENT=staging already exists in .env file"
|
||||||
|
fi
|
||||||
|
|
||||||
- name: Set up Depot CLI
|
- name: Set up Depot CLI
|
||||||
uses: depot/setup-action@b0b1ea4f69e92ebf5dea3f8713a1b0c37b2126a5 # v1.6.0
|
uses: depot/setup-action@b0b1ea4f69e92ebf5dea3f8713a1b0c37b2126a5 # v1.6.0
|
||||||
@@ -83,6 +136,21 @@ jobs:
|
|||||||
database_url=${{ secrets.DUMMY_DATABASE_URL }}
|
database_url=${{ secrets.DUMMY_DATABASE_URL }}
|
||||||
encryption_key=${{ secrets.DUMMY_ENCRYPTION_KEY }}
|
encryption_key=${{ secrets.DUMMY_ENCRYPTION_KEY }}
|
||||||
|
|
||||||
|
- name: Extract image info for sourcemap upload
|
||||||
|
id: extract_image_info
|
||||||
|
run: |
|
||||||
|
# Use the first readable tag from metadata action output
|
||||||
|
DOCKER_IMAGE=$(echo "${{ steps.meta.outputs.tags }}" | head -n1 | xargs)
|
||||||
|
echo "DOCKER_IMAGE=$DOCKER_IMAGE" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
# Use the generated version for Sentry release
|
||||||
|
RELEASE_VERSION="$VERSION"
|
||||||
|
echo "RELEASE_VERSION=$RELEASE_VERSION" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
echo "Docker image: $DOCKER_IMAGE"
|
||||||
|
echo "Release version: $RELEASE_VERSION"
|
||||||
|
echo "Available tags: ${{ steps.meta.outputs.tags }}"
|
||||||
|
|
||||||
# Sign the resulting Docker image digest except on PRs.
|
# Sign the resulting Docker image digest except on PRs.
|
||||||
# This will only write to the public Rekor transparency log when the Docker
|
# This will only write to the public Rekor transparency log when the Docker
|
||||||
# repository is public to avoid leaking data. If you would like to publish
|
# repository is public to avoid leaking data. If you would like to publish
|
||||||
@@ -97,3 +165,30 @@ jobs:
|
|||||||
# This step uses the identity token to provision an ephemeral certificate
|
# This step uses the identity token to provision an ephemeral certificate
|
||||||
# against the sigstore community Fulcio instance.
|
# against the sigstore community Fulcio instance.
|
||||||
run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST}
|
run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST}
|
||||||
|
|
||||||
|
upload-sentry-sourcemaps:
|
||||||
|
name: Upload Sentry Sourcemaps
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
needs:
|
||||||
|
- build
|
||||||
|
steps:
|
||||||
|
- name: Harden the runner (Audit all outbound calls)
|
||||||
|
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
||||||
|
with:
|
||||||
|
egress-policy: audit
|
||||||
|
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Upload Sentry Sourcemaps
|
||||||
|
uses: ./.github/actions/upload-sentry-sourcemaps
|
||||||
|
continue-on-error: true
|
||||||
|
with:
|
||||||
|
docker_image: ${{ needs.build.outputs.DOCKER_IMAGE }}
|
||||||
|
release_version: ${{ needs.build.outputs.RELEASE_VERSION }}
|
||||||
|
sentry_auth_token: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||||
|
environment: staging
|
||||||
|
|||||||
31
.github/workflows/release-docker-github.yml
vendored
31
.github/workflows/release-docker-github.yml
vendored
@@ -7,6 +7,12 @@ name: Docker Release to Github
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_call:
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
IS_PRERELEASE:
|
||||||
|
description: "Whether this is a prerelease (affects latest tag)"
|
||||||
|
required: false
|
||||||
|
type: boolean
|
||||||
|
default: false
|
||||||
outputs:
|
outputs:
|
||||||
VERSION:
|
VERSION:
|
||||||
description: release version
|
description: release version
|
||||||
@@ -20,6 +26,9 @@ env:
|
|||||||
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||||
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
|
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -45,10 +54,23 @@ jobs:
|
|||||||
- name: Get Release Tag
|
- name: Get Release Tag
|
||||||
id: extract_release_tag
|
id: extract_release_tag
|
||||||
run: |
|
run: |
|
||||||
TAG=${{ github.ref }}
|
# Extract version from tag (e.g., refs/tags/v1.2.3 -> 1.2.3)
|
||||||
|
TAG="$GITHUB_REF"
|
||||||
TAG=${TAG#refs/tags/v}
|
TAG=${TAG#refs/tags/v}
|
||||||
|
|
||||||
|
# Validate the extracted tag format
|
||||||
|
if [[ ! "$TAG" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$ ]]; then
|
||||||
|
echo "❌ Error: Invalid release tag format after extraction. Must be semver (e.g., 1.2.3, 1.2.3-alpha)"
|
||||||
|
echo "Original ref: $GITHUB_REF"
|
||||||
|
echo "Extracted tag: $TAG"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Safely add to environment variables
|
||||||
echo "RELEASE_TAG=$TAG" >> $GITHUB_ENV
|
echo "RELEASE_TAG=$TAG" >> $GITHUB_ENV
|
||||||
|
|
||||||
echo "VERSION=$TAG" >> $GITHUB_OUTPUT
|
echo "VERSION=$TAG" >> $GITHUB_OUTPUT
|
||||||
|
echo "Using tag-based version: $TAG"
|
||||||
|
|
||||||
- name: Update package.json version
|
- name: Update package.json version
|
||||||
run: |
|
run: |
|
||||||
@@ -81,6 +103,13 @@ jobs:
|
|||||||
uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # v5.7.0
|
uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # v5.7.0
|
||||||
with:
|
with:
|
||||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||||
|
tags: |
|
||||||
|
# Default semver tags (version, major.minor, major)
|
||||||
|
type=semver,pattern={{version}}
|
||||||
|
type=semver,pattern={{major}}.{{minor}}
|
||||||
|
type=semver,pattern={{major}}
|
||||||
|
# Only tag as 'latest' for stable releases (not prereleases)
|
||||||
|
type=raw,value=latest,enable=${{ inputs.IS_PRERELEASE != 'true' }}
|
||||||
|
|
||||||
# Build and push Docker image with Buildx (don't push on PR)
|
# Build and push Docker image with Buildx (don't push on PR)
|
||||||
# https://github.com/docker/build-push-action
|
# https://github.com/docker/build-push-action
|
||||||
|
|||||||
30
.github/workflows/release-helm-chart.yml
vendored
30
.github/workflows/release-helm-chart.yml
vendored
@@ -26,8 +26,23 @@ jobs:
|
|||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
|
||||||
- name: Extract release version
|
- name: Validate input version
|
||||||
run: echo "VERSION=${{ github.event.release.tag_name }}" >> $GITHUB_ENV
|
env:
|
||||||
|
INPUT_VERSION: ${{ inputs.VERSION }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
# Validate input version format (expects clean semver without 'v' prefix)
|
||||||
|
if [[ ! "$INPUT_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$ ]]; then
|
||||||
|
echo "❌ Error: Invalid version format. Must be clean semver (e.g., 1.2.3, 1.2.3-alpha)"
|
||||||
|
echo "Expected: clean version without 'v' prefix"
|
||||||
|
echo "Provided: $INPUT_VERSION"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Store validated version in environment variable
|
||||||
|
echo "VERSION<<EOF" >> $GITHUB_ENV
|
||||||
|
echo "$INPUT_VERSION" >> $GITHUB_ENV
|
||||||
|
echo "EOF" >> $GITHUB_ENV
|
||||||
|
|
||||||
- name: Set up Helm
|
- name: Set up Helm
|
||||||
uses: azure/setup-helm@5119fcb9089d432beecbf79bb2c7915207344b78 # v3.5
|
uses: azure/setup-helm@5119fcb9089d432beecbf79bb2c7915207344b78 # v3.5
|
||||||
@@ -35,15 +50,18 @@ jobs:
|
|||||||
version: latest
|
version: latest
|
||||||
|
|
||||||
- name: Log in to GitHub Container Registry
|
- name: Log in to GitHub Container Registry
|
||||||
run: echo "${{ secrets.GITHUB_TOKEN }}" | helm registry login ghcr.io --username ${{ github.actor }} --password-stdin
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
GITHUB_ACTOR: ${{ github.actor }}
|
||||||
|
run: printf '%s' "$GITHUB_TOKEN" | helm registry login ghcr.io --username "$GITHUB_ACTOR" --password-stdin
|
||||||
|
|
||||||
- name: Install YQ
|
- name: Install YQ
|
||||||
uses: dcarbone/install-yq-action@4075b4dca348d74bd83f2bf82d30f25d7c54539b # v1.3.1
|
uses: dcarbone/install-yq-action@4075b4dca348d74bd83f2bf82d30f25d7c54539b # v1.3.1
|
||||||
|
|
||||||
- name: Update Chart.yaml with new version
|
- name: Update Chart.yaml with new version
|
||||||
run: |
|
run: |
|
||||||
yq -i ".version = \"${{ inputs.VERSION }}\"" helm-chart/Chart.yaml
|
yq -i ".version = \"$VERSION\"" helm-chart/Chart.yaml
|
||||||
yq -i ".appVersion = \"v${{ inputs.VERSION }}\"" helm-chart/Chart.yaml
|
yq -i ".appVersion = \"v$VERSION\"" helm-chart/Chart.yaml
|
||||||
|
|
||||||
- name: Package Helm chart
|
- name: Package Helm chart
|
||||||
run: |
|
run: |
|
||||||
@@ -51,4 +69,4 @@ jobs:
|
|||||||
|
|
||||||
- name: Push Helm chart to GitHub Container Registry
|
- name: Push Helm chart to GitHub Container Registry
|
||||||
run: |
|
run: |
|
||||||
helm push formbricks-${{ inputs.VERSION }}.tgz oci://ghcr.io/formbricks/helm-charts
|
helm push "formbricks-$VERSION.tgz" oci://ghcr.io/formbricks/helm-charts
|
||||||
|
|||||||
81
.github/workflows/scorecard.yml
vendored
81
.github/workflows/scorecard.yml
vendored
@@ -1,81 +0,0 @@
|
|||||||
# This workflow uses actions that are not certified by GitHub. They are provided
|
|
||||||
# by a third-party and are governed by separate terms of service, privacy
|
|
||||||
# policy, and support documentation.
|
|
||||||
|
|
||||||
name: Scorecard supply-chain security
|
|
||||||
on:
|
|
||||||
# For Branch-Protection check. Only the default branch is supported. See
|
|
||||||
# https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection
|
|
||||||
branch_protection_rule:
|
|
||||||
# To guarantee Maintained check is occasionally updated. See
|
|
||||||
# https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained
|
|
||||||
schedule:
|
|
||||||
- cron: "17 17 * * 6"
|
|
||||||
push:
|
|
||||||
branches: ["main"]
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
# Declare default permissions as read only.
|
|
||||||
permissions: read-all
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
analysis:
|
|
||||||
name: Scorecard analysis
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
# Needed to upload the results to code-scanning dashboard.
|
|
||||||
security-events: write
|
|
||||||
# Needed to publish results and get a badge (see publish_results below).
|
|
||||||
id-token: write
|
|
||||||
# Add this permission
|
|
||||||
actions: write # Required for artifact upload
|
|
||||||
# Uncomment the permissions below if installing in a private repository.
|
|
||||||
# contents: read
|
|
||||||
# actions: read
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Harden the runner (Audit all outbound calls)
|
|
||||||
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
|
||||||
with:
|
|
||||||
egress-policy: audit
|
|
||||||
|
|
||||||
- name: "Checkout code"
|
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
- name: "Run analysis"
|
|
||||||
uses: ossf/scorecard-action@0864cf19026789058feabb7e87baa5f140aac736 # v2.3.1
|
|
||||||
with:
|
|
||||||
results_file: results.sarif
|
|
||||||
results_format: sarif
|
|
||||||
# (Optional) "write" PAT token. Uncomment the `repo_token` line below if:
|
|
||||||
# - you want to enable the Branch-Protection check on a *public* repository, or
|
|
||||||
# - you are installing Scorecard on a *private* repository
|
|
||||||
# To create the PAT, follow the steps in https://github.com/ossf/scorecard-action?tab=readme-ov-file#authentication-with-fine-grained-pat-optional.
|
|
||||||
# repo_token: ${{ secrets.SCORECARD_TOKEN }}
|
|
||||||
|
|
||||||
# Public repositories:
|
|
||||||
# - Publish results to OpenSSF REST API for easy access by consumers
|
|
||||||
# - Allows the repository to include the Scorecard badge.
|
|
||||||
# - See https://github.com/ossf/scorecard-action#publishing-results.
|
|
||||||
# For private repositories:
|
|
||||||
# - `publish_results` will always be set to `false`, regardless
|
|
||||||
# of the value entered here.
|
|
||||||
publish_results: true
|
|
||||||
|
|
||||||
# Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
|
|
||||||
# format to the repository Actions tab.
|
|
||||||
- name: "Upload artifact"
|
|
||||||
uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0
|
|
||||||
with:
|
|
||||||
name: sarif
|
|
||||||
path: results.sarif
|
|
||||||
retention-days: 5
|
|
||||||
|
|
||||||
# Upload the results to GitHub's code scanning dashboard (optional).
|
|
||||||
# Commenting out will disable upload of results to your repo's Code Scanning dashboard
|
|
||||||
- name: "Upload to code-scanning"
|
|
||||||
uses: github/codeql-action/upload-sarif@b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d # v3.28.10
|
|
||||||
with:
|
|
||||||
sarif_file: results.sarif
|
|
||||||
8
.github/workflows/semantic-pull-requests.yml
vendored
8
.github/workflows/semantic-pull-requests.yml
vendored
@@ -56,11 +56,3 @@ jobs:
|
|||||||
```
|
```
|
||||||
${{ steps.lint_pr_title.outputs.error_message }}
|
${{ steps.lint_pr_title.outputs.error_message }}
|
||||||
```
|
```
|
||||||
|
|
||||||
# Delete a previous comment when the issue has been resolved
|
|
||||||
- if: ${{ steps.lint_pr_title.outputs.error_message == null }}
|
|
||||||
uses: marocchino/sticky-pull-request-comment@67d0dec7b07ed060a405f9b2a64b8ab319fdd7db # v2.9.2
|
|
||||||
with:
|
|
||||||
header: pr-title-lint-error
|
|
||||||
message: |
|
|
||||||
Thank you for following the naming conventions for pull request titles! 🙏
|
|
||||||
|
|||||||
@@ -14,12 +14,14 @@ on:
|
|||||||
paths:
|
paths:
|
||||||
- "infra/terraform/**"
|
- "infra/terraform/**"
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
terraform:
|
terraform:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
id-token: write
|
id-token: write
|
||||||
contents: read
|
|
||||||
pull-requests: write
|
pull-requests: write
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@@ -33,7 +35,7 @@ jobs:
|
|||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
|
||||||
- name: Tailscale
|
- name: Tailscale
|
||||||
uses: tailscale/github-action@v3
|
uses: tailscale/github-action@84a3f23bb4d843bcf4da6cf824ec1be473daf4de # v3.2.3
|
||||||
with:
|
with:
|
||||||
oauth-client-id: ${{ secrets.TS_OAUTH_CLIENT_ID }}
|
oauth-client-id: ${{ secrets.TS_OAUTH_CLIENT_ID }}
|
||||||
oauth-secret: ${{ secrets.TS_OAUTH_SECRET }}
|
oauth-secret: ${{ secrets.TS_OAUTH_SECRET }}
|
||||||
|
|||||||
10
.github/workflows/tolgee.yml
vendored
10
.github/workflows/tolgee.yml
vendored
@@ -27,10 +27,18 @@ jobs:
|
|||||||
|
|
||||||
- name: Get source branch name
|
- name: Get source branch name
|
||||||
id: branch-name
|
id: branch-name
|
||||||
|
env:
|
||||||
|
RAW_BRANCH: ${{ github.head_ref }}
|
||||||
run: |
|
run: |
|
||||||
RAW_BRANCH="${{ github.head_ref }}"
|
# Validate and sanitize branch name - only allow alphanumeric, dots, underscores, hyphens, and forward slashes
|
||||||
SOURCE_BRANCH=$(echo "$RAW_BRANCH" | sed 's/[^a-zA-Z0-9._\/-]//g')
|
SOURCE_BRANCH=$(echo "$RAW_BRANCH" | sed 's/[^a-zA-Z0-9._\/-]//g')
|
||||||
|
|
||||||
|
# Additional validation - ensure branch name is not empty after sanitization
|
||||||
|
if [[ -z "$SOURCE_BRANCH" ]]; then
|
||||||
|
echo "❌ Error: Branch name is empty after sanitization"
|
||||||
|
echo "Original branch: $RAW_BRANCH"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
# Safely add to environment variables using GitHub's recommended method
|
# Safely add to environment variables using GitHub's recommended method
|
||||||
# This prevents environment variable injection attacks
|
# This prevents environment variable injection attacks
|
||||||
|
|||||||
20
.github/workflows/upload-sentry-sourcemaps.yml
vendored
20
.github/workflows/upload-sentry-sourcemaps.yml
vendored
@@ -23,24 +23,26 @@ jobs:
|
|||||||
upload-sourcemaps:
|
upload-sourcemaps:
|
||||||
name: Upload Sourcemaps to Sentry
|
name: Upload Sourcemaps to Sentry
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
|
- name: Harden the runner (Audit all outbound calls)
|
||||||
|
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
||||||
|
with:
|
||||||
|
egress-policy: audit
|
||||||
|
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4.2.2
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- name: Set Docker Image
|
- name: Set Docker Image
|
||||||
run: |
|
run: echo "DOCKER_IMAGE=${DOCKER_IMAGE}" >> $GITHUB_ENV
|
||||||
if [ -n "${{ inputs.tag_version }}" ]; then
|
env:
|
||||||
echo "DOCKER_IMAGE=${{ inputs.docker_image }}:${{ inputs.tag_version }}" >> $GITHUB_ENV
|
DOCKER_IMAGE: ${{ inputs.docker_image }}:${{ inputs.tag_version != '' && inputs.tag_version || inputs.release_version }}
|
||||||
else
|
|
||||||
echo "DOCKER_IMAGE=${{ inputs.docker_image }}:${{ inputs.release_version }}" >> $GITHUB_ENV
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Upload Sourcemaps to Sentry
|
- name: Upload Sourcemaps to Sentry
|
||||||
uses: ./.github/actions/upload-sentry-sourcemaps
|
uses: ./.github/actions/upload-sentry-sourcemaps
|
||||||
with:
|
with:
|
||||||
docker_image: ${{ env.DOCKER_IMAGE }}
|
docker_image: ${{ env.DOCKER_IMAGE }}
|
||||||
release_version: ${{ inputs.release_version }}
|
release_version: ${{ inputs.release_version }}
|
||||||
sentry_auth_token: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
sentry_auth_token: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||||
|
|||||||
32
.github/workflows/welcome-new-contributors.yml
vendored
32
.github/workflows/welcome-new-contributors.yml
vendored
@@ -1,32 +0,0 @@
|
|||||||
name: "Welcome new contributors"
|
|
||||||
|
|
||||||
on:
|
|
||||||
issues:
|
|
||||||
types: opened
|
|
||||||
pull_request_target:
|
|
||||||
types: opened
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
pull-requests: write
|
|
||||||
issues: write
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
welcome-message:
|
|
||||||
name: Welcoming New Users
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
timeout-minutes: 10
|
|
||||||
if: github.event.action == 'opened'
|
|
||||||
steps:
|
|
||||||
- name: Harden the runner (Audit all outbound calls)
|
|
||||||
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
|
||||||
with:
|
|
||||||
egress-policy: audit
|
|
||||||
|
|
||||||
- uses: actions/first-interaction@3c71ce730280171fd1cfb57c00c774f8998586f7 # v1
|
|
||||||
with:
|
|
||||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
pr-message: |-
|
|
||||||
Thank you so much for making your first Pull Request and taking the time to improve Formbricks! 🚀🙏❤️
|
|
||||||
Feel free to join the conversation on [Github Discussions](https://github.com/formbricks/formbricks/discussions) if you need any help or have any questions. 😊
|
|
||||||
issue-message: |
|
|
||||||
Thank you for opening your first issue! 🙏❤️ One of our team members will review it and get back to you as soon as it possible. 😊
|
|
||||||
@@ -31,6 +31,10 @@
|
|||||||
{
|
{
|
||||||
"language": "pt-PT",
|
"language": "pt-PT",
|
||||||
"path": "./apps/web/locales/pt-PT.json"
|
"path": "./apps/web/locales/pt-PT.json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"language": "ro-RO",
|
||||||
|
"path": "./apps/web/locales/ro-RO.json"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"forceMode": "OVERRIDE"
|
"forceMode": "OVERRIDE"
|
||||||
|
|||||||
@@ -1,13 +1,16 @@
|
|||||||
import type { StorybookConfig } from "@storybook/react-vite";
|
import type { StorybookConfig } from "@storybook/react-vite";
|
||||||
|
import { createRequire } from "module";
|
||||||
import { dirname, join } from "path";
|
import { dirname, join } from "path";
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This function is used to resolve the absolute path of a package.
|
* This function is used to resolve the absolute path of a package.
|
||||||
* It is needed in projects that use Yarn PnP or are set up within a monorepo.
|
* It is needed in projects that use Yarn PnP or are set up within a monorepo.
|
||||||
*/
|
*/
|
||||||
const getAbsolutePath = (value: string) => {
|
function getAbsolutePath(value: string): any {
|
||||||
return dirname(require.resolve(join(value, "package.json")));
|
return dirname(require.resolve(join(value, "package.json")));
|
||||||
};
|
}
|
||||||
|
|
||||||
const config: StorybookConfig = {
|
const config: StorybookConfig = {
|
||||||
stories: ["../src/**/*.mdx", "../../web/modules/ui/**/stories.@(js|jsx|mjs|ts|tsx)"],
|
stories: ["../src/**/*.mdx", "../../web/modules/ui/**/stories.@(js|jsx|mjs|ts|tsx)"],
|
||||||
|
|||||||
@@ -80,25 +80,25 @@ export const LandingSidebar = ({
|
|||||||
<DropdownMenuTrigger
|
<DropdownMenuTrigger
|
||||||
asChild
|
asChild
|
||||||
id="userDropdownTrigger"
|
id="userDropdownTrigger"
|
||||||
className="w-full rounded-br-xl border-t py-4 pl-4 transition-colors duration-200 hover:bg-slate-50 focus:outline-none">
|
className="w-full rounded-br-xl border-t p-4 transition-colors duration-200 hover:bg-slate-50 focus:outline-none">
|
||||||
<div tabIndex={0} className={cn("flex cursor-pointer flex-row items-center space-x-3")}>
|
<div tabIndex={0} className={cn("flex cursor-pointer flex-row items-center gap-3")}>
|
||||||
<ProfileAvatar userId={user.id} imageUrl={user.imageUrl} />
|
<ProfileAvatar userId={user.id} imageUrl={user.imageUrl} />
|
||||||
<>
|
<>
|
||||||
<div>
|
<div className="grow overflow-hidden">
|
||||||
<p
|
<p
|
||||||
title={user?.email}
|
title={user?.email}
|
||||||
className={cn(
|
className={cn(
|
||||||
"ph-no-capture ph-no-capture -mb-0.5 max-w-28 truncate text-sm font-bold text-slate-700"
|
"ph-no-capture ph-no-capture -mb-0.5 truncate text-sm font-bold text-slate-700"
|
||||||
)}>
|
)}>
|
||||||
{user?.name ? <span>{user?.name}</span> : <span>{user?.email}</span>}
|
{user?.name ? <span>{user?.name}</span> : <span>{user?.email}</span>}
|
||||||
</p>
|
</p>
|
||||||
<p
|
<p
|
||||||
title={capitalizeFirstLetter(organization?.name)}
|
title={capitalizeFirstLetter(organization?.name)}
|
||||||
className="max-w-28 truncate text-sm text-slate-500">
|
className="truncate text-sm text-slate-500">
|
||||||
{capitalizeFirstLetter(organization?.name)}
|
{capitalizeFirstLetter(organization?.name)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<ChevronRightIcon className={cn("h-5 w-5 text-slate-700 hover:text-slate-500")} />
|
<ChevronRightIcon className={cn("h-5 w-5 shrink-0 text-slate-700 hover:text-slate-500")} />
|
||||||
</>
|
</>
|
||||||
</div>
|
</div>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ describe("ProjectSettings component", () => {
|
|||||||
industry: "ind",
|
industry: "ind",
|
||||||
defaultBrandColor: "#fff",
|
defaultBrandColor: "#fff",
|
||||||
organizationTeams: [],
|
organizationTeams: [],
|
||||||
canDoRoleManagement: false,
|
isAccessControlAllowed: false,
|
||||||
userProjectsCount: 0,
|
userProjectsCount: 0,
|
||||||
} as any;
|
} as any;
|
||||||
|
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ interface ProjectSettingsProps {
|
|||||||
industry: TProjectConfigIndustry;
|
industry: TProjectConfigIndustry;
|
||||||
defaultBrandColor: string;
|
defaultBrandColor: string;
|
||||||
organizationTeams: TOrganizationTeam[];
|
organizationTeams: TOrganizationTeam[];
|
||||||
canDoRoleManagement: boolean;
|
isAccessControlAllowed: boolean;
|
||||||
userProjectsCount: number;
|
userProjectsCount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,7 +53,7 @@ export const ProjectSettings = ({
|
|||||||
industry,
|
industry,
|
||||||
defaultBrandColor,
|
defaultBrandColor,
|
||||||
organizationTeams,
|
organizationTeams,
|
||||||
canDoRoleManagement = false,
|
isAccessControlAllowed = false,
|
||||||
userProjectsCount,
|
userProjectsCount,
|
||||||
}: ProjectSettingsProps) => {
|
}: ProjectSettingsProps) => {
|
||||||
const [createTeamModalOpen, setCreateTeamModalOpen] = useState(false);
|
const [createTeamModalOpen, setCreateTeamModalOpen] = useState(false);
|
||||||
@@ -174,7 +174,7 @@ export const ProjectSettings = ({
|
|||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{canDoRoleManagement && userProjectsCount > 0 && (
|
{isAccessControlAllowed && userProjectsCount > 0 && (
|
||||||
<FormField
|
<FormField
|
||||||
control={form.control}
|
control={form.control}
|
||||||
name="teamIds"
|
name="teamIds"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { getTeamsByOrganizationId } from "@/app/(app)/(onboarding)/lib/onboarding";
|
import { getTeamsByOrganizationId } from "@/app/(app)/(onboarding)/lib/onboarding";
|
||||||
import { getUserProjects } from "@/lib/project/service";
|
import { getUserProjects } from "@/lib/project/service";
|
||||||
import { getRoleManagementPermission } from "@/modules/ee/license-check/lib/utils";
|
import { getAccessControlPermission } from "@/modules/ee/license-check/lib/utils";
|
||||||
import { getOrganizationAuth } from "@/modules/organization/lib/utils";
|
import { getOrganizationAuth } from "@/modules/organization/lib/utils";
|
||||||
import "@testing-library/jest-dom/vitest";
|
import "@testing-library/jest-dom/vitest";
|
||||||
import { cleanup, render, screen } from "@testing-library/react";
|
import { cleanup, render, screen } from "@testing-library/react";
|
||||||
@@ -12,7 +12,7 @@ vi.mock("@/lib/constants", () => ({ DEFAULT_BRAND_COLOR: "#fff" }));
|
|||||||
// Mocks before component import
|
// Mocks before component import
|
||||||
vi.mock("@/app/(app)/(onboarding)/lib/onboarding", () => ({ getTeamsByOrganizationId: vi.fn() }));
|
vi.mock("@/app/(app)/(onboarding)/lib/onboarding", () => ({ getTeamsByOrganizationId: vi.fn() }));
|
||||||
vi.mock("@/lib/project/service", () => ({ getUserProjects: vi.fn() }));
|
vi.mock("@/lib/project/service", () => ({ getUserProjects: vi.fn() }));
|
||||||
vi.mock("@/modules/ee/license-check/lib/utils", () => ({ getRoleManagementPermission: vi.fn() }));
|
vi.mock("@/modules/ee/license-check/lib/utils", () => ({ getAccessControlPermission: vi.fn() }));
|
||||||
vi.mock("@/modules/organization/lib/utils", () => ({ getOrganizationAuth: vi.fn() }));
|
vi.mock("@/modules/organization/lib/utils", () => ({ getOrganizationAuth: vi.fn() }));
|
||||||
vi.mock("@/tolgee/server", () => ({ getTranslate: () => Promise.resolve((key: string) => key) }));
|
vi.mock("@/tolgee/server", () => ({ getTranslate: () => Promise.resolve((key: string) => key) }));
|
||||||
vi.mock("next/navigation", () => ({ redirect: vi.fn() }));
|
vi.mock("next/navigation", () => ({ redirect: vi.fn() }));
|
||||||
@@ -61,7 +61,7 @@ describe("ProjectSettingsPage", () => {
|
|||||||
} as any);
|
} as any);
|
||||||
vi.mocked(getUserProjects).mockResolvedValueOnce([] as any);
|
vi.mocked(getUserProjects).mockResolvedValueOnce([] as any);
|
||||||
vi.mocked(getTeamsByOrganizationId).mockResolvedValueOnce(null as any);
|
vi.mocked(getTeamsByOrganizationId).mockResolvedValueOnce(null as any);
|
||||||
vi.mocked(getRoleManagementPermission).mockResolvedValueOnce(false as any);
|
vi.mocked(getAccessControlPermission).mockResolvedValueOnce(false as any);
|
||||||
|
|
||||||
await expect(Page({ params, searchParams })).rejects.toThrow("common.organization_teams_not_found");
|
await expect(Page({ params, searchParams })).rejects.toThrow("common.organization_teams_not_found");
|
||||||
});
|
});
|
||||||
@@ -73,7 +73,7 @@ describe("ProjectSettingsPage", () => {
|
|||||||
} as any);
|
} as any);
|
||||||
vi.mocked(getUserProjects).mockResolvedValueOnce([{ id: "p1" }] as any);
|
vi.mocked(getUserProjects).mockResolvedValueOnce([{ id: "p1" }] as any);
|
||||||
vi.mocked(getTeamsByOrganizationId).mockResolvedValueOnce([{ id: "t1", name: "Team1" }] as any);
|
vi.mocked(getTeamsByOrganizationId).mockResolvedValueOnce([{ id: "t1", name: "Team1" }] as any);
|
||||||
vi.mocked(getRoleManagementPermission).mockResolvedValueOnce(true as any);
|
vi.mocked(getAccessControlPermission).mockResolvedValueOnce(true as any);
|
||||||
|
|
||||||
const element = await Page({ params, searchParams });
|
const element = await Page({ params, searchParams });
|
||||||
render(element as React.ReactElement);
|
render(element as React.ReactElement);
|
||||||
@@ -96,7 +96,7 @@ describe("ProjectSettingsPage", () => {
|
|||||||
} as any);
|
} as any);
|
||||||
vi.mocked(getUserProjects).mockResolvedValueOnce([] as any);
|
vi.mocked(getUserProjects).mockResolvedValueOnce([] as any);
|
||||||
vi.mocked(getTeamsByOrganizationId).mockResolvedValueOnce([{ id: "t1", name: "Team1" }] as any);
|
vi.mocked(getTeamsByOrganizationId).mockResolvedValueOnce([{ id: "t1", name: "Team1" }] as any);
|
||||||
vi.mocked(getRoleManagementPermission).mockResolvedValueOnce(true as any);
|
vi.mocked(getAccessControlPermission).mockResolvedValueOnce(true as any);
|
||||||
|
|
||||||
const element = await Page({ params, searchParams });
|
const element = await Page({ params, searchParams });
|
||||||
render(element as React.ReactElement);
|
render(element as React.ReactElement);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { getTeamsByOrganizationId } from "@/app/(app)/(onboarding)/lib/onboardin
|
|||||||
import { ProjectSettings } from "@/app/(app)/(onboarding)/organizations/[organizationId]/projects/new/settings/components/ProjectSettings";
|
import { ProjectSettings } from "@/app/(app)/(onboarding)/organizations/[organizationId]/projects/new/settings/components/ProjectSettings";
|
||||||
import { DEFAULT_BRAND_COLOR } from "@/lib/constants";
|
import { DEFAULT_BRAND_COLOR } from "@/lib/constants";
|
||||||
import { getUserProjects } from "@/lib/project/service";
|
import { getUserProjects } from "@/lib/project/service";
|
||||||
import { getRoleManagementPermission } from "@/modules/ee/license-check/lib/utils";
|
import { getAccessControlPermission } from "@/modules/ee/license-check/lib/utils";
|
||||||
import { getOrganizationAuth } from "@/modules/organization/lib/utils";
|
import { getOrganizationAuth } from "@/modules/organization/lib/utils";
|
||||||
import { Button } from "@/modules/ui/components/button";
|
import { Button } from "@/modules/ui/components/button";
|
||||||
import { Header } from "@/modules/ui/components/header";
|
import { Header } from "@/modules/ui/components/header";
|
||||||
@@ -41,7 +41,7 @@ const Page = async (props: ProjectSettingsPageProps) => {
|
|||||||
|
|
||||||
const organizationTeams = await getTeamsByOrganizationId(params.organizationId);
|
const organizationTeams = await getTeamsByOrganizationId(params.organizationId);
|
||||||
|
|
||||||
const canDoRoleManagement = await getRoleManagementPermission(organization.billing.plan);
|
const isAccessControlAllowed = await getAccessControlPermission(organization.billing.plan);
|
||||||
|
|
||||||
if (!organizationTeams) {
|
if (!organizationTeams) {
|
||||||
throw new Error(t("common.organization_teams_not_found"));
|
throw new Error(t("common.organization_teams_not_found"));
|
||||||
@@ -60,7 +60,7 @@ const Page = async (props: ProjectSettingsPageProps) => {
|
|||||||
industry={industry}
|
industry={industry}
|
||||||
defaultBrandColor={DEFAULT_BRAND_COLOR}
|
defaultBrandColor={DEFAULT_BRAND_COLOR}
|
||||||
organizationTeams={organizationTeams}
|
organizationTeams={organizationTeams}
|
||||||
canDoRoleManagement={canDoRoleManagement}
|
isAccessControlAllowed={isAccessControlAllowed}
|
||||||
userProjectsCount={projects.length}
|
userProjectsCount={projects.length}
|
||||||
/>
|
/>
|
||||||
{projects.length >= 1 && (
|
{projects.length >= 1 && (
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ import { checkAuthorizationUpdated } from "@/lib/utils/action-client/action-clie
|
|||||||
import { AuthenticatedActionClientCtx } from "@/lib/utils/action-client/types/context";
|
import { AuthenticatedActionClientCtx } from "@/lib/utils/action-client/types/context";
|
||||||
import { withAuditLogging } from "@/modules/ee/audit-logs/lib/handler";
|
import { withAuditLogging } from "@/modules/ee/audit-logs/lib/handler";
|
||||||
import {
|
import {
|
||||||
|
getAccessControlPermission,
|
||||||
getOrganizationProjectsLimit,
|
getOrganizationProjectsLimit,
|
||||||
getRoleManagementPermission,
|
|
||||||
} from "@/modules/ee/license-check/lib/utils";
|
} from "@/modules/ee/license-check/lib/utils";
|
||||||
import { createProject } from "@/modules/projects/settings/lib/project";
|
import { createProject } from "@/modules/projects/settings/lib/project";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
@@ -58,9 +58,9 @@ export const createProjectAction = authenticatedActionClient.schema(ZCreateProje
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (parsedInput.data.teamIds && parsedInput.data.teamIds.length > 0) {
|
if (parsedInput.data.teamIds && parsedInput.data.teamIds.length > 0) {
|
||||||
const canDoRoleManagement = await getRoleManagementPermission(organization.billing.plan);
|
const isAccessControlAllowed = await getAccessControlPermission(organization.billing.plan);
|
||||||
|
|
||||||
if (!canDoRoleManagement) {
|
if (!isAccessControlAllowed) {
|
||||||
throw new OperationNotAllowedError("You do not have permission to manage roles");
|
throw new OperationNotAllowedError("You do not have permission to manage roles");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -71,10 +71,6 @@ export const createProjectAction = authenticatedActionClient.schema(ZCreateProje
|
|||||||
alert: {
|
alert: {
|
||||||
...user.notificationSettings?.alert,
|
...user.notificationSettings?.alert,
|
||||||
},
|
},
|
||||||
weeklySummary: {
|
|
||||||
...user.notificationSettings?.weeklySummary,
|
|
||||||
[project.id]: true,
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
await updateUser(user.id, {
|
await updateUser(user.id, {
|
||||||
|
|||||||
@@ -24,14 +24,17 @@ export const ActionClassesTable = ({
|
|||||||
otherEnvActionClasses,
|
otherEnvActionClasses,
|
||||||
otherEnvironment,
|
otherEnvironment,
|
||||||
}: ActionClassesTableProps) => {
|
}: ActionClassesTableProps) => {
|
||||||
const [isActionDetailModalOpen, setActionDetailModalOpen] = useState(false);
|
const [isActionDetailModalOpen, setIsActionDetailModalOpen] = useState(false);
|
||||||
|
|
||||||
const [activeActionClass, setActiveActionClass] = useState<TActionClass>();
|
const [activeActionClass, setActiveActionClass] = useState<TActionClass>();
|
||||||
|
|
||||||
const handleOpenActionDetailModalClick = (e, actionClass: TActionClass) => {
|
const handleOpenActionDetailModalClick = (
|
||||||
|
e: React.MouseEvent<HTMLButtonElement>,
|
||||||
|
actionClass: TActionClass
|
||||||
|
) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setActiveActionClass(actionClass);
|
setActiveActionClass(actionClass);
|
||||||
setActionDetailModalOpen(true);
|
setIsActionDetailModalOpen(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -42,7 +45,7 @@ export const ActionClassesTable = ({
|
|||||||
{actionClasses.length > 0 ? (
|
{actionClasses.length > 0 ? (
|
||||||
actionClasses.map((actionClass, index) => (
|
actionClasses.map((actionClass, index) => (
|
||||||
<button
|
<button
|
||||||
onClick={(e) => {
|
onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
|
||||||
handleOpenActionDetailModalClick(e, actionClass);
|
handleOpenActionDetailModalClick(e, actionClass);
|
||||||
}}
|
}}
|
||||||
className="w-full"
|
className="w-full"
|
||||||
@@ -63,7 +66,7 @@ export const ActionClassesTable = ({
|
|||||||
environmentId={environmentId}
|
environmentId={environmentId}
|
||||||
environment={environment}
|
environment={environment}
|
||||||
open={isActionDetailModalOpen}
|
open={isActionDetailModalOpen}
|
||||||
setOpen={setActionDetailModalOpen}
|
setOpen={setIsActionDetailModalOpen}
|
||||||
actionClasses={actionClasses}
|
actionClasses={actionClasses}
|
||||||
actionClass={activeActionClass}
|
actionClass={activeActionClass}
|
||||||
isReadOnly={isReadOnly}
|
isReadOnly={isReadOnly}
|
||||||
|
|||||||
@@ -70,15 +70,13 @@ export const ActionDetailModal = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<ModalWithTabs
|
||||||
<ModalWithTabs
|
open={open}
|
||||||
open={open}
|
setOpen={setOpen}
|
||||||
setOpen={setOpen}
|
tabs={tabs}
|
||||||
tabs={tabs}
|
icon={ACTION_TYPE_ICON_LOOKUP[actionClass.type]}
|
||||||
icon={ACTION_TYPE_ICON_LOOKUP[actionClass.type]}
|
label={actionClass.name}
|
||||||
label={actionClass.name}
|
description={typeDescription()}
|
||||||
description={typeDescription()}
|
/>
|
||||||
/>
|
|
||||||
</>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -11,6 +11,21 @@ vi.mock("@/app/(app)/environments/[environmentId]/actions/actions", () => ({
|
|||||||
updateActionClassAction: vi.fn(),
|
updateActionClassAction: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// Mock action utils
|
||||||
|
vi.mock("@/modules/survey/editor/lib/action-utils", () => ({
|
||||||
|
useActionClassKeys: vi.fn(() => ["existing-key"]),
|
||||||
|
createActionClassZodResolver: vi.fn(() => vi.fn()),
|
||||||
|
validatePermissions: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mock action builder
|
||||||
|
vi.mock("@/modules/survey/editor/lib/action-builder", () => ({
|
||||||
|
buildActionObject: vi.fn((data, environmentId, t) => ({
|
||||||
|
...data,
|
||||||
|
environmentId,
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
|
||||||
// Mock utils
|
// Mock utils
|
||||||
vi.mock("@/app/lib/actionClass/actionClass", () => ({
|
vi.mock("@/app/lib/actionClass/actionClass", () => ({
|
||||||
isValidCssSelector: vi.fn((selector) => selector !== "invalid-selector"),
|
isValidCssSelector: vi.fn((selector) => selector !== "invalid-selector"),
|
||||||
@@ -24,6 +39,7 @@ vi.mock("@/modules/ui/components/button", () => ({
|
|||||||
</button>
|
</button>
|
||||||
),
|
),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("@/modules/ui/components/code-action-form", () => ({
|
vi.mock("@/modules/ui/components/code-action-form", () => ({
|
||||||
CodeActionForm: ({ isReadOnly }: { isReadOnly: boolean }) => (
|
CodeActionForm: ({ isReadOnly }: { isReadOnly: boolean }) => (
|
||||||
<div data-testid="code-action-form" data-readonly={isReadOnly}>
|
<div data-testid="code-action-form" data-readonly={isReadOnly}>
|
||||||
@@ -31,6 +47,7 @@ vi.mock("@/modules/ui/components/code-action-form", () => ({
|
|||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("@/modules/ui/components/delete-dialog", () => ({
|
vi.mock("@/modules/ui/components/delete-dialog", () => ({
|
||||||
DeleteDialog: ({ open, setOpen, isDeleting, onDelete }: any) =>
|
DeleteDialog: ({ open, setOpen, isDeleting, onDelete }: any) =>
|
||||||
open ? (
|
open ? (
|
||||||
@@ -43,6 +60,26 @@ vi.mock("@/modules/ui/components/delete-dialog", () => ({
|
|||||||
</div>
|
</div>
|
||||||
) : null,
|
) : null,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/modules/ui/components/action-name-description-fields", () => ({
|
||||||
|
ActionNameDescriptionFields: ({ isReadOnly, nameInputId, descriptionInputId }: any) => (
|
||||||
|
<div data-testid="action-name-description-fields">
|
||||||
|
<input
|
||||||
|
data-testid={`name-input-${nameInputId}`}
|
||||||
|
placeholder="environments.actions.eg_clicked_download"
|
||||||
|
disabled={isReadOnly}
|
||||||
|
defaultValue="Test Action"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
data-testid={`description-input-${descriptionInputId}`}
|
||||||
|
placeholder="environments.actions.user_clicked_download_button"
|
||||||
|
disabled={isReadOnly}
|
||||||
|
defaultValue="Test Description"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
vi.mock("@/modules/ui/components/no-code-action-form", () => ({
|
vi.mock("@/modules/ui/components/no-code-action-form", () => ({
|
||||||
NoCodeActionForm: ({ isReadOnly }: { isReadOnly: boolean }) => (
|
NoCodeActionForm: ({ isReadOnly }: { isReadOnly: boolean }) => (
|
||||||
<div data-testid="no-code-action-form" data-readonly={isReadOnly}>
|
<div data-testid="no-code-action-form" data-readonly={isReadOnly}>
|
||||||
@@ -56,6 +93,23 @@ vi.mock("lucide-react", () => ({
|
|||||||
TrashIcon: () => <div data-testid="trash-icon">Trash</div>,
|
TrashIcon: () => <div data-testid="trash-icon">Trash</div>,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// Mock react-hook-form
|
||||||
|
const mockHandleSubmit = vi.fn();
|
||||||
|
const mockForm = {
|
||||||
|
handleSubmit: mockHandleSubmit,
|
||||||
|
control: {},
|
||||||
|
formState: { errors: {} },
|
||||||
|
};
|
||||||
|
|
||||||
|
vi.mock("react-hook-form", async () => {
|
||||||
|
const actual = await vi.importActual("react-hook-form");
|
||||||
|
return {
|
||||||
|
...actual,
|
||||||
|
useForm: vi.fn(() => mockForm),
|
||||||
|
FormProvider: ({ children }: any) => <div>{children}</div>,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
const mockSetOpen = vi.fn();
|
const mockSetOpen = vi.fn();
|
||||||
const mockActionClasses: TActionClass[] = [
|
const mockActionClasses: TActionClass[] = [
|
||||||
{
|
{
|
||||||
@@ -88,6 +142,7 @@ const createMockActionClass = (id: string, type: TActionClassType, name: string)
|
|||||||
describe("ActionSettingsTab", () => {
|
describe("ActionSettingsTab", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
|
mockHandleSubmit.mockImplementation((fn) => fn);
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -105,13 +160,9 @@ describe("ActionSettingsTab", () => {
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
// Use getByPlaceholderText or getByLabelText now that Input isn't mocked
|
expect(screen.getByTestId("action-name-description-fields")).toBeInTheDocument();
|
||||||
expect(screen.getByPlaceholderText("environments.actions.eg_clicked_download")).toHaveValue(
|
expect(screen.getByTestId("name-input-actionNameSettingsInput")).toBeInTheDocument();
|
||||||
actionClass.name
|
expect(screen.getByTestId("description-input-actionDescriptionSettingsInput")).toBeInTheDocument();
|
||||||
);
|
|
||||||
expect(screen.getByPlaceholderText("environments.actions.user_clicked_download_button")).toHaveValue(
|
|
||||||
actionClass.description
|
|
||||||
);
|
|
||||||
expect(screen.getByTestId("code-action-form")).toBeInTheDocument();
|
expect(screen.getByTestId("code-action-form")).toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
screen.getByText("environments.actions.this_is_a_code_action_please_make_changes_in_your_code_base")
|
screen.getByText("environments.actions.this_is_a_code_action_please_make_changes_in_your_code_base")
|
||||||
@@ -131,18 +182,104 @@ describe("ActionSettingsTab", () => {
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
// Use getByPlaceholderText or getByLabelText now that Input isn't mocked
|
expect(screen.getByTestId("action-name-description-fields")).toBeInTheDocument();
|
||||||
expect(screen.getByPlaceholderText("environments.actions.eg_clicked_download")).toHaveValue(
|
|
||||||
actionClass.name
|
|
||||||
);
|
|
||||||
expect(screen.getByPlaceholderText("environments.actions.user_clicked_download_button")).toHaveValue(
|
|
||||||
actionClass.description
|
|
||||||
);
|
|
||||||
expect(screen.getByTestId("no-code-action-form")).toBeInTheDocument();
|
expect(screen.getByTestId("no-code-action-form")).toBeInTheDocument();
|
||||||
expect(screen.getByRole("button", { name: "common.save_changes" })).toBeInTheDocument();
|
expect(screen.getByRole("button", { name: "common.save_changes" })).toBeInTheDocument();
|
||||||
expect(screen.getByRole("button", { name: /common.delete/ })).toBeInTheDocument();
|
expect(screen.getByRole("button", { name: /common.delete/ })).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("renders correctly for other action types (fallback)", () => {
|
||||||
|
const actionClass = {
|
||||||
|
...createMockActionClass("auto1", "noCode", "Auto Action"),
|
||||||
|
type: "automatic" as any,
|
||||||
|
};
|
||||||
|
render(
|
||||||
|
<ActionSettingsTab
|
||||||
|
actionClass={actionClass}
|
||||||
|
actionClasses={mockActionClasses}
|
||||||
|
setOpen={mockSetOpen}
|
||||||
|
isReadOnly={false}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByTestId("action-name-description-fields")).toBeInTheDocument();
|
||||||
|
expect(
|
||||||
|
screen.getByText(
|
||||||
|
"environments.actions.this_action_was_created_automatically_you_cannot_make_changes_to_it"
|
||||||
|
)
|
||||||
|
).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("calls utility functions on initialization", async () => {
|
||||||
|
const actionUtilsMock = await import("@/modules/survey/editor/lib/action-utils");
|
||||||
|
|
||||||
|
const actionClass = createMockActionClass("noCode1", "noCode", "No Code Action");
|
||||||
|
render(
|
||||||
|
<ActionSettingsTab
|
||||||
|
actionClass={actionClass}
|
||||||
|
actionClasses={mockActionClasses}
|
||||||
|
setOpen={mockSetOpen}
|
||||||
|
isReadOnly={false}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(actionUtilsMock.useActionClassKeys).toHaveBeenCalledWith(mockActionClasses);
|
||||||
|
expect(actionUtilsMock.createActionClassZodResolver).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("handles successful form submission", async () => {
|
||||||
|
const { updateActionClassAction } = await import(
|
||||||
|
"@/app/(app)/environments/[environmentId]/actions/actions"
|
||||||
|
);
|
||||||
|
const actionUtilsMock = await import("@/modules/survey/editor/lib/action-utils");
|
||||||
|
|
||||||
|
vi.mocked(updateActionClassAction).mockResolvedValue({ data: {} } as any);
|
||||||
|
|
||||||
|
const actionClass = createMockActionClass("noCode1", "noCode", "No Code Action");
|
||||||
|
render(
|
||||||
|
<ActionSettingsTab
|
||||||
|
actionClass={actionClass}
|
||||||
|
actionClasses={mockActionClasses}
|
||||||
|
setOpen={mockSetOpen}
|
||||||
|
isReadOnly={false}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
// Check that utility functions were called during component initialization
|
||||||
|
expect(actionUtilsMock.useActionClassKeys).toHaveBeenCalledWith(mockActionClasses);
|
||||||
|
expect(actionUtilsMock.createActionClassZodResolver).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("handles permission validation error", async () => {
|
||||||
|
const actionUtilsMock = await import("@/modules/survey/editor/lib/action-utils");
|
||||||
|
vi.mocked(actionUtilsMock.validatePermissions).mockImplementation(() => {
|
||||||
|
throw new Error("Not authorized");
|
||||||
|
});
|
||||||
|
|
||||||
|
const actionClass = createMockActionClass("noCode1", "noCode", "No Code Action");
|
||||||
|
render(
|
||||||
|
<ActionSettingsTab
|
||||||
|
actionClass={actionClass}
|
||||||
|
actionClasses={mockActionClasses}
|
||||||
|
setOpen={mockSetOpen}
|
||||||
|
isReadOnly={false}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
const submitButton = screen.getByRole("button", { name: "common.save_changes" });
|
||||||
|
|
||||||
|
mockHandleSubmit.mockImplementation((fn) => (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
return fn({ name: "Test", type: "noCode" });
|
||||||
|
});
|
||||||
|
|
||||||
|
await userEvent.click(submitButton);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(toast.error).toHaveBeenCalledWith("Not authorized");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
test("handles successful deletion", async () => {
|
test("handles successful deletion", async () => {
|
||||||
const actionClass = createMockActionClass("noCode1", "noCode", "No Code Action");
|
const actionClass = createMockActionClass("noCode1", "noCode", "No Code Action");
|
||||||
const { deleteActionClassAction } = await import(
|
const { deleteActionClassAction } = await import(
|
||||||
@@ -209,17 +346,16 @@ describe("ActionSettingsTab", () => {
|
|||||||
actionClass={actionClass}
|
actionClass={actionClass}
|
||||||
actionClasses={mockActionClasses}
|
actionClasses={mockActionClasses}
|
||||||
setOpen={mockSetOpen}
|
setOpen={mockSetOpen}
|
||||||
isReadOnly={true} // Set to read-only
|
isReadOnly={true}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
// Use getByPlaceholderText or getByLabelText now that Input isn't mocked
|
expect(screen.getByTestId("name-input-actionNameSettingsInput")).toBeDisabled();
|
||||||
expect(screen.getByPlaceholderText("environments.actions.eg_clicked_download")).toBeDisabled();
|
expect(screen.getByTestId("description-input-actionDescriptionSettingsInput")).toBeDisabled();
|
||||||
expect(screen.getByPlaceholderText("environments.actions.user_clicked_download_button")).toBeDisabled();
|
|
||||||
expect(screen.getByTestId("no-code-action-form")).toHaveAttribute("data-readonly", "true");
|
expect(screen.getByTestId("no-code-action-form")).toHaveAttribute("data-readonly", "true");
|
||||||
expect(screen.queryByRole("button", { name: "common.save_changes" })).not.toBeInTheDocument();
|
expect(screen.queryByRole("button", { name: "common.save_changes" })).not.toBeInTheDocument();
|
||||||
expect(screen.queryByRole("button", { name: /common.delete/ })).not.toBeInTheDocument();
|
expect(screen.queryByRole("button", { name: /common.delete/ })).not.toBeInTheDocument();
|
||||||
expect(screen.getByRole("link", { name: "common.read_docs" })).toBeInTheDocument(); // Docs link still visible
|
expect(screen.getByRole("link", { name: "common.read_docs" })).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("prevents delete when read-only", async () => {
|
test("prevents delete when read-only", async () => {
|
||||||
@@ -228,7 +364,6 @@ describe("ActionSettingsTab", () => {
|
|||||||
"@/app/(app)/environments/[environmentId]/actions/actions"
|
"@/app/(app)/environments/[environmentId]/actions/actions"
|
||||||
);
|
);
|
||||||
|
|
||||||
// Render with isReadOnly=true, but simulate a delete attempt
|
|
||||||
render(
|
render(
|
||||||
<ActionSettingsTab
|
<ActionSettingsTab
|
||||||
actionClass={actionClass}
|
actionClass={actionClass}
|
||||||
@@ -238,12 +373,6 @@ describe("ActionSettingsTab", () => {
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
// Try to open and confirm delete dialog (buttons won't exist, so we simulate the flow)
|
|
||||||
// This test primarily checks the logic within handleDeleteAction if it were called.
|
|
||||||
// A better approach might be to export handleDeleteAction for direct testing,
|
|
||||||
// but for now, we assume the UI prevents calling it.
|
|
||||||
|
|
||||||
// We can assert that the delete button isn't there to prevent the flow
|
|
||||||
expect(screen.queryByRole("button", { name: /common.delete/ })).not.toBeInTheDocument();
|
expect(screen.queryByRole("button", { name: /common.delete/ })).not.toBeInTheDocument();
|
||||||
expect(deleteActionClassAction).not.toHaveBeenCalled();
|
expect(deleteActionClassAction).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
@@ -262,4 +391,19 @@ describe("ActionSettingsTab", () => {
|
|||||||
expect(docsLink).toHaveAttribute("href", "https://formbricks.com/docs/actions/no-code");
|
expect(docsLink).toHaveAttribute("href", "https://formbricks.com/docs/actions/no-code");
|
||||||
expect(docsLink).toHaveAttribute("target", "_blank");
|
expect(docsLink).toHaveAttribute("target", "_blank");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("uses correct input IDs for ActionNameDescriptionFields", () => {
|
||||||
|
const actionClass = createMockActionClass("noCode1", "noCode", "No Code Action");
|
||||||
|
render(
|
||||||
|
<ActionSettingsTab
|
||||||
|
actionClass={actionClass}
|
||||||
|
actionClasses={mockActionClasses}
|
||||||
|
setOpen={mockSetOpen}
|
||||||
|
isReadOnly={false}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByTestId("name-input-actionNameSettingsInput")).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId("description-input-actionDescriptionSettingsInput")).toBeInTheDocument();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -4,14 +4,17 @@ import {
|
|||||||
deleteActionClassAction,
|
deleteActionClassAction,
|
||||||
updateActionClassAction,
|
updateActionClassAction,
|
||||||
} from "@/app/(app)/environments/[environmentId]/actions/actions";
|
} from "@/app/(app)/environments/[environmentId]/actions/actions";
|
||||||
import { isValidCssSelector } from "@/app/lib/actionClass/actionClass";
|
import { buildActionObject } from "@/modules/survey/editor/lib/action-builder";
|
||||||
|
import {
|
||||||
|
createActionClassZodResolver,
|
||||||
|
useActionClassKeys,
|
||||||
|
validatePermissions,
|
||||||
|
} from "@/modules/survey/editor/lib/action-utils";
|
||||||
|
import { ActionNameDescriptionFields } from "@/modules/ui/components/action-name-description-fields";
|
||||||
import { Button } from "@/modules/ui/components/button";
|
import { Button } from "@/modules/ui/components/button";
|
||||||
import { CodeActionForm } from "@/modules/ui/components/code-action-form";
|
import { CodeActionForm } from "@/modules/ui/components/code-action-form";
|
||||||
import { DeleteDialog } from "@/modules/ui/components/delete-dialog";
|
import { DeleteDialog } from "@/modules/ui/components/delete-dialog";
|
||||||
import { FormControl, FormError, FormField, FormItem, FormLabel } from "@/modules/ui/components/form";
|
|
||||||
import { Input } from "@/modules/ui/components/input";
|
|
||||||
import { NoCodeActionForm } from "@/modules/ui/components/no-code-action-form";
|
import { NoCodeActionForm } from "@/modules/ui/components/no-code-action-form";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
|
||||||
import { useTranslate } from "@tolgee/react";
|
import { useTranslate } from "@tolgee/react";
|
||||||
import { TrashIcon } from "lucide-react";
|
import { TrashIcon } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
@@ -19,8 +22,7 @@ import { useRouter } from "next/navigation";
|
|||||||
import { useMemo, useState } from "react";
|
import { useMemo, useState } from "react";
|
||||||
import { FormProvider, useForm } from "react-hook-form";
|
import { FormProvider, useForm } from "react-hook-form";
|
||||||
import { toast } from "react-hot-toast";
|
import { toast } from "react-hot-toast";
|
||||||
import { z } from "zod";
|
import { TActionClass, TActionClassInput } from "@formbricks/types/action-classes";
|
||||||
import { TActionClass, TActionClassInput, ZActionClassInput } from "@formbricks/types/action-classes";
|
|
||||||
|
|
||||||
interface ActionSettingsTabProps {
|
interface ActionSettingsTabProps {
|
||||||
actionClass: TActionClass;
|
actionClass: TActionClass;
|
||||||
@@ -48,63 +50,51 @@ export const ActionSettingsTab = ({
|
|||||||
[actionClass.id, actionClasses]
|
[actionClass.id, actionClasses]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const actionClassKeys = useActionClassKeys(actionClasses);
|
||||||
|
|
||||||
const form = useForm<TActionClassInput>({
|
const form = useForm<TActionClassInput>({
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
...restActionClass,
|
...restActionClass,
|
||||||
},
|
},
|
||||||
resolver: zodResolver(
|
resolver: createActionClassZodResolver(actionClassNames, actionClassKeys, t),
|
||||||
ZActionClassInput.superRefine((data, ctx) => {
|
|
||||||
if (data.name && actionClassNames.includes(data.name)) {
|
|
||||||
ctx.addIssue({
|
|
||||||
code: z.ZodIssueCode.custom,
|
|
||||||
path: ["name"],
|
|
||||||
message: t("environments.actions.action_with_name_already_exists", { name: data.name }),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
})
|
|
||||||
),
|
|
||||||
|
|
||||||
mode: "onChange",
|
mode: "onChange",
|
||||||
});
|
});
|
||||||
|
|
||||||
const { handleSubmit, control } = form;
|
const { handleSubmit, control } = form;
|
||||||
|
|
||||||
|
const renderActionForm = () => {
|
||||||
|
if (actionClass.type === "code") {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<CodeActionForm form={form} isReadOnly={true} />
|
||||||
|
<p className="text-sm text-slate-600">
|
||||||
|
{t("environments.actions.this_is_a_code_action_please_make_changes_in_your_code_base")}
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (actionClass.type === "noCode") {
|
||||||
|
return <NoCodeActionForm form={form} isReadOnly={isReadOnly} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<p className="text-sm text-slate-600">
|
||||||
|
{t("environments.actions.this_action_was_created_automatically_you_cannot_make_changes_to_it")}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
const onSubmit = async (data: TActionClassInput) => {
|
const onSubmit = async (data: TActionClassInput) => {
|
||||||
try {
|
try {
|
||||||
if (isReadOnly) {
|
|
||||||
throw new Error(t("common.you_are_not_authorised_to_perform_this_action"));
|
|
||||||
}
|
|
||||||
setIsUpdatingAction(true);
|
setIsUpdatingAction(true);
|
||||||
|
validatePermissions(isReadOnly, t);
|
||||||
|
const updatedAction = buildActionObject(data, actionClass.environmentId, t);
|
||||||
|
|
||||||
if (data.name && actionClassNames.includes(data.name)) {
|
|
||||||
throw new Error(t("environments.actions.action_with_name_already_exists", { name: data.name }));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
data.type === "noCode" &&
|
|
||||||
data.noCodeConfig?.type === "click" &&
|
|
||||||
data.noCodeConfig.elementSelector.cssSelector &&
|
|
||||||
!isValidCssSelector(data.noCodeConfig.elementSelector.cssSelector)
|
|
||||||
) {
|
|
||||||
throw new Error(t("environments.actions.invalid_css_selector"));
|
|
||||||
}
|
|
||||||
|
|
||||||
const updatedData: TActionClassInput = {
|
|
||||||
...data,
|
|
||||||
...(data.type === "noCode" &&
|
|
||||||
data.noCodeConfig?.type === "click" && {
|
|
||||||
noCodeConfig: {
|
|
||||||
...data.noCodeConfig,
|
|
||||||
elementSelector: {
|
|
||||||
cssSelector: data.noCodeConfig.elementSelector.cssSelector,
|
|
||||||
innerHtml: data.noCodeConfig.elementSelector.innerHtml,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
await updateActionClassAction({
|
await updateActionClassAction({
|
||||||
actionClassId: actionClass.id,
|
actionClassId: actionClass.id,
|
||||||
updatedAction: updatedData,
|
updatedAction: updatedAction,
|
||||||
});
|
});
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
router.refresh();
|
router.refresh();
|
||||||
@@ -123,7 +113,7 @@ export const ActionSettingsTab = ({
|
|||||||
router.refresh();
|
router.refresh();
|
||||||
toast.success(t("environments.actions.action_deleted_successfully"));
|
toast.success(t("environments.actions.action_deleted_successfully"));
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
} catch (error) {
|
} catch {
|
||||||
toast.error(t("common.something_went_wrong_please_try_again"));
|
toast.error(t("common.something_went_wrong_please_try_again"));
|
||||||
} finally {
|
} finally {
|
||||||
setIsDeletingAction(false);
|
setIsDeletingAction(false);
|
||||||
@@ -135,79 +125,14 @@ export const ActionSettingsTab = ({
|
|||||||
<FormProvider {...form}>
|
<FormProvider {...form}>
|
||||||
<form onSubmit={handleSubmit(onSubmit)}>
|
<form onSubmit={handleSubmit(onSubmit)}>
|
||||||
<div className="max-h-[400px] w-full space-y-4 overflow-y-auto">
|
<div className="max-h-[400px] w-full space-y-4 overflow-y-auto">
|
||||||
<div className="grid w-full grid-cols-2 gap-x-4">
|
<ActionNameDescriptionFields
|
||||||
<div className="col-span-1">
|
control={control}
|
||||||
<FormField
|
isReadOnly={isReadOnly}
|
||||||
control={control}
|
nameInputId="actionNameSettingsInput"
|
||||||
name="name"
|
descriptionInputId="actionDescriptionSettingsInput"
|
||||||
disabled={isReadOnly}
|
/>
|
||||||
render={({ field, fieldState: { error } }) => (
|
|
||||||
<FormItem>
|
|
||||||
<FormLabel htmlFor="actionNameSettingsInput">
|
|
||||||
{actionClass.type === "noCode"
|
|
||||||
? t("environments.actions.what_did_your_user_do")
|
|
||||||
: t("environments.actions.display_name")}
|
|
||||||
</FormLabel>
|
|
||||||
|
|
||||||
<FormControl>
|
{renderActionForm()}
|
||||||
<Input
|
|
||||||
type="text"
|
|
||||||
id="actionNameSettingsInput"
|
|
||||||
{...field}
|
|
||||||
placeholder={t("environments.actions.eg_clicked_download")}
|
|
||||||
isInvalid={!!error?.message}
|
|
||||||
disabled={isReadOnly}
|
|
||||||
/>
|
|
||||||
</FormControl>
|
|
||||||
|
|
||||||
<FormError />
|
|
||||||
</FormItem>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="col-span-1">
|
|
||||||
<FormField
|
|
||||||
control={control}
|
|
||||||
name="description"
|
|
||||||
render={({ field }) => (
|
|
||||||
<FormItem>
|
|
||||||
<FormLabel htmlFor="actionDescriptionSettingsInput">
|
|
||||||
{t("common.description")}
|
|
||||||
</FormLabel>
|
|
||||||
|
|
||||||
<FormControl>
|
|
||||||
<Input
|
|
||||||
type="text"
|
|
||||||
id="actionDescriptionSettingsInput"
|
|
||||||
{...field}
|
|
||||||
placeholder={t("environments.actions.user_clicked_download_button")}
|
|
||||||
value={field.value ?? ""}
|
|
||||||
disabled={isReadOnly}
|
|
||||||
/>
|
|
||||||
</FormControl>
|
|
||||||
</FormItem>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{actionClass.type === "code" ? (
|
|
||||||
<>
|
|
||||||
<CodeActionForm form={form} isReadOnly={true} />
|
|
||||||
<p className="text-sm text-slate-600">
|
|
||||||
{t("environments.actions.this_is_a_code_action_please_make_changes_in_your_code_base")}
|
|
||||||
</p>
|
|
||||||
</>
|
|
||||||
) : actionClass.type === "noCode" ? (
|
|
||||||
<NoCodeActionForm form={form} isReadOnly={isReadOnly} />
|
|
||||||
) : (
|
|
||||||
<p className="text-sm text-slate-600">
|
|
||||||
{t(
|
|
||||||
"environments.actions.this_action_was_created_automatically_you_cannot_make_changes_to_it"
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex justify-between gap-x-2 border-slate-200 pt-4">
|
<div className="flex justify-between gap-x-2 border-slate-200 pt-4">
|
||||||
|
|||||||
@@ -9,8 +9,12 @@ import {
|
|||||||
} from "@/lib/organization/service";
|
} from "@/lib/organization/service";
|
||||||
import { getUserProjects } from "@/lib/project/service";
|
import { getUserProjects } from "@/lib/project/service";
|
||||||
import { getUser } from "@/lib/user/service";
|
import { getUser } from "@/lib/user/service";
|
||||||
import { getOrganizationProjectsLimit } from "@/modules/ee/license-check/lib/utils";
|
import {
|
||||||
|
getAccessControlPermission,
|
||||||
|
getOrganizationProjectsLimit,
|
||||||
|
} from "@/modules/ee/license-check/lib/utils";
|
||||||
import { getProjectPermissionByUserId } from "@/modules/ee/teams/lib/roles";
|
import { getProjectPermissionByUserId } from "@/modules/ee/teams/lib/roles";
|
||||||
|
import { getTeamsByOrganizationId } from "@/modules/ee/teams/team-list/lib/team";
|
||||||
import { cleanup, render, screen } from "@testing-library/react";
|
import { cleanup, render, screen } from "@testing-library/react";
|
||||||
import type { Session } from "next-auth";
|
import type { Session } from "next-auth";
|
||||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||||
@@ -49,10 +53,14 @@ vi.mock("@/lib/membership/utils", () => ({
|
|||||||
}));
|
}));
|
||||||
vi.mock("@/modules/ee/license-check/lib/utils", () => ({
|
vi.mock("@/modules/ee/license-check/lib/utils", () => ({
|
||||||
getOrganizationProjectsLimit: vi.fn(),
|
getOrganizationProjectsLimit: vi.fn(),
|
||||||
|
getAccessControlPermission: vi.fn(),
|
||||||
}));
|
}));
|
||||||
vi.mock("@/modules/ee/teams/lib/roles", () => ({
|
vi.mock("@/modules/ee/teams/lib/roles", () => ({
|
||||||
getProjectPermissionByUserId: vi.fn(),
|
getProjectPermissionByUserId: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
vi.mock("@/modules/ee/teams/team-list/lib/team", () => ({
|
||||||
|
getTeamsByOrganizationId: vi.fn(),
|
||||||
|
}));
|
||||||
vi.mock("@/tolgee/server", () => ({
|
vi.mock("@/tolgee/server", () => ({
|
||||||
getTranslate: async () => (key: string) => key,
|
getTranslate: async () => (key: string) => key,
|
||||||
}));
|
}));
|
||||||
@@ -71,7 +79,13 @@ vi.mock("@/lib/constants", () => ({
|
|||||||
|
|
||||||
// Mock components
|
// Mock components
|
||||||
vi.mock("@/app/(app)/environments/[environmentId]/components/MainNavigation", () => ({
|
vi.mock("@/app/(app)/environments/[environmentId]/components/MainNavigation", () => ({
|
||||||
MainNavigation: () => <div data-testid="main-navigation">MainNavigation</div>,
|
MainNavigation: ({ organizationTeams, isAccessControlAllowed }: any) => (
|
||||||
|
<div data-testid="main-navigation">
|
||||||
|
MainNavigation
|
||||||
|
<div data-testid="organization-teams">{JSON.stringify(organizationTeams || [])}</div>
|
||||||
|
<div data-testid="is-access-control-allowed">{isAccessControlAllowed?.toString() || "false"}</div>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
}));
|
}));
|
||||||
vi.mock("@/app/(app)/environments/[environmentId]/components/TopControlBar", () => ({
|
vi.mock("@/app/(app)/environments/[environmentId]/components/TopControlBar", () => ({
|
||||||
TopControlBar: () => <div data-testid="top-control-bar">TopControlBar</div>,
|
TopControlBar: () => <div data-testid="top-control-bar">TopControlBar</div>,
|
||||||
@@ -104,7 +118,7 @@ const mockUser = {
|
|||||||
identityProvider: "email",
|
identityProvider: "email",
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
notificationSettings: { alert: {}, weeklySummary: {} },
|
notificationSettings: { alert: {} },
|
||||||
} as unknown as TUser;
|
} as unknown as TUser;
|
||||||
|
|
||||||
const mockOrganization = {
|
const mockOrganization = {
|
||||||
@@ -156,6 +170,17 @@ const mockProjectPermission = {
|
|||||||
role: "admin",
|
role: "admin",
|
||||||
} as any;
|
} as any;
|
||||||
|
|
||||||
|
const mockOrganizationTeams = [
|
||||||
|
{
|
||||||
|
id: "team-1",
|
||||||
|
name: "Development Team",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "team-2",
|
||||||
|
name: "Marketing Team",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
const mockSession: Session = {
|
const mockSession: Session = {
|
||||||
user: {
|
user: {
|
||||||
id: "user-1",
|
id: "user-1",
|
||||||
@@ -176,6 +201,8 @@ describe("EnvironmentLayout", () => {
|
|||||||
vi.mocked(getMonthlyOrganizationResponseCount).mockResolvedValue(500);
|
vi.mocked(getMonthlyOrganizationResponseCount).mockResolvedValue(500);
|
||||||
vi.mocked(getOrganizationProjectsLimit).mockResolvedValue(null as any);
|
vi.mocked(getOrganizationProjectsLimit).mockResolvedValue(null as any);
|
||||||
vi.mocked(getProjectPermissionByUserId).mockResolvedValue(mockProjectPermission);
|
vi.mocked(getProjectPermissionByUserId).mockResolvedValue(mockProjectPermission);
|
||||||
|
vi.mocked(getTeamsByOrganizationId).mockResolvedValue(mockOrganizationTeams);
|
||||||
|
vi.mocked(getAccessControlPermission).mockResolvedValue(true);
|
||||||
mockIsDevelopment = false;
|
mockIsDevelopment = false;
|
||||||
mockIsFormbricksCloud = false;
|
mockIsFormbricksCloud = false;
|
||||||
});
|
});
|
||||||
@@ -288,6 +315,110 @@ describe("EnvironmentLayout", () => {
|
|||||||
expect(screen.getByTestId("downgrade-banner")).toBeInTheDocument();
|
expect(screen.getByTestId("downgrade-banner")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("passes isAccessControlAllowed props to MainNavigation", async () => {
|
||||||
|
vi.resetModules();
|
||||||
|
await vi.doMock("@/modules/ee/license-check/lib/license", () => ({
|
||||||
|
getEnterpriseLicense: vi.fn().mockResolvedValue({
|
||||||
|
active: false,
|
||||||
|
isPendingDowngrade: false,
|
||||||
|
features: { isMultiOrgEnabled: false },
|
||||||
|
lastChecked: new Date(),
|
||||||
|
fallbackLevel: "live",
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
const { EnvironmentLayout } = await import(
|
||||||
|
"@/app/(app)/environments/[environmentId]/components/EnvironmentLayout"
|
||||||
|
);
|
||||||
|
render(
|
||||||
|
await EnvironmentLayout({
|
||||||
|
environmentId: "env-1",
|
||||||
|
session: mockSession,
|
||||||
|
children: <div>Child Content</div>,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByTestId("is-access-control-allowed")).toHaveTextContent("true");
|
||||||
|
expect(vi.mocked(getAccessControlPermission)).toHaveBeenCalledWith(mockOrganization.billing.plan);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("handles empty organizationTeams array", async () => {
|
||||||
|
vi.mocked(getTeamsByOrganizationId).mockResolvedValue([]);
|
||||||
|
vi.resetModules();
|
||||||
|
await vi.doMock("@/modules/ee/license-check/lib/license", () => ({
|
||||||
|
getEnterpriseLicense: vi.fn().mockResolvedValue({
|
||||||
|
active: false,
|
||||||
|
isPendingDowngrade: false,
|
||||||
|
features: { isMultiOrgEnabled: false },
|
||||||
|
lastChecked: new Date(),
|
||||||
|
fallbackLevel: "live",
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
const { EnvironmentLayout } = await import(
|
||||||
|
"@/app/(app)/environments/[environmentId]/components/EnvironmentLayout"
|
||||||
|
);
|
||||||
|
render(
|
||||||
|
await EnvironmentLayout({
|
||||||
|
environmentId: "env-1",
|
||||||
|
session: mockSession,
|
||||||
|
children: <div>Child Content</div>,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByTestId("organization-teams")).toHaveTextContent("[]");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("handles null organizationTeams", async () => {
|
||||||
|
vi.mocked(getTeamsByOrganizationId).mockResolvedValue(null);
|
||||||
|
vi.resetModules();
|
||||||
|
await vi.doMock("@/modules/ee/license-check/lib/license", () => ({
|
||||||
|
getEnterpriseLicense: vi.fn().mockResolvedValue({
|
||||||
|
active: false,
|
||||||
|
isPendingDowngrade: false,
|
||||||
|
features: { isMultiOrgEnabled: false },
|
||||||
|
lastChecked: new Date(),
|
||||||
|
fallbackLevel: "live",
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
const { EnvironmentLayout } = await import(
|
||||||
|
"@/app/(app)/environments/[environmentId]/components/EnvironmentLayout"
|
||||||
|
);
|
||||||
|
render(
|
||||||
|
await EnvironmentLayout({
|
||||||
|
environmentId: "env-1",
|
||||||
|
session: mockSession,
|
||||||
|
children: <div>Child Content</div>,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByTestId("organization-teams")).toHaveTextContent("[]");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("handles isAccessControlAllowed false", async () => {
|
||||||
|
vi.mocked(getAccessControlPermission).mockResolvedValue(false);
|
||||||
|
vi.resetModules();
|
||||||
|
await vi.doMock("@/modules/ee/license-check/lib/license", () => ({
|
||||||
|
getEnterpriseLicense: vi.fn().mockResolvedValue({
|
||||||
|
active: false,
|
||||||
|
isPendingDowngrade: false,
|
||||||
|
features: { isMultiOrgEnabled: false },
|
||||||
|
lastChecked: new Date(),
|
||||||
|
fallbackLevel: "live",
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
const { EnvironmentLayout } = await import(
|
||||||
|
"@/app/(app)/environments/[environmentId]/components/EnvironmentLayout"
|
||||||
|
);
|
||||||
|
render(
|
||||||
|
await EnvironmentLayout({
|
||||||
|
environmentId: "env-1",
|
||||||
|
session: mockSession,
|
||||||
|
children: <div>Child Content</div>,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByTestId("is-access-control-allowed")).toHaveTextContent("false");
|
||||||
|
});
|
||||||
|
|
||||||
test("throws error if user not found", async () => {
|
test("throws error if user not found", async () => {
|
||||||
vi.mocked(getUser).mockResolvedValue(null);
|
vi.mocked(getUser).mockResolvedValue(null);
|
||||||
vi.resetModules();
|
vi.resetModules();
|
||||||
|
|||||||
@@ -13,7 +13,10 @@ import {
|
|||||||
import { getUserProjects } from "@/lib/project/service";
|
import { getUserProjects } from "@/lib/project/service";
|
||||||
import { getUser } from "@/lib/user/service";
|
import { getUser } from "@/lib/user/service";
|
||||||
import { getEnterpriseLicense } from "@/modules/ee/license-check/lib/license";
|
import { getEnterpriseLicense } from "@/modules/ee/license-check/lib/license";
|
||||||
import { getOrganizationProjectsLimit } from "@/modules/ee/license-check/lib/utils";
|
import {
|
||||||
|
getAccessControlPermission,
|
||||||
|
getOrganizationProjectsLimit,
|
||||||
|
} from "@/modules/ee/license-check/lib/utils";
|
||||||
import { getProjectPermissionByUserId } from "@/modules/ee/teams/lib/roles";
|
import { getProjectPermissionByUserId } from "@/modules/ee/teams/lib/roles";
|
||||||
import { DevEnvironmentBanner } from "@/modules/ui/components/dev-environment-banner";
|
import { DevEnvironmentBanner } from "@/modules/ui/components/dev-environment-banner";
|
||||||
import { LimitsReachedBanner } from "@/modules/ui/components/limits-reached-banner";
|
import { LimitsReachedBanner } from "@/modules/ui/components/limits-reached-banner";
|
||||||
@@ -48,9 +51,10 @@ export const EnvironmentLayout = async ({ environmentId, session, children }: En
|
|||||||
throw new Error(t("common.environment_not_found"));
|
throw new Error(t("common.environment_not_found"));
|
||||||
}
|
}
|
||||||
|
|
||||||
const [projects, environments] = await Promise.all([
|
const [projects, environments, isAccessControlAllowed] = await Promise.all([
|
||||||
getUserProjects(user.id, organization.id),
|
getUserProjects(user.id, organization.id),
|
||||||
getEnvironments(environment.projectId),
|
getEnvironments(environment.projectId),
|
||||||
|
getAccessControlPermission(organization.billing.plan),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (!projects || !environments || !organizations) {
|
if (!projects || !environments || !organizations) {
|
||||||
@@ -117,15 +121,16 @@ export const EnvironmentLayout = async ({ environmentId, session, children }: En
|
|||||||
membershipRole={membershipRole}
|
membershipRole={membershipRole}
|
||||||
isMultiOrgEnabled={isMultiOrgEnabled}
|
isMultiOrgEnabled={isMultiOrgEnabled}
|
||||||
isLicenseActive={active}
|
isLicenseActive={active}
|
||||||
|
isAccessControlAllowed={isAccessControlAllowed}
|
||||||
/>
|
/>
|
||||||
<div id="mainContent" className="flex-1 overflow-y-auto bg-slate-50">
|
<div id="mainContent" className="flex flex-1 flex-col overflow-hidden bg-slate-50">
|
||||||
<TopControlBar
|
<TopControlBar
|
||||||
environment={environment}
|
environment={environment}
|
||||||
environments={environments}
|
environments={environments}
|
||||||
membershipRole={membershipRole}
|
membershipRole={membershipRole}
|
||||||
projectPermission={projectPermission}
|
projectPermission={projectPermission}
|
||||||
/>
|
/>
|
||||||
<div className="mt-14">{children}</div>
|
<div className="flex-1 overflow-y-auto">{children}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useSignOut } from "@/modules/auth/hooks/use-sign-out";
|
import { useSignOut } from "@/modules/auth/hooks/use-sign-out";
|
||||||
|
import { TOrganizationTeam } from "@/modules/ee/teams/team-list/types/team";
|
||||||
import { cleanup, render, screen, waitFor } from "@testing-library/react";
|
import { cleanup, render, screen, waitFor } from "@testing-library/react";
|
||||||
import userEvent from "@testing-library/user-event";
|
import userEvent from "@testing-library/user-event";
|
||||||
import { usePathname, useRouter } from "next/navigation";
|
import { usePathname, useRouter } from "next/navigation";
|
||||||
@@ -52,9 +53,19 @@ vi.mock("@/modules/organization/components/CreateOrganizationModal", () => ({
|
|||||||
open ? <div data-testid="create-org-modal">Create Org Modal</div> : null,
|
open ? <div data-testid="create-org-modal">Create Org Modal</div> : null,
|
||||||
}));
|
}));
|
||||||
vi.mock("@/modules/projects/components/project-switcher", () => ({
|
vi.mock("@/modules/projects/components/project-switcher", () => ({
|
||||||
ProjectSwitcher: ({ isCollapsed }: { isCollapsed: boolean }) => (
|
ProjectSwitcher: ({
|
||||||
|
isCollapsed,
|
||||||
|
organizationTeams,
|
||||||
|
isAccessControlAllowed,
|
||||||
|
}: {
|
||||||
|
isCollapsed: boolean;
|
||||||
|
organizationTeams: TOrganizationTeam[];
|
||||||
|
isAccessControlAllowed: boolean;
|
||||||
|
}) => (
|
||||||
<div data-testid="project-switcher" data-collapsed={isCollapsed}>
|
<div data-testid="project-switcher" data-collapsed={isCollapsed}>
|
||||||
Project Switcher
|
Project Switcher
|
||||||
|
<div data-testid="organization-teams-count">{organizationTeams?.length || 0}</div>
|
||||||
|
<div data-testid="is-access-control-allowed">{isAccessControlAllowed.toString()}</div>
|
||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
}));
|
}));
|
||||||
@@ -106,7 +117,7 @@ const mockUser = {
|
|||||||
identityProvider: "email",
|
identityProvider: "email",
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
notificationSettings: { alert: {}, weeklySummary: {} },
|
notificationSettings: { alert: {} },
|
||||||
role: "project_manager",
|
role: "project_manager",
|
||||||
objective: "other",
|
objective: "other",
|
||||||
} as unknown as TUser;
|
} as unknown as TUser;
|
||||||
@@ -146,6 +157,7 @@ const defaultProps = {
|
|||||||
membershipRole: "owner" as const,
|
membershipRole: "owner" as const,
|
||||||
organizationProjectsLimit: 5,
|
organizationProjectsLimit: 5,
|
||||||
isLicenseActive: true,
|
isLicenseActive: true,
|
||||||
|
isAccessControlAllowed: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
describe("MainNavigation", () => {
|
describe("MainNavigation", () => {
|
||||||
@@ -334,4 +346,23 @@ describe("MainNavigation", () => {
|
|||||||
});
|
});
|
||||||
expect(screen.queryByText("common.license")).not.toBeInTheDocument();
|
expect(screen.queryByText("common.license")).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("passes isAccessControlAllowed props to ProjectSwitcher", () => {
|
||||||
|
render(<MainNavigation {...defaultProps} />);
|
||||||
|
|
||||||
|
expect(screen.getByTestId("organization-teams-count")).toHaveTextContent("0");
|
||||||
|
expect(screen.getByTestId("is-access-control-allowed")).toHaveTextContent("true");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("handles no organizationTeams", () => {
|
||||||
|
render(<MainNavigation {...defaultProps} />);
|
||||||
|
|
||||||
|
expect(screen.getByTestId("organization-teams-count")).toHaveTextContent("0");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("handles isAccessControlAllowed false", () => {
|
||||||
|
render(<MainNavigation {...defaultProps} isAccessControlAllowed={false} />);
|
||||||
|
|
||||||
|
expect(screen.getByTestId("is-access-control-allowed")).toHaveTextContent("false");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -66,6 +66,7 @@ interface NavigationProps {
|
|||||||
membershipRole?: TOrganizationRole;
|
membershipRole?: TOrganizationRole;
|
||||||
organizationProjectsLimit: number;
|
organizationProjectsLimit: number;
|
||||||
isLicenseActive: boolean;
|
isLicenseActive: boolean;
|
||||||
|
isAccessControlAllowed: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const MainNavigation = ({
|
export const MainNavigation = ({
|
||||||
@@ -80,6 +81,7 @@ export const MainNavigation = ({
|
|||||||
organizationProjectsLimit,
|
organizationProjectsLimit,
|
||||||
isLicenseActive,
|
isLicenseActive,
|
||||||
isDevelopment,
|
isDevelopment,
|
||||||
|
isAccessControlAllowed,
|
||||||
}: NavigationProps) => {
|
}: NavigationProps) => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
@@ -323,6 +325,7 @@ export const MainNavigation = ({
|
|||||||
isTextVisible={isTextVisible}
|
isTextVisible={isTextVisible}
|
||||||
organization={organization}
|
organization={organization}
|
||||||
organizationProjectsLimit={organizationProjectsLimit}
|
organizationProjectsLimit={organizationProjectsLimit}
|
||||||
|
isAccessControlAllowed={isAccessControlAllowed}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -336,27 +339,30 @@ export const MainNavigation = ({
|
|||||||
<div
|
<div
|
||||||
tabIndex={0}
|
tabIndex={0}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex cursor-pointer flex-row items-center space-x-3",
|
"flex cursor-pointer flex-row items-center gap-3",
|
||||||
isCollapsed ? "pl-2" : "pl-4"
|
isCollapsed ? "justify-center px-2" : "px-4"
|
||||||
)}>
|
)}>
|
||||||
<ProfileAvatar userId={user.id} imageUrl={user.imageUrl} />
|
<ProfileAvatar userId={user.id} imageUrl={user.imageUrl} />
|
||||||
{!isCollapsed && !isTextVisible && (
|
{!isCollapsed && !isTextVisible && (
|
||||||
<>
|
<>
|
||||||
<div className={cn(isTextVisible ? "opacity-0" : "opacity-100")}>
|
<div
|
||||||
|
className={cn(isTextVisible ? "opacity-0" : "opacity-100", "grow overflow-hidden")}>
|
||||||
<p
|
<p
|
||||||
title={user?.email}
|
title={user?.email}
|
||||||
className={cn(
|
className={cn(
|
||||||
"ph-no-capture ph-no-capture -mb-0.5 max-w-28 truncate text-sm font-bold text-slate-700"
|
"ph-no-capture ph-no-capture -mb-0.5 truncate text-sm font-bold text-slate-700"
|
||||||
)}>
|
)}>
|
||||||
{user?.name ? <span>{user?.name}</span> : <span>{user?.email}</span>}
|
{user?.name ? <span>{user?.name}</span> : <span>{user?.email}</span>}
|
||||||
</p>
|
</p>
|
||||||
<p
|
<p
|
||||||
title={capitalizeFirstLetter(organization?.name)}
|
title={capitalizeFirstLetter(organization?.name)}
|
||||||
className="max-w-28 truncate text-sm text-slate-500">
|
className="truncate text-sm text-slate-500">
|
||||||
{capitalizeFirstLetter(organization?.name)}
|
{capitalizeFirstLetter(organization?.name)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<ChevronRightIcon className={cn("h-5 w-5 text-slate-700 hover:text-slate-500")} />
|
<ChevronRightIcon
|
||||||
|
className={cn("h-5 w-5 shrink-0 text-slate-700 hover:text-slate-500")}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ const TestComponent = () => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div data-testid="onlyComplete">{selectedFilter.onlyComplete.toString()}</div>
|
<div data-testid="responseStatus">{selectedFilter.responseStatus}</div>
|
||||||
<div data-testid="filterLength">{selectedFilter.filter.length}</div>
|
<div data-testid="filterLength">{selectedFilter.filter.length}</div>
|
||||||
<div data-testid="questionOptionsLength">{selectedOptions.questionOptions.length}</div>
|
<div data-testid="questionOptionsLength">{selectedOptions.questionOptions.length}</div>
|
||||||
<div data-testid="questionFilterOptionsLength">{selectedOptions.questionFilterOptions.length}</div>
|
<div data-testid="questionFilterOptionsLength">{selectedOptions.questionFilterOptions.length}</div>
|
||||||
@@ -44,7 +44,7 @@ const TestComponent = () => {
|
|||||||
filterType: { filterValue: "value1", filterComboBoxValue: "option1" },
|
filterType: { filterValue: "value1", filterComboBoxValue: "option1" },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
onlyComplete: true,
|
responseStatus: "complete",
|
||||||
})
|
})
|
||||||
}>
|
}>
|
||||||
Update Filter
|
Update Filter
|
||||||
@@ -81,7 +81,7 @@ describe("ResponseFilterContext", () => {
|
|||||||
</ResponseFilterProvider>
|
</ResponseFilterProvider>
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(screen.getByTestId("onlyComplete").textContent).toBe("false");
|
expect(screen.getByTestId("responseStatus").textContent).toBe("all");
|
||||||
expect(screen.getByTestId("filterLength").textContent).toBe("0");
|
expect(screen.getByTestId("filterLength").textContent).toBe("0");
|
||||||
expect(screen.getByTestId("questionOptionsLength").textContent).toBe("0");
|
expect(screen.getByTestId("questionOptionsLength").textContent).toBe("0");
|
||||||
expect(screen.getByTestId("questionFilterOptionsLength").textContent).toBe("0");
|
expect(screen.getByTestId("questionFilterOptionsLength").textContent).toBe("0");
|
||||||
@@ -99,7 +99,7 @@ describe("ResponseFilterContext", () => {
|
|||||||
const updateButton = screen.getByText("Update Filter");
|
const updateButton = screen.getByText("Update Filter");
|
||||||
await userEvent.click(updateButton);
|
await userEvent.click(updateButton);
|
||||||
|
|
||||||
expect(screen.getByTestId("onlyComplete").textContent).toBe("true");
|
expect(screen.getByTestId("responseStatus").textContent).toBe("complete");
|
||||||
expect(screen.getByTestId("filterLength").textContent).toBe("1");
|
expect(screen.getByTestId("filterLength").textContent).toBe("1");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -16,9 +16,11 @@ export interface FilterValue {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type TResponseStatus = "all" | "complete" | "partial";
|
||||||
|
|
||||||
export interface SelectedFilterValue {
|
export interface SelectedFilterValue {
|
||||||
filter: FilterValue[];
|
filter: FilterValue[];
|
||||||
onlyComplete: boolean;
|
responseStatus: TResponseStatus;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface SelectedFilterOptions {
|
interface SelectedFilterOptions {
|
||||||
@@ -47,7 +49,7 @@ const ResponseFilterProvider = ({ children }: { children: React.ReactNode }) =>
|
|||||||
// state holds the filter selected value
|
// state holds the filter selected value
|
||||||
const [selectedFilter, setSelectedFilter] = useState<SelectedFilterValue>({
|
const [selectedFilter, setSelectedFilter] = useState<SelectedFilterValue>({
|
||||||
filter: [],
|
filter: [],
|
||||||
onlyComplete: false,
|
responseStatus: "all",
|
||||||
});
|
});
|
||||||
// state holds all the options of the responses fetched
|
// state holds all the options of the responses fetched
|
||||||
const [selectedOptions, setSelectedOptions] = useState<SelectedFilterOptions>({
|
const [selectedOptions, setSelectedOptions] = useState<SelectedFilterOptions>({
|
||||||
@@ -67,7 +69,7 @@ const ResponseFilterProvider = ({ children }: { children: React.ReactNode }) =>
|
|||||||
});
|
});
|
||||||
setSelectedFilter({
|
setSelectedFilter({
|
||||||
filter: [],
|
filter: [],
|
||||||
onlyComplete: false,
|
responseStatus: "all",
|
||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
|||||||
@@ -44,10 +44,8 @@ describe("TopControlBar", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Check if the main div is rendered
|
// Check if the main div is rendered
|
||||||
const mainDiv = screen.getByTestId("top-control-buttons").parentElement?.parentElement?.parentElement;
|
const mainDiv = screen.getByTestId("fb__global-top-control-bar");
|
||||||
expect(mainDiv).toHaveClass(
|
expect(mainDiv).toHaveClass("flex h-14 w-full items-center justify-end bg-slate-50 px-6");
|
||||||
"fixed inset-0 top-0 z-30 flex h-14 w-full items-center justify-end bg-slate-50 px-6"
|
|
||||||
);
|
|
||||||
|
|
||||||
// Check if the mocked child component is rendered
|
// Check if the mocked child component is rendered
|
||||||
expect(screen.getByTestId("top-control-buttons")).toBeInTheDocument();
|
expect(screen.getByTestId("top-control-buttons")).toBeInTheDocument();
|
||||||
|
|||||||
@@ -17,7 +17,9 @@ export const TopControlBar = ({
|
|||||||
projectPermission,
|
projectPermission,
|
||||||
}: SideBarProps) => {
|
}: SideBarProps) => {
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 top-0 z-30 flex h-14 w-full items-center justify-end bg-slate-50 px-6">
|
<div
|
||||||
|
className="flex h-14 w-full items-center justify-end bg-slate-50 px-6"
|
||||||
|
data-testid="fb__global-top-control-bar">
|
||||||
<div className="shadow-xs z-10">
|
<div className="shadow-xs z-10">
|
||||||
<div className="flex w-fit items-center space-x-2 py-2">
|
<div className="flex w-fit items-center space-x-2 py-2">
|
||||||
<TopControlButtons
|
<TopControlButtons
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { TProject } from "@formbricks/types/project";
|
|||||||
export interface EnvironmentContextType {
|
export interface EnvironmentContextType {
|
||||||
environment: TEnvironment;
|
environment: TEnvironment;
|
||||||
project: TProject;
|
project: TProject;
|
||||||
|
organizationId: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const EnvironmentContext = createContext<EnvironmentContextType | null>(null);
|
const EnvironmentContext = createContext<EnvironmentContextType | null>(null);
|
||||||
@@ -35,6 +36,7 @@ export const EnvironmentContextWrapper = ({
|
|||||||
() => ({
|
() => ({
|
||||||
environment,
|
environment,
|
||||||
project,
|
project,
|
||||||
|
organizationId: project.organizationId,
|
||||||
}),
|
}),
|
||||||
[environment, project]
|
[environment, project]
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -30,16 +30,16 @@ interface ManageIntegrationProps {
|
|||||||
locale: TUserLocale;
|
locale: TUserLocale;
|
||||||
}
|
}
|
||||||
|
|
||||||
const tableHeaders = [
|
|
||||||
"common.survey",
|
|
||||||
"environments.integrations.airtable.table_name",
|
|
||||||
"common.questions",
|
|
||||||
"common.updated_at",
|
|
||||||
];
|
|
||||||
|
|
||||||
export const ManageIntegration = (props: ManageIntegrationProps) => {
|
export const ManageIntegration = (props: ManageIntegrationProps) => {
|
||||||
const { airtableIntegration, environment, environmentId, setIsConnected, surveys, airtableArray } = props;
|
const { airtableIntegration, environment, environmentId, setIsConnected, surveys, airtableArray } = props;
|
||||||
const { t } = useTranslate();
|
const { t } = useTranslate();
|
||||||
|
|
||||||
|
const tableHeaders = [
|
||||||
|
t("common.survey"),
|
||||||
|
t("environments.integrations.airtable.table_name"),
|
||||||
|
t("common.questions"),
|
||||||
|
t("common.updated_at"),
|
||||||
|
];
|
||||||
const [isDeleting, setisDeleting] = useState(false);
|
const [isDeleting, setisDeleting] = useState(false);
|
||||||
const [isDeleteIntegrationModalOpen, setIsDeleteIntegrationModalOpen] = useState(false);
|
const [isDeleteIntegrationModalOpen, setIsDeleteIntegrationModalOpen] = useState(false);
|
||||||
const [defaultValues, setDefaultValues] = useState<(IntegrationModalInputs & { index: number }) | null>(
|
const [defaultValues, setDefaultValues] = useState<(IntegrationModalInputs & { index: number }) | null>(
|
||||||
@@ -100,7 +100,7 @@ export const ManageIntegration = (props: ManageIntegrationProps) => {
|
|||||||
<div className="grid h-12 grid-cols-8 content-center rounded-lg bg-slate-100 text-left text-sm font-semibold text-slate-900">
|
<div className="grid h-12 grid-cols-8 content-center rounded-lg bg-slate-100 text-left text-sm font-semibold text-slate-900">
|
||||||
{tableHeaders.map((header) => (
|
{tableHeaders.map((header) => (
|
||||||
<div key={header} className={`col-span-2 hidden text-center sm:block`}>
|
<div key={header} className={`col-span-2 hidden text-center sm:block`}>
|
||||||
{t(header)}
|
{header}
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -220,7 +220,6 @@ const surveys: TSurvey[] = [
|
|||||||
welcomeCard: { enabled: true } as unknown as TSurvey["welcomeCard"],
|
welcomeCard: { enabled: true } as unknown as TSurvey["welcomeCard"],
|
||||||
hiddenFields: { enabled: true, fieldIds: [] },
|
hiddenFields: { enabled: true, fieldIds: [] },
|
||||||
pin: null,
|
pin: null,
|
||||||
resultShareKey: null,
|
|
||||||
displayLimit: null,
|
displayLimit: null,
|
||||||
} as unknown as TSurvey,
|
} as unknown as TSurvey,
|
||||||
{
|
{
|
||||||
@@ -258,7 +257,6 @@ const surveys: TSurvey[] = [
|
|||||||
welcomeCard: { enabled: true } as unknown as TSurvey["welcomeCard"],
|
welcomeCard: { enabled: true } as unknown as TSurvey["welcomeCard"],
|
||||||
hiddenFields: { enabled: true, fieldIds: [] },
|
hiddenFields: { enabled: true, fieldIds: [] },
|
||||||
pin: null,
|
pin: null,
|
||||||
resultShareKey: null,
|
|
||||||
displayLimit: null,
|
displayLimit: null,
|
||||||
} as unknown as TSurvey,
|
} as unknown as TSurvey,
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -119,7 +119,6 @@ const mockSurveys: TSurvey[] = [
|
|||||||
displayPercentage: null,
|
displayPercentage: null,
|
||||||
languages: [],
|
languages: [],
|
||||||
pin: null,
|
pin: null,
|
||||||
resultShareKey: null,
|
|
||||||
segment: null,
|
segment: null,
|
||||||
singleUse: null,
|
singleUse: null,
|
||||||
styling: null,
|
styling: null,
|
||||||
|
|||||||
@@ -236,7 +236,6 @@ const surveys: TSurvey[] = [
|
|||||||
languages: [],
|
languages: [],
|
||||||
welcomeCard: { enabled: true } as unknown as TSurvey["welcomeCard"],
|
welcomeCard: { enabled: true } as unknown as TSurvey["welcomeCard"],
|
||||||
pin: null,
|
pin: null,
|
||||||
resultShareKey: null,
|
|
||||||
displayLimit: null,
|
displayLimit: null,
|
||||||
} as unknown as TSurvey,
|
} as unknown as TSurvey,
|
||||||
{
|
{
|
||||||
@@ -272,7 +271,6 @@ const surveys: TSurvey[] = [
|
|||||||
languages: [],
|
languages: [],
|
||||||
welcomeCard: { enabled: true } as unknown as TSurvey["welcomeCard"],
|
welcomeCard: { enabled: true } as unknown as TSurvey["welcomeCard"],
|
||||||
pin: null,
|
pin: null,
|
||||||
resultShareKey: null,
|
|
||||||
displayLimit: null,
|
displayLimit: null,
|
||||||
} as unknown as TSurvey,
|
} as unknown as TSurvey,
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -128,7 +128,6 @@ const mockSurveys: TSurvey[] = [
|
|||||||
displayPercentage: null,
|
displayPercentage: null,
|
||||||
languages: [],
|
languages: [],
|
||||||
pin: null,
|
pin: null,
|
||||||
resultShareKey: null,
|
|
||||||
segment: null,
|
segment: null,
|
||||||
singleUse: null,
|
singleUse: null,
|
||||||
styling: null,
|
styling: null,
|
||||||
|
|||||||
@@ -226,7 +226,6 @@ const surveys: TSurvey[] = [
|
|||||||
welcomeCard: { enabled: true } as unknown as TSurvey["welcomeCard"],
|
welcomeCard: { enabled: true } as unknown as TSurvey["welcomeCard"],
|
||||||
hiddenFields: { enabled: true, fieldIds: [] },
|
hiddenFields: { enabled: true, fieldIds: [] },
|
||||||
pin: null,
|
pin: null,
|
||||||
resultShareKey: null,
|
|
||||||
displayLimit: null,
|
displayLimit: null,
|
||||||
} as unknown as TSurvey,
|
} as unknown as TSurvey,
|
||||||
{
|
{
|
||||||
@@ -264,7 +263,6 @@ const surveys: TSurvey[] = [
|
|||||||
welcomeCard: { enabled: true } as unknown as TSurvey["welcomeCard"],
|
welcomeCard: { enabled: true } as unknown as TSurvey["welcomeCard"],
|
||||||
hiddenFields: { enabled: true, fieldIds: [] },
|
hiddenFields: { enabled: true, fieldIds: [] },
|
||||||
pin: null,
|
pin: null,
|
||||||
resultShareKey: null,
|
|
||||||
displayLimit: null,
|
displayLimit: null,
|
||||||
} as unknown as TSurvey,
|
} as unknown as TSurvey,
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -114,7 +114,6 @@ const mockSurveys: TSurvey[] = [
|
|||||||
languages: [],
|
languages: [],
|
||||||
styling: null,
|
styling: null,
|
||||||
segment: null,
|
segment: null,
|
||||||
resultShareKey: null,
|
|
||||||
displayPercentage: null,
|
displayPercentage: null,
|
||||||
closeOnDate: null,
|
closeOnDate: null,
|
||||||
runOnDate: null,
|
runOnDate: null,
|
||||||
|
|||||||
@@ -49,7 +49,6 @@ const mockUser = {
|
|||||||
email: "test@example.com",
|
email: "test@example.com",
|
||||||
notificationSettings: {
|
notificationSettings: {
|
||||||
alert: {},
|
alert: {},
|
||||||
weeklySummary: {},
|
|
||||||
unsubscribedOrganizationIds: [],
|
unsubscribedOrganizationIds: [],
|
||||||
},
|
},
|
||||||
role: "project_manager",
|
role: "project_manager",
|
||||||
|
|||||||
@@ -1,166 +0,0 @@
|
|||||||
import { cleanup, render, screen } from "@testing-library/react";
|
|
||||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
|
||||||
import { TUser } from "@formbricks/types/user";
|
|
||||||
import { Membership } from "../types";
|
|
||||||
import { EditWeeklySummary } from "./EditWeeklySummary";
|
|
||||||
|
|
||||||
vi.mock("lucide-react", () => ({
|
|
||||||
UsersIcon: () => <div data-testid="users-icon" />,
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock("next/link", () => ({
|
|
||||||
default: ({ children, href }: { children: React.ReactNode; href: string }) => (
|
|
||||||
<a href={href} data-testid="link">
|
|
||||||
{children}
|
|
||||||
</a>
|
|
||||||
),
|
|
||||||
}));
|
|
||||||
|
|
||||||
const mockNotificationSwitch = vi.fn();
|
|
||||||
vi.mock("./NotificationSwitch", () => ({
|
|
||||||
NotificationSwitch: (props: any) => {
|
|
||||||
mockNotificationSwitch(props);
|
|
||||||
return (
|
|
||||||
<div data-testid={`notification-switch-${props.surveyOrProjectOrOrganizationId}`}>
|
|
||||||
NotificationSwitch
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
const mockT = vi.fn((key) => key);
|
|
||||||
vi.mock("@tolgee/react", () => ({
|
|
||||||
useTranslate: () => ({
|
|
||||||
t: mockT,
|
|
||||||
}),
|
|
||||||
}));
|
|
||||||
|
|
||||||
const mockUser = {
|
|
||||||
id: "user1",
|
|
||||||
name: "Test User",
|
|
||||||
email: "test@example.com",
|
|
||||||
notificationSettings: {
|
|
||||||
alert: {},
|
|
||||||
weeklySummary: {
|
|
||||||
proj1: true,
|
|
||||||
proj3: false,
|
|
||||||
},
|
|
||||||
unsubscribedOrganizationIds: [],
|
|
||||||
},
|
|
||||||
role: "project_manager",
|
|
||||||
objective: "other",
|
|
||||||
emailVerified: new Date(),
|
|
||||||
createdAt: new Date(),
|
|
||||||
updatedAt: new Date(),
|
|
||||||
identityProvider: "email",
|
|
||||||
twoFactorEnabled: false,
|
|
||||||
} as unknown as TUser;
|
|
||||||
|
|
||||||
const mockMemberships: Membership[] = [
|
|
||||||
{
|
|
||||||
organization: {
|
|
||||||
id: "org1",
|
|
||||||
name: "Organization 1",
|
|
||||||
projects: [
|
|
||||||
{ id: "proj1", name: "Project 1", environments: [] },
|
|
||||||
{ id: "proj2", name: "Project 2", environments: [] },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
organization: {
|
|
||||||
id: "org2",
|
|
||||||
name: "Organization 2",
|
|
||||||
projects: [{ id: "proj3", name: "Project 3", environments: [] }],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
const environmentId = "test-env-id";
|
|
||||||
|
|
||||||
describe("EditWeeklySummary", () => {
|
|
||||||
afterEach(() => {
|
|
||||||
cleanup();
|
|
||||||
vi.clearAllMocks();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("renders correctly with multiple memberships and projects", () => {
|
|
||||||
render(<EditWeeklySummary memberships={mockMemberships} user={mockUser} environmentId={environmentId} />);
|
|
||||||
|
|
||||||
expect(screen.getByText("Organization 1")).toBeInTheDocument();
|
|
||||||
expect(screen.getByText("Project 1")).toBeInTheDocument();
|
|
||||||
expect(screen.getByText("Project 2")).toBeInTheDocument();
|
|
||||||
expect(screen.getByText("Organization 2")).toBeInTheDocument();
|
|
||||||
expect(screen.getByText("Project 3")).toBeInTheDocument();
|
|
||||||
|
|
||||||
expect(mockNotificationSwitch).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
surveyOrProjectOrOrganizationId: "proj1",
|
|
||||||
notificationSettings: mockUser.notificationSettings,
|
|
||||||
notificationType: "weeklySummary",
|
|
||||||
})
|
|
||||||
);
|
|
||||||
expect(screen.getByTestId("notification-switch-proj1")).toBeInTheDocument();
|
|
||||||
|
|
||||||
expect(mockNotificationSwitch).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
surveyOrProjectOrOrganizationId: "proj2",
|
|
||||||
notificationSettings: mockUser.notificationSettings,
|
|
||||||
notificationType: "weeklySummary",
|
|
||||||
})
|
|
||||||
);
|
|
||||||
expect(screen.getByTestId("notification-switch-proj2")).toBeInTheDocument();
|
|
||||||
|
|
||||||
expect(mockNotificationSwitch).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
surveyOrProjectOrOrganizationId: "proj3",
|
|
||||||
notificationSettings: mockUser.notificationSettings,
|
|
||||||
notificationType: "weeklySummary",
|
|
||||||
})
|
|
||||||
);
|
|
||||||
expect(screen.getByTestId("notification-switch-proj3")).toBeInTheDocument();
|
|
||||||
|
|
||||||
const inviteLinks = screen.getAllByTestId("link");
|
|
||||||
expect(inviteLinks.length).toBe(mockMemberships.length);
|
|
||||||
inviteLinks.forEach((link) => {
|
|
||||||
expect(link).toHaveAttribute("href", `/environments/${environmentId}/settings/general`);
|
|
||||||
expect(link).toHaveTextContent("common.invite_them");
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(screen.getAllByTestId("users-icon").length).toBe(mockMemberships.length);
|
|
||||||
|
|
||||||
expect(screen.getAllByText("common.project")[0]).toBeInTheDocument();
|
|
||||||
expect(screen.getAllByText("common.weekly_summary")[0]).toBeInTheDocument();
|
|
||||||
expect(
|
|
||||||
screen.getAllByText("environments.settings.notifications.want_to_loop_in_organization_mates?").length
|
|
||||||
).toBe(mockMemberships.length);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("renders correctly with no memberships", () => {
|
|
||||||
render(<EditWeeklySummary memberships={[]} user={mockUser} environmentId={environmentId} />);
|
|
||||||
expect(screen.queryByText("Organization 1")).not.toBeInTheDocument();
|
|
||||||
expect(screen.queryByTestId("users-icon")).not.toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("renders correctly when an organization has no projects", () => {
|
|
||||||
const membershipsWithNoProjects: Membership[] = [
|
|
||||||
{
|
|
||||||
organization: {
|
|
||||||
id: "org3",
|
|
||||||
name: "Organization No Projects",
|
|
||||||
projects: [],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
];
|
|
||||||
render(
|
|
||||||
<EditWeeklySummary
|
|
||||||
memberships={membershipsWithNoProjects}
|
|
||||||
user={mockUser}
|
|
||||||
environmentId={environmentId}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
expect(screen.getByText("Organization No Projects")).toBeInTheDocument();
|
|
||||||
expect(screen.queryByText("Project 1")).not.toBeInTheDocument(); // Check that no projects are listed under it
|
|
||||||
expect(mockNotificationSwitch).not.toHaveBeenCalled(); // No projects, so no switches for projects
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useTranslate } from "@tolgee/react";
|
|
||||||
import { UsersIcon } from "lucide-react";
|
|
||||||
import Link from "next/link";
|
|
||||||
import { TUser } from "@formbricks/types/user";
|
|
||||||
import { Membership } from "../types";
|
|
||||||
import { NotificationSwitch } from "./NotificationSwitch";
|
|
||||||
|
|
||||||
interface EditAlertsProps {
|
|
||||||
memberships: Membership[];
|
|
||||||
user: TUser;
|
|
||||||
environmentId: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const EditWeeklySummary = ({ memberships, user, environmentId }: EditAlertsProps) => {
|
|
||||||
const { t } = useTranslate();
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
{memberships.map((membership) => (
|
|
||||||
<div key={membership.organization.id}>
|
|
||||||
<div className="mb-5 flex items-center space-x-3 text-sm font-medium">
|
|
||||||
<UsersIcon className="h-6 w-7 text-slate-600" />
|
|
||||||
|
|
||||||
<p className="text-slate-800">{membership.organization.name}</p>
|
|
||||||
</div>
|
|
||||||
<div className="mb-6 rounded-lg border border-slate-200">
|
|
||||||
<div className="grid h-12 grid-cols-3 content-center rounded-t-lg bg-slate-100 px-4 text-left text-sm font-semibold text-slate-900">
|
|
||||||
<div className="col-span-2">{t("common.project")}</div>
|
|
||||||
<div className="col-span-1 text-center">{t("common.weekly_summary")}</div>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1 p-2">
|
|
||||||
{membership.organization.projects.map((project) => (
|
|
||||||
<div
|
|
||||||
className="grid h-auto w-full cursor-pointer grid-cols-3 place-content-center justify-center rounded-lg px-2 py-2 text-left text-sm text-slate-900 hover:bg-slate-50"
|
|
||||||
key={project.id}>
|
|
||||||
<div className="col-span-2">{project?.name}</div>
|
|
||||||
<div className="col-span-1 flex items-center justify-center">
|
|
||||||
<NotificationSwitch
|
|
||||||
surveyOrProjectOrOrganizationId={project.id}
|
|
||||||
notificationSettings={user.notificationSettings!}
|
|
||||||
notificationType={"weeklySummary"}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<p className="pb-3 pl-4 text-xs text-slate-400">
|
|
||||||
{t("environments.settings.notifications.want_to_loop_in_organization_mates")}?{" "}
|
|
||||||
<Link className="font-semibold" href={`/environments/${environmentId}/settings/general`}>
|
|
||||||
{t("common.invite_them")}
|
|
||||||
</Link>
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -29,7 +29,6 @@ const organizationId = "org1";
|
|||||||
|
|
||||||
const baseNotificationSettings: TUserNotificationSettings = {
|
const baseNotificationSettings: TUserNotificationSettings = {
|
||||||
alert: {},
|
alert: {},
|
||||||
weeklySummary: {},
|
|
||||||
unsubscribedOrganizationIds: [],
|
unsubscribedOrganizationIds: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -68,19 +67,6 @@ describe("NotificationSwitch", () => {
|
|||||||
expect(switchInput.checked).toBe(false);
|
expect(switchInput.checked).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("renders with initial checked state for 'weeklySummary' (true)", () => {
|
|
||||||
const settings = { ...baseNotificationSettings, weeklySummary: { [projectId]: true } };
|
|
||||||
renderSwitch({
|
|
||||||
surveyOrProjectOrOrganizationId: projectId,
|
|
||||||
notificationSettings: settings,
|
|
||||||
notificationType: "weeklySummary",
|
|
||||||
});
|
|
||||||
const switchInput = screen.getByLabelText(
|
|
||||||
"toggle notification settings for weeklySummary"
|
|
||||||
) as HTMLInputElement;
|
|
||||||
expect(switchInput.checked).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("renders with initial checked state for 'unsubscribedOrganizationIds' (subscribed initially, so checked is true)", () => {
|
test("renders with initial checked state for 'unsubscribedOrganizationIds' (subscribed initially, so checked is true)", () => {
|
||||||
const settings = { ...baseNotificationSettings, unsubscribedOrganizationIds: [] };
|
const settings = { ...baseNotificationSettings, unsubscribedOrganizationIds: [] };
|
||||||
renderSwitch({
|
renderSwitch({
|
||||||
@@ -268,31 +254,6 @@ describe("NotificationSwitch", () => {
|
|||||||
expect(toast.success).not.toHaveBeenCalled();
|
expect(toast.success).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("shows error toast when updateNotificationSettingsAction fails for 'weeklySummary' type", async () => {
|
|
||||||
const mockErrorResponse = { serverError: "Database connection failed" };
|
|
||||||
vi.mocked(updateNotificationSettingsAction).mockResolvedValueOnce(mockErrorResponse);
|
|
||||||
|
|
||||||
const initialSettings = { ...baseNotificationSettings, weeklySummary: { [projectId]: true } };
|
|
||||||
renderSwitch({
|
|
||||||
surveyOrProjectOrOrganizationId: projectId,
|
|
||||||
notificationSettings: initialSettings,
|
|
||||||
notificationType: "weeklySummary",
|
|
||||||
});
|
|
||||||
const switchInput = screen.getByLabelText("toggle notification settings for weeklySummary");
|
|
||||||
|
|
||||||
await act(async () => {
|
|
||||||
await user.click(switchInput);
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(updateNotificationSettingsAction).toHaveBeenCalledWith({
|
|
||||||
notificationSettings: { ...initialSettings, weeklySummary: { [projectId]: false } },
|
|
||||||
});
|
|
||||||
expect(toast.error).toHaveBeenCalledWith("Database connection failed", {
|
|
||||||
id: "notification-switch",
|
|
||||||
});
|
|
||||||
expect(toast.success).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("shows error toast when updateNotificationSettingsAction fails for 'unsubscribedOrganizationIds' type", async () => {
|
test("shows error toast when updateNotificationSettingsAction fails for 'unsubscribedOrganizationIds' type", async () => {
|
||||||
const mockErrorResponse = { serverError: "Permission denied" };
|
const mockErrorResponse = { serverError: "Permission denied" };
|
||||||
vi.mocked(updateNotificationSettingsAction).mockResolvedValueOnce(mockErrorResponse);
|
vi.mocked(updateNotificationSettingsAction).mockResolvedValueOnce(mockErrorResponse);
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import { updateNotificationSettingsAction } from "../actions";
|
|||||||
interface NotificationSwitchProps {
|
interface NotificationSwitchProps {
|
||||||
surveyOrProjectOrOrganizationId: string;
|
surveyOrProjectOrOrganizationId: string;
|
||||||
notificationSettings: TUserNotificationSettings;
|
notificationSettings: TUserNotificationSettings;
|
||||||
notificationType: "alert" | "weeklySummary" | "unsubscribedOrganizationIds";
|
notificationType: "alert" | "unsubscribedOrganizationIds";
|
||||||
autoDisableNotificationType?: string;
|
autoDisableNotificationType?: string;
|
||||||
autoDisableNotificationElementId?: string;
|
autoDisableNotificationElementId?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,17 +34,5 @@ describe("Loading Notifications Settings", () => {
|
|||||||
.getByText("environments.settings.notifications.email_alerts_surveys")
|
.getByText("environments.settings.notifications.email_alerts_surveys")
|
||||||
.closest("div[class*='rounded-xl']"); // Find parent card
|
.closest("div[class*='rounded-xl']"); // Find parent card
|
||||||
expect(alertsCard).toBeInTheDocument();
|
expect(alertsCard).toBeInTheDocument();
|
||||||
|
|
||||||
// Check for Weekly Summary LoadingCard
|
|
||||||
expect(
|
|
||||||
screen.getByText("environments.settings.notifications.weekly_summary_projects")
|
|
||||||
).toBeInTheDocument();
|
|
||||||
expect(
|
|
||||||
screen.getByText("environments.settings.notifications.stay_up_to_date_with_a_Weekly_every_Monday")
|
|
||||||
).toBeInTheDocument();
|
|
||||||
const weeklySummaryCard = screen
|
|
||||||
.getByText("environments.settings.notifications.weekly_summary_projects")
|
|
||||||
.closest("div[class*='rounded-xl']"); // Find parent card
|
|
||||||
expect(weeklySummaryCard).toBeInTheDocument();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,11 +14,6 @@ const Loading = () => {
|
|||||||
description: t("environments.settings.notifications.set_up_an_alert_to_get_an_email_on_new_responses"),
|
description: t("environments.settings.notifications.set_up_an_alert_to_get_an_email_on_new_responses"),
|
||||||
skeletonLines: [{ classes: "h-6 w-28" }, { classes: "h-10 w-128" }, { classes: "h-10 w-128" }],
|
skeletonLines: [{ classes: "h-6 w-28" }, { classes: "h-10 w-128" }, { classes: "h-10 w-128" }],
|
||||||
},
|
},
|
||||||
{
|
|
||||||
title: t("environments.settings.notifications.weekly_summary_projects"),
|
|
||||||
description: t("environments.settings.notifications.stay_up_to_date_with_a_Weekly_every_Monday"),
|
|
||||||
skeletonLines: [{ classes: "h-6 w-28" }, { classes: "h-10 w-128" }, { classes: "h-10 w-128" }],
|
|
||||||
},
|
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
|||||||
import { prisma } from "@formbricks/database";
|
import { prisma } from "@formbricks/database";
|
||||||
import { TUser } from "@formbricks/types/user";
|
import { TUser } from "@formbricks/types/user";
|
||||||
import { EditAlerts } from "./components/EditAlerts";
|
import { EditAlerts } from "./components/EditAlerts";
|
||||||
import { EditWeeklySummary } from "./components/EditWeeklySummary";
|
|
||||||
import Page from "./page";
|
import Page from "./page";
|
||||||
import { Membership } from "./types";
|
import { Membership } from "./types";
|
||||||
|
|
||||||
@@ -58,9 +57,7 @@ vi.mock("@formbricks/database", () => ({
|
|||||||
vi.mock("./components/EditAlerts", () => ({
|
vi.mock("./components/EditAlerts", () => ({
|
||||||
EditAlerts: vi.fn(() => <div>EditAlertsComponent</div>),
|
EditAlerts: vi.fn(() => <div>EditAlertsComponent</div>),
|
||||||
}));
|
}));
|
||||||
vi.mock("./components/EditWeeklySummary", () => ({
|
|
||||||
EditWeeklySummary: vi.fn(() => <div>EditWeeklySummaryComponent</div>),
|
|
||||||
}));
|
|
||||||
vi.mock("./components/IntegrationsTip", () => ({
|
vi.mock("./components/IntegrationsTip", () => ({
|
||||||
IntegrationsTip: () => <div>IntegrationsTipComponent</div>,
|
IntegrationsTip: () => <div>IntegrationsTipComponent</div>,
|
||||||
}));
|
}));
|
||||||
@@ -71,7 +68,6 @@ const mockUser: Partial<TUser> = {
|
|||||||
email: "test@example.com",
|
email: "test@example.com",
|
||||||
notificationSettings: {
|
notificationSettings: {
|
||||||
alert: { "survey-old": true },
|
alert: { "survey-old": true },
|
||||||
weeklySummary: { "project-old": true },
|
|
||||||
unsubscribedOrganizationIds: ["org-unsubscribed"],
|
unsubscribedOrganizationIds: ["org-unsubscribed"],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -137,13 +133,6 @@ describe("NotificationsPage", () => {
|
|||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
expect(screen.getByText("EditAlertsComponent")).toBeInTheDocument();
|
expect(screen.getByText("EditAlertsComponent")).toBeInTheDocument();
|
||||||
expect(screen.getByText("IntegrationsTipComponent")).toBeInTheDocument();
|
expect(screen.getByText("IntegrationsTipComponent")).toBeInTheDocument();
|
||||||
expect(
|
|
||||||
screen.getByText("environments.settings.notifications.weekly_summary_projects")
|
|
||||||
).toBeInTheDocument();
|
|
||||||
expect(
|
|
||||||
screen.getByText("environments.settings.notifications.stay_up_to_date_with_a_Weekly_every_Monday")
|
|
||||||
).toBeInTheDocument();
|
|
||||||
expect(screen.getByText("EditWeeklySummaryComponent")).toBeInTheDocument();
|
|
||||||
|
|
||||||
// The actual `user.notificationSettings` passed to EditAlerts will be a new object
|
// The actual `user.notificationSettings` passed to EditAlerts will be a new object
|
||||||
// after `setCompleteNotificationSettings` processes it.
|
// after `setCompleteNotificationSettings` processes it.
|
||||||
@@ -157,16 +146,12 @@ describe("NotificationsPage", () => {
|
|||||||
// It iterates memberships, then projects, then environments, then surveys.
|
// It iterates memberships, then projects, then environments, then surveys.
|
||||||
// `newNotificationSettings.alert[survey.id] = notificationSettings[survey.id]?.responseFinished || (notificationSettings.alert && notificationSettings.alert[survey.id]) || false;`
|
// `newNotificationSettings.alert[survey.id] = notificationSettings[survey.id]?.responseFinished || (notificationSettings.alert && notificationSettings.alert[survey.id]) || false;`
|
||||||
// This means only survey IDs found in memberships will be in the new `alert` object.
|
// This means only survey IDs found in memberships will be in the new `alert` object.
|
||||||
// `newNotificationSettings.weeklySummary[project.id]` also only adds project IDs from memberships.
|
|
||||||
|
|
||||||
const finalExpectedSettings = {
|
const finalExpectedSettings = {
|
||||||
alert: {
|
alert: {
|
||||||
"survey-1": false,
|
"survey-1": false,
|
||||||
"survey-2": false,
|
"survey-2": false,
|
||||||
},
|
},
|
||||||
weeklySummary: {
|
|
||||||
"project-1": false,
|
|
||||||
},
|
|
||||||
unsubscribedOrganizationIds: ["org-unsubscribed"],
|
unsubscribedOrganizationIds: ["org-unsubscribed"],
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -175,11 +160,6 @@ describe("NotificationsPage", () => {
|
|||||||
expect(editAlertsCall.environmentId).toBe(mockParams.environmentId);
|
expect(editAlertsCall.environmentId).toBe(mockParams.environmentId);
|
||||||
expect(editAlertsCall.autoDisableNotificationType).toBe(mockSearchParams.type);
|
expect(editAlertsCall.autoDisableNotificationType).toBe(mockSearchParams.type);
|
||||||
expect(editAlertsCall.autoDisableNotificationElementId).toBe(mockSearchParams.elementId);
|
expect(editAlertsCall.autoDisableNotificationElementId).toBe(mockSearchParams.elementId);
|
||||||
|
|
||||||
const editWeeklySummaryCall = vi.mocked(EditWeeklySummary).mock.calls[0][0];
|
|
||||||
expect(editWeeklySummaryCall.user.notificationSettings).toEqual(finalExpectedSettings);
|
|
||||||
expect(editWeeklySummaryCall.memberships).toEqual(mockMemberships);
|
|
||||||
expect(editWeeklySummaryCall.environmentId).toBe(mockParams.environmentId);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("throws error if session is not found", async () => {
|
test("throws error if session is not found", async () => {
|
||||||
@@ -207,21 +187,15 @@ describe("NotificationsPage", () => {
|
|||||||
render(PageComponent);
|
render(PageComponent);
|
||||||
|
|
||||||
expect(screen.getByText("EditAlertsComponent")).toBeInTheDocument();
|
expect(screen.getByText("EditAlertsComponent")).toBeInTheDocument();
|
||||||
expect(screen.getByText("EditWeeklySummaryComponent")).toBeInTheDocument();
|
|
||||||
|
|
||||||
const expectedEmptySettings = {
|
const expectedEmptySettings = {
|
||||||
alert: {},
|
alert: {},
|
||||||
weeklySummary: {},
|
|
||||||
unsubscribedOrganizationIds: [],
|
unsubscribedOrganizationIds: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
const editAlertsCall = vi.mocked(EditAlerts).mock.calls[0][0];
|
const editAlertsCall = vi.mocked(EditAlerts).mock.calls[0][0];
|
||||||
expect(editAlertsCall.user.notificationSettings).toEqual(expectedEmptySettings);
|
expect(editAlertsCall.user.notificationSettings).toEqual(expectedEmptySettings);
|
||||||
expect(editAlertsCall.memberships).toEqual([]);
|
expect(editAlertsCall.memberships).toEqual([]);
|
||||||
|
|
||||||
const editWeeklySummaryCall = vi.mocked(EditWeeklySummary).mock.calls[0][0];
|
|
||||||
expect(editWeeklySummaryCall.user.notificationSettings).toEqual(expectedEmptySettings);
|
|
||||||
expect(editWeeklySummaryCall.memberships).toEqual([]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("handles legacy notification settings correctly", async () => {
|
test("handles legacy notification settings correctly", async () => {
|
||||||
@@ -229,7 +203,6 @@ describe("NotificationsPage", () => {
|
|||||||
id: "user-legacy",
|
id: "user-legacy",
|
||||||
notificationSettings: {
|
notificationSettings: {
|
||||||
"survey-1": { responseFinished: true }, // Legacy alert for survey-1
|
"survey-1": { responseFinished: true }, // Legacy alert for survey-1
|
||||||
weeklySummary: { "project-1": true },
|
|
||||||
unsubscribedOrganizationIds: [],
|
unsubscribedOrganizationIds: [],
|
||||||
} as any, // To allow legacy structure
|
} as any, // To allow legacy structure
|
||||||
};
|
};
|
||||||
@@ -246,9 +219,6 @@ describe("NotificationsPage", () => {
|
|||||||
"survey-1": true, // Should be true due to legacy setting
|
"survey-1": true, // Should be true due to legacy setting
|
||||||
"survey-2": false, // Default for other surveys in membership
|
"survey-2": false, // Default for other surveys in membership
|
||||||
},
|
},
|
||||||
weeklySummary: {
|
|
||||||
"project-1": true, // From user's weeklySummary
|
|
||||||
},
|
|
||||||
unsubscribedOrganizationIds: [],
|
unsubscribedOrganizationIds: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import { getServerSession } from "next-auth";
|
|||||||
import { prisma } from "@formbricks/database";
|
import { prisma } from "@formbricks/database";
|
||||||
import { TUserNotificationSettings } from "@formbricks/types/user";
|
import { TUserNotificationSettings } from "@formbricks/types/user";
|
||||||
import { EditAlerts } from "./components/EditAlerts";
|
import { EditAlerts } from "./components/EditAlerts";
|
||||||
import { EditWeeklySummary } from "./components/EditWeeklySummary";
|
|
||||||
import { IntegrationsTip } from "./components/IntegrationsTip";
|
import { IntegrationsTip } from "./components/IntegrationsTip";
|
||||||
import type { Membership } from "./types";
|
import type { Membership } from "./types";
|
||||||
|
|
||||||
@@ -19,14 +18,10 @@ const setCompleteNotificationSettings = (
|
|||||||
): TUserNotificationSettings => {
|
): TUserNotificationSettings => {
|
||||||
const newNotificationSettings = {
|
const newNotificationSettings = {
|
||||||
alert: {},
|
alert: {},
|
||||||
weeklySummary: {},
|
|
||||||
unsubscribedOrganizationIds: notificationSettings.unsubscribedOrganizationIds || [],
|
unsubscribedOrganizationIds: notificationSettings.unsubscribedOrganizationIds || [],
|
||||||
};
|
};
|
||||||
for (const membership of memberships) {
|
for (const membership of memberships) {
|
||||||
for (const project of membership.organization.projects) {
|
for (const project of membership.organization.projects) {
|
||||||
// set default values for weekly summary
|
|
||||||
newNotificationSettings.weeklySummary[project.id] =
|
|
||||||
(notificationSettings.weeklySummary && notificationSettings.weeklySummary[project.id]) || false;
|
|
||||||
// set default values for alerts
|
// set default values for alerts
|
||||||
for (const environment of project.environments) {
|
for (const environment of project.environments) {
|
||||||
for (const survey of environment.surveys) {
|
for (const survey of environment.surveys) {
|
||||||
@@ -183,11 +178,6 @@ const Page = async (props) => {
|
|||||||
/>
|
/>
|
||||||
</SettingsCard>
|
</SettingsCard>
|
||||||
<IntegrationsTip environmentId={params.environmentId} />
|
<IntegrationsTip environmentId={params.environmentId} />
|
||||||
<SettingsCard
|
|
||||||
title={t("environments.settings.notifications.weekly_summary_projects")}
|
|
||||||
description={t("environments.settings.notifications.stay_up_to_date_with_a_Weekly_every_Monday")}>
|
|
||||||
<EditWeeklySummary memberships={memberships} user={user} environmentId={params.environmentId} />
|
|
||||||
</SettingsCard>
|
|
||||||
</PageContentWrapper>
|
</PageContentWrapper>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -10,24 +10,19 @@ import { getFileNameWithIdFromUrl } from "@/lib/storage/utils";
|
|||||||
import { getUser, updateUser } from "@/lib/user/service";
|
import { getUser, updateUser } from "@/lib/user/service";
|
||||||
import { authenticatedActionClient } from "@/lib/utils/action-client";
|
import { authenticatedActionClient } from "@/lib/utils/action-client";
|
||||||
import { AuthenticatedActionClientCtx } from "@/lib/utils/action-client/types/context";
|
import { AuthenticatedActionClientCtx } from "@/lib/utils/action-client/types/context";
|
||||||
import { rateLimit } from "@/lib/utils/rate-limit";
|
|
||||||
import { updateBrevoCustomer } from "@/modules/auth/lib/brevo";
|
import { updateBrevoCustomer } from "@/modules/auth/lib/brevo";
|
||||||
|
import { applyRateLimit } from "@/modules/core/rate-limit/helpers";
|
||||||
|
import { rateLimitConfigs } from "@/modules/core/rate-limit/rate-limit-configs";
|
||||||
import { withAuditLogging } from "@/modules/ee/audit-logs/lib/handler";
|
import { withAuditLogging } from "@/modules/ee/audit-logs/lib/handler";
|
||||||
import { sendForgotPasswordEmail, sendVerificationNewEmail } from "@/modules/email";
|
import { sendForgotPasswordEmail, sendVerificationNewEmail } from "@/modules/email";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { ZId } from "@formbricks/types/common";
|
import { ZId } from "@formbricks/types/common";
|
||||||
|
import { AuthenticationError, AuthorizationError, OperationNotAllowedError } from "@formbricks/types/errors";
|
||||||
import {
|
import {
|
||||||
AuthenticationError,
|
TUserPersonalInfoUpdateInput,
|
||||||
AuthorizationError,
|
TUserUpdateInput,
|
||||||
OperationNotAllowedError,
|
ZUserPersonalInfoUpdateInput,
|
||||||
TooManyRequestsError,
|
} from "@formbricks/types/user";
|
||||||
} from "@formbricks/types/errors";
|
|
||||||
import { TUserUpdateInput, ZUserPassword, ZUserUpdateInput } from "@formbricks/types/user";
|
|
||||||
|
|
||||||
const limiter = rateLimit({
|
|
||||||
interval: 60 * 60, // 1 hour
|
|
||||||
allowedPerInterval: 3, // max 3 calls for email verification per hour
|
|
||||||
});
|
|
||||||
|
|
||||||
function buildUserUpdatePayload(parsedInput: any): TUserUpdateInput {
|
function buildUserUpdatePayload(parsedInput: any): TUserUpdateInput {
|
||||||
return {
|
return {
|
||||||
@@ -41,18 +36,15 @@ async function handleEmailUpdate({
|
|||||||
parsedInput,
|
parsedInput,
|
||||||
payload,
|
payload,
|
||||||
}: {
|
}: {
|
||||||
ctx: any;
|
ctx: AuthenticatedActionClientCtx;
|
||||||
parsedInput: any;
|
parsedInput: TUserPersonalInfoUpdateInput;
|
||||||
payload: TUserUpdateInput;
|
payload: TUserUpdateInput;
|
||||||
}) {
|
}) {
|
||||||
const inputEmail = parsedInput.email?.trim().toLowerCase();
|
const inputEmail = parsedInput.email?.trim().toLowerCase();
|
||||||
if (!inputEmail || ctx.user.email === inputEmail) return payload;
|
if (!inputEmail || ctx.user.email === inputEmail) return payload;
|
||||||
|
|
||||||
try {
|
await applyRateLimit(rateLimitConfigs.actions.emailUpdate, ctx.user.id);
|
||||||
await limiter(ctx.user.id);
|
|
||||||
} catch {
|
|
||||||
throw new TooManyRequestsError("Too many requests");
|
|
||||||
}
|
|
||||||
if (ctx.user.identityProvider !== "email") {
|
if (ctx.user.identityProvider !== "email") {
|
||||||
throw new OperationNotAllowedError("Email update is not allowed for non-credential users.");
|
throw new OperationNotAllowedError("Email update is not allowed for non-credential users.");
|
||||||
}
|
}
|
||||||
@@ -75,41 +67,35 @@ async function handleEmailUpdate({
|
|||||||
return payload;
|
return payload;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const updateUserAction = authenticatedActionClient
|
export const updateUserAction = authenticatedActionClient.schema(ZUserPersonalInfoUpdateInput).action(
|
||||||
.schema(
|
withAuditLogging(
|
||||||
ZUserUpdateInput.pick({ name: true, email: true, locale: true }).extend({
|
"updated",
|
||||||
password: ZUserPassword.optional(),
|
"user",
|
||||||
})
|
async ({
|
||||||
)
|
ctx,
|
||||||
.action(
|
parsedInput,
|
||||||
withAuditLogging(
|
}: {
|
||||||
"updated",
|
ctx: AuthenticatedActionClientCtx;
|
||||||
"user",
|
parsedInput: TUserPersonalInfoUpdateInput;
|
||||||
async ({
|
}) => {
|
||||||
ctx,
|
const oldObject = await getUser(ctx.user.id);
|
||||||
parsedInput,
|
let payload = buildUserUpdatePayload(parsedInput);
|
||||||
}: {
|
payload = await handleEmailUpdate({ ctx, parsedInput, payload });
|
||||||
ctx: AuthenticatedActionClientCtx;
|
|
||||||
parsedInput: Record<string, any>;
|
|
||||||
}) => {
|
|
||||||
const oldObject = await getUser(ctx.user.id);
|
|
||||||
let payload = buildUserUpdatePayload(parsedInput);
|
|
||||||
payload = await handleEmailUpdate({ ctx, parsedInput, payload });
|
|
||||||
|
|
||||||
// Only proceed with updateUser if we have actual changes to make
|
// Only proceed with updateUser if we have actual changes to make
|
||||||
let newObject = oldObject;
|
let newObject = oldObject;
|
||||||
if (Object.keys(payload).length > 0) {
|
if (Object.keys(payload).length > 0) {
|
||||||
newObject = await updateUser(ctx.user.id, payload);
|
newObject = await updateUser(ctx.user.id, payload);
|
||||||
}
|
|
||||||
|
|
||||||
ctx.auditLoggingCtx.userId = ctx.user.id;
|
|
||||||
ctx.auditLoggingCtx.oldObject = oldObject;
|
|
||||||
ctx.auditLoggingCtx.newObject = newObject;
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
)
|
|
||||||
);
|
ctx.auditLoggingCtx.userId = ctx.user.id;
|
||||||
|
ctx.auditLoggingCtx.oldObject = oldObject;
|
||||||
|
ctx.auditLoggingCtx.newObject = newObject;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
const ZUpdateAvatarAction = z.object({
|
const ZUpdateAvatarAction = z.object({
|
||||||
avatarUrl: z.string(),
|
avatarUrl: z.string(),
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ const mockUser = {
|
|||||||
email: "test@example.com",
|
email: "test@example.com",
|
||||||
notificationSettings: {
|
notificationSettings: {
|
||||||
alert: {},
|
alert: {},
|
||||||
weeklySummary: {},
|
|
||||||
unsubscribedOrganizationIds: [],
|
unsubscribedOrganizationIds: [],
|
||||||
},
|
},
|
||||||
twoFactorEnabled: false,
|
twoFactorEnabled: false,
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ const mockUser = {
|
|||||||
id: "user1",
|
id: "user1",
|
||||||
name: "Test User",
|
name: "Test User",
|
||||||
email: "test@example.com",
|
email: "test@example.com",
|
||||||
notificationSettings: { alert: {}, weeklySummary: {}, unsubscribedOrganizationIds: [] },
|
notificationSettings: { alert: {}, unsubscribedOrganizationIds: [] },
|
||||||
twoFactorEnabled: false,
|
twoFactorEnabled: false,
|
||||||
identityProvider: "email",
|
identityProvider: "email",
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ const mockUser = {
|
|||||||
locale: "en-US",
|
locale: "en-US",
|
||||||
notificationSettings: {
|
notificationSettings: {
|
||||||
alert: {},
|
alert: {},
|
||||||
weeklySummary: {},
|
|
||||||
unsubscribedOrganizationIds: [],
|
unsubscribedOrganizationIds: [],
|
||||||
},
|
},
|
||||||
twoFactorEnabled: false,
|
twoFactorEnabled: false,
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ const mockUser = {
|
|||||||
imageUrl: "http://example.com/avatar.png",
|
imageUrl: "http://example.com/avatar.png",
|
||||||
twoFactorEnabled: false,
|
twoFactorEnabled: false,
|
||||||
identityProvider: "email",
|
identityProvider: "email",
|
||||||
notificationSettings: { alert: {}, weeklySummary: {}, unsubscribedOrganizationIds: [] },
|
notificationSettings: { alert: {}, unsubscribedOrganizationIds: [] },
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
role: "project_manager",
|
role: "project_manager",
|
||||||
@@ -121,8 +121,9 @@ describe("ProfilePage", () => {
|
|||||||
expect(screen.getByTestId("account-security")).toBeInTheDocument(); // Shown because 2FA license is enabled
|
expect(screen.getByTestId("account-security")).toBeInTheDocument(); // Shown because 2FA license is enabled
|
||||||
expect(screen.queryByTestId("upgrade-prompt")).not.toBeInTheDocument();
|
expect(screen.queryByTestId("upgrade-prompt")).not.toBeInTheDocument();
|
||||||
expect(screen.getByTestId("delete-account")).toBeInTheDocument();
|
expect(screen.getByTestId("delete-account")).toBeInTheDocument();
|
||||||
// Use a regex to match the text content, allowing for variable whitespace
|
// Check for IdBadge content
|
||||||
expect(screen.getByText(new RegExp(`common\\.profile\\s*:\\s*${mockUser.id}`))).toBeInTheDocument(); // SettingsId
|
expect(screen.getByText("common.profile_id")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(mockUser.id)).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ import { getOrganizationsWhereUserIsSingleOwner } from "@/lib/organization/servi
|
|||||||
import { getUser } from "@/lib/user/service";
|
import { getUser } from "@/lib/user/service";
|
||||||
import { getIsMultiOrgEnabled, getIsTwoFactorAuthEnabled } from "@/modules/ee/license-check/lib/utils";
|
import { getIsMultiOrgEnabled, getIsTwoFactorAuthEnabled } from "@/modules/ee/license-check/lib/utils";
|
||||||
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
|
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
|
||||||
|
import { IdBadge } from "@/modules/ui/components/id-badge";
|
||||||
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
|
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
|
||||||
import { PageHeader } from "@/modules/ui/components/page-header";
|
import { PageHeader } from "@/modules/ui/components/page-header";
|
||||||
import { SettingsId } from "@/modules/ui/components/settings-id";
|
|
||||||
import { UpgradePrompt } from "@/modules/ui/components/upgrade-prompt";
|
import { UpgradePrompt } from "@/modules/ui/components/upgrade-prompt";
|
||||||
import { getTranslate } from "@/tolgee/server";
|
import { getTranslate } from "@/tolgee/server";
|
||||||
import { SettingsCard } from "../../components/SettingsCard";
|
import { SettingsCard } from "../../components/SettingsCard";
|
||||||
@@ -103,7 +103,7 @@ const Page = async (props: { params: Promise<{ environmentId: string }> }) => {
|
|||||||
isMultiOrgEnabled={isMultiOrgEnabled}
|
isMultiOrgEnabled={isMultiOrgEnabled}
|
||||||
/>
|
/>
|
||||||
</SettingsCard>
|
</SettingsCard>
|
||||||
<SettingsId title={t("common.profile")} id={user.id}></SettingsId>
|
<IdBadge id={user.id} label={t("common.profile_id")} variant="column" />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</PageContentWrapper>
|
</PageContentWrapper>
|
||||||
|
|||||||
@@ -129,7 +129,7 @@ const mockUser = {
|
|||||||
imageUrl: "",
|
imageUrl: "",
|
||||||
twoFactorEnabled: false,
|
twoFactorEnabled: false,
|
||||||
identityProvider: "email",
|
identityProvider: "email",
|
||||||
notificationSettings: { alert: {}, weeklySummary: {} },
|
notificationSettings: { alert: {} },
|
||||||
role: "project_manager",
|
role: "project_manager",
|
||||||
objective: "other",
|
objective: "other",
|
||||||
} as unknown as TUser;
|
} as unknown as TUser;
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { getIsMultiOrgEnabled, getWhiteLabelPermission } from "@/modules/ee/lice
|
|||||||
import { EmailCustomizationSettings } from "@/modules/ee/whitelabel/email-customization/components/email-customization-settings";
|
import { EmailCustomizationSettings } from "@/modules/ee/whitelabel/email-customization/components/email-customization-settings";
|
||||||
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
|
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
|
||||||
import { TEnvironmentAuth } from "@/modules/environments/types/environment-auth";
|
import { TEnvironmentAuth } from "@/modules/environments/types/environment-auth";
|
||||||
import { SettingsId } from "@/modules/ui/components/settings-id";
|
import { IdBadge } from "@/modules/ui/components/id-badge";
|
||||||
import { getTranslate } from "@/tolgee/server";
|
import { getTranslate } from "@/tolgee/server";
|
||||||
import { cleanup, render, screen } from "@testing-library/react";
|
import { cleanup, render, screen } from "@testing-library/react";
|
||||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||||
@@ -78,8 +78,8 @@ vi.mock("./components/DeleteOrganization", () => ({
|
|||||||
DeleteOrganization: vi.fn(() => <div>DeleteOrganization</div>),
|
DeleteOrganization: vi.fn(() => <div>DeleteOrganization</div>),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("@/modules/ui/components/settings-id", () => ({
|
vi.mock("@/modules/ui/components/id-badge", () => ({
|
||||||
SettingsId: vi.fn(() => <div>SettingsId</div>),
|
IdBadge: vi.fn(() => <div>IdBadge</div>),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
describe("Page", () => {
|
describe("Page", () => {
|
||||||
@@ -156,10 +156,11 @@ describe("Page", () => {
|
|||||||
},
|
},
|
||||||
undefined
|
undefined
|
||||||
);
|
);
|
||||||
expect(SettingsId).toHaveBeenCalledWith(
|
expect(IdBadge).toHaveBeenCalledWith(
|
||||||
{
|
{
|
||||||
title: "common.organization_id",
|
|
||||||
id: mockEnvironmentAuth.organization.id,
|
id: mockEnvironmentAuth.organization.id,
|
||||||
|
label: "common.organization_id",
|
||||||
|
variant: "column",
|
||||||
},
|
},
|
||||||
undefined
|
undefined
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ import { getUser } from "@/lib/user/service";
|
|||||||
import { getIsMultiOrgEnabled, getWhiteLabelPermission } from "@/modules/ee/license-check/lib/utils";
|
import { getIsMultiOrgEnabled, getWhiteLabelPermission } from "@/modules/ee/license-check/lib/utils";
|
||||||
import { EmailCustomizationSettings } from "@/modules/ee/whitelabel/email-customization/components/email-customization-settings";
|
import { EmailCustomizationSettings } from "@/modules/ee/whitelabel/email-customization/components/email-customization-settings";
|
||||||
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
|
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
|
||||||
|
import { IdBadge } from "@/modules/ui/components/id-badge";
|
||||||
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
|
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
|
||||||
import { PageHeader } from "@/modules/ui/components/page-header";
|
import { PageHeader } from "@/modules/ui/components/page-header";
|
||||||
import { SettingsId } from "@/modules/ui/components/settings-id";
|
|
||||||
import { getTranslate } from "@/tolgee/server";
|
import { getTranslate } from "@/tolgee/server";
|
||||||
import { SettingsCard } from "../../components/SettingsCard";
|
import { SettingsCard } from "../../components/SettingsCard";
|
||||||
import { DeleteOrganization } from "./components/DeleteOrganization";
|
import { DeleteOrganization } from "./components/DeleteOrganization";
|
||||||
@@ -70,7 +70,7 @@ const Page = async (props: { params: Promise<{ environmentId: string }> }) => {
|
|||||||
</SettingsCard>
|
</SettingsCard>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<SettingsId title={t("common.organization_id")} id={organization.id}></SettingsId>
|
<IdBadge id={organization.id} label={t("common.organization_id")} variant="column" />
|
||||||
</PageContentWrapper>
|
</PageContentWrapper>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -58,7 +58,6 @@ vi.mock("@/lib/env", () => ({
|
|||||||
vi.mock("@/app/(app)/environments/[environmentId]/components/ResponseFilterContext");
|
vi.mock("@/app/(app)/environments/[environmentId]/components/ResponseFilterContext");
|
||||||
vi.mock("@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/actions");
|
vi.mock("@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/actions");
|
||||||
vi.mock("@/app/lib/surveys/surveys");
|
vi.mock("@/app/lib/surveys/surveys");
|
||||||
vi.mock("@/app/share/[sharingKey]/actions");
|
|
||||||
vi.mock("@/modules/ui/components/secondary-navigation", () => ({
|
vi.mock("@/modules/ui/components/secondary-navigation", () => ({
|
||||||
SecondaryNavigation: vi.fn(() => <div data-testid="secondary-navigation" />),
|
SecondaryNavigation: vi.fn(() => <div data-testid="secondary-navigation" />),
|
||||||
}));
|
}));
|
||||||
@@ -112,7 +111,6 @@ const mockSurvey = {
|
|||||||
surveyClosedMessage: null,
|
surveyClosedMessage: null,
|
||||||
welcomeCard: { enabled: false, headline: { default: "" } } as unknown as TSurvey["welcomeCard"],
|
welcomeCard: { enabled: false, headline: { default: "" } } as unknown as TSurvey["welcomeCard"],
|
||||||
segment: null,
|
segment: null,
|
||||||
resultShareKey: null,
|
|
||||||
closeOnDate: null,
|
closeOnDate: null,
|
||||||
delay: 0,
|
delay: 0,
|
||||||
autoComplete: null,
|
autoComplete: null,
|
||||||
@@ -171,22 +169,6 @@ describe("SurveyAnalysisNavigation", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("renders navigation correctly for sharing page", () => {
|
|
||||||
mockUsePathname.mockReturnValue(
|
|
||||||
`/environments/${defaultProps.environmentId}/surveys/${mockSurvey.id}/summary`
|
|
||||||
);
|
|
||||||
mockUseParams.mockReturnValue({ sharingKey: "test-sharing-key" });
|
|
||||||
mockUseResponseFilter.mockReturnValue({ selectedFilter: "all", dateRange: {} } as any);
|
|
||||||
mockGetFormattedFilters.mockReturnValue([] as any);
|
|
||||||
mockGetResponseCountAction.mockResolvedValue({ data: 5 });
|
|
||||||
|
|
||||||
render(<SurveyAnalysisNavigation {...defaultProps} />);
|
|
||||||
|
|
||||||
expect(MockSecondaryNavigation).toHaveBeenCalled();
|
|
||||||
const lastCallArgs = MockSecondaryNavigation.mock.calls[MockSecondaryNavigation.mock.calls.length - 1][0];
|
|
||||||
expect(lastCallArgs.navigation[0].href).toContain("/share/test-sharing-key");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("displays correct response count string in label for various scenarios", async () => {
|
test("displays correct response count string in label for various scenarios", async () => {
|
||||||
mockUsePathname.mockReturnValue(
|
mockUsePathname.mockReturnValue(
|
||||||
`/environments/${defaultProps.environmentId}/surveys/${mockSurvey.id}/responses`
|
`/environments/${defaultProps.environmentId}/surveys/${mockSurvey.id}/responses`
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { revalidateSurveyIdPath } from "@/app/(app)/environments/[environmentId]
|
|||||||
import { SecondaryNavigation } from "@/modules/ui/components/secondary-navigation";
|
import { SecondaryNavigation } from "@/modules/ui/components/secondary-navigation";
|
||||||
import { useTranslate } from "@tolgee/react";
|
import { useTranslate } from "@tolgee/react";
|
||||||
import { InboxIcon, PresentationIcon } from "lucide-react";
|
import { InboxIcon, PresentationIcon } from "lucide-react";
|
||||||
import { useParams, usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
import { TSurvey } from "@formbricks/types/surveys/types";
|
import { TSurvey } from "@formbricks/types/surveys/types";
|
||||||
|
|
||||||
interface SurveyAnalysisNavigationProps {
|
interface SurveyAnalysisNavigationProps {
|
||||||
@@ -20,11 +20,8 @@ export const SurveyAnalysisNavigation = ({
|
|||||||
}: SurveyAnalysisNavigationProps) => {
|
}: SurveyAnalysisNavigationProps) => {
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const { t } = useTranslate();
|
const { t } = useTranslate();
|
||||||
const params = useParams();
|
|
||||||
const sharingKey = params.sharingKey as string;
|
|
||||||
const isSharingPage = !!sharingKey;
|
|
||||||
|
|
||||||
const url = isSharingPage ? `/share/${sharingKey}` : `/environments/${environmentId}/surveys/${survey.id}`;
|
const url = `/environments/${environmentId}/surveys/${survey.id}`;
|
||||||
|
|
||||||
const navigation = [
|
const navigation = [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -50,7 +50,6 @@ const mockSurvey = {
|
|||||||
isBackButtonHidden: false,
|
isBackButtonHidden: false,
|
||||||
pin: null,
|
pin: null,
|
||||||
recontactDays: null,
|
recontactDays: null,
|
||||||
resultShareKey: null,
|
|
||||||
runOnDate: null,
|
runOnDate: null,
|
||||||
showLanguageSwitch: false,
|
showLanguageSwitch: false,
|
||||||
singleUse: null,
|
singleUse: null,
|
||||||
|
|||||||
@@ -60,7 +60,6 @@ const mockResponses = [
|
|||||||
userAgent: { browser: "Chrome", os: "Mac OS", device: "Desktop" },
|
userAgent: { browser: "Chrome", os: "Mac OS", device: "Desktop" },
|
||||||
url: "http://localhost:3000",
|
url: "http://localhost:3000",
|
||||||
},
|
},
|
||||||
notes: [],
|
|
||||||
tags: [],
|
tags: [],
|
||||||
} as unknown as TResponse,
|
} as unknown as TResponse,
|
||||||
{
|
{
|
||||||
@@ -74,7 +73,6 @@ const mockResponses = [
|
|||||||
userAgent: { browser: "Firefox", os: "Windows", device: "Desktop" },
|
userAgent: { browser: "Firefox", os: "Windows", device: "Desktop" },
|
||||||
url: "http://localhost:3000/page2",
|
url: "http://localhost:3000/page2",
|
||||||
},
|
},
|
||||||
notes: [],
|
|
||||||
tags: [],
|
tags: [],
|
||||||
} as unknown as TResponse,
|
} as unknown as TResponse,
|
||||||
{
|
{
|
||||||
@@ -88,7 +86,6 @@ const mockResponses = [
|
|||||||
userAgent: { browser: "Safari", os: "iOS", device: "Mobile" },
|
userAgent: { browser: "Safari", os: "iOS", device: "Mobile" },
|
||||||
url: "http://localhost:3000/page3",
|
url: "http://localhost:3000/page3",
|
||||||
},
|
},
|
||||||
notes: [],
|
|
||||||
tags: [],
|
tags: [],
|
||||||
} as unknown as TResponse,
|
} as unknown as TResponse,
|
||||||
] as unknown as TResponse[];
|
] as unknown as TResponse[];
|
||||||
@@ -113,7 +110,6 @@ const mockSurvey = {
|
|||||||
singleUse: null,
|
singleUse: null,
|
||||||
triggers: [],
|
triggers: [],
|
||||||
languages: [],
|
languages: [],
|
||||||
resultShareKey: null,
|
|
||||||
displayPercentage: null,
|
displayPercentage: null,
|
||||||
welcomeCard: { enabled: false, headline: { default: "Welcome!" } } as unknown as TSurvey["welcomeCard"],
|
welcomeCard: { enabled: false, headline: { default: "Welcome!" } } as unknown as TSurvey["welcomeCard"],
|
||||||
styling: null,
|
styling: null,
|
||||||
@@ -139,7 +135,7 @@ const mockUser = {
|
|||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
role: "project_manager",
|
role: "project_manager",
|
||||||
objective: "increase_conversion",
|
objective: "increase_conversion",
|
||||||
notificationSettings: { alert: {}, weeklySummary: {}, unsubscribedOrganizationIds: [] },
|
notificationSettings: { alert: {}, unsubscribedOrganizationIds: [] },
|
||||||
} as unknown as TUser;
|
} as unknown as TUser;
|
||||||
|
|
||||||
const mockEnvironmentTags: TTag[] = [
|
const mockEnvironmentTags: TTag[] = [
|
||||||
|
|||||||
@@ -82,7 +82,6 @@ export const ResponseCardModal = ({
|
|||||||
survey={survey}
|
survey={survey}
|
||||||
response={responses[currentIndex]}
|
response={responses[currentIndex]}
|
||||||
user={user}
|
user={user}
|
||||||
pageType="response"
|
|
||||||
environment={environment}
|
environment={environment}
|
||||||
environmentTags={environmentTags}
|
environmentTags={environmentTags}
|
||||||
isReadOnly={isReadOnly}
|
isReadOnly={isReadOnly}
|
||||||
|
|||||||
@@ -88,7 +88,6 @@ const mockSurvey = {
|
|||||||
surveyClosedMessage: null,
|
surveyClosedMessage: null,
|
||||||
triggers: [],
|
triggers: [],
|
||||||
languages: [],
|
languages: [],
|
||||||
resultShareKey: null,
|
|
||||||
displayPercentage: null,
|
displayPercentage: null,
|
||||||
} as unknown as TSurvey;
|
} as unknown as TSurvey;
|
||||||
|
|
||||||
@@ -118,17 +117,6 @@ const mockResponses: TResponse[] = [
|
|||||||
singleUseId: null,
|
singleUseId: null,
|
||||||
ttc: {},
|
ttc: {},
|
||||||
tags: [{ id: "tag1", name: "Tag1", environmentId: "env1", createdAt: new Date(), updatedAt: new Date() }],
|
tags: [{ id: "tag1", name: "Tag1", environmentId: "env1", createdAt: new Date(), updatedAt: new Date() }],
|
||||||
notes: [
|
|
||||||
{
|
|
||||||
id: "note1",
|
|
||||||
text: "Note 1",
|
|
||||||
createdAt: new Date(),
|
|
||||||
updatedAt: new Date(),
|
|
||||||
isResolved: false,
|
|
||||||
isEdited: false,
|
|
||||||
user: { id: "user1", name: "User 1" },
|
|
||||||
},
|
|
||||||
],
|
|
||||||
variables: { var1: "Response Var Value" },
|
variables: { var1: "Response Var Value" },
|
||||||
language: "en",
|
language: "en",
|
||||||
contact: null,
|
contact: null,
|
||||||
@@ -145,7 +133,6 @@ const mockResponses: TResponse[] = [
|
|||||||
singleUseId: null,
|
singleUseId: null,
|
||||||
ttc: {},
|
ttc: {},
|
||||||
tags: [],
|
tags: [],
|
||||||
notes: [],
|
|
||||||
variables: {},
|
variables: {},
|
||||||
language: "de",
|
language: "de",
|
||||||
contact: null,
|
contact: null,
|
||||||
@@ -235,12 +222,17 @@ describe("ResponseDataView", () => {
|
|||||||
status: "Completed",
|
status: "Completed",
|
||||||
responseId: "response1",
|
responseId: "response1",
|
||||||
tags: mockResponses[0].tags,
|
tags: mockResponses[0].tags,
|
||||||
notes: mockResponses[0].notes,
|
|
||||||
variables: { var1: "Response Var Value" },
|
variables: { var1: "Response Var Value" },
|
||||||
verifiedEmail: "test@example.com",
|
verifiedEmail: "test@example.com",
|
||||||
language: "en",
|
language: "en",
|
||||||
person: null,
|
person: null,
|
||||||
contactAttributes: null,
|
contactAttributes: null,
|
||||||
|
meta: {
|
||||||
|
url: "http://localhost",
|
||||||
|
userAgent: {
|
||||||
|
browser: "test-agent",
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
responseData: {
|
responseData: {
|
||||||
@@ -250,12 +242,17 @@ describe("ResponseDataView", () => {
|
|||||||
status: "Not Completed",
|
status: "Not Completed",
|
||||||
responseId: "response2",
|
responseId: "response2",
|
||||||
tags: [],
|
tags: [],
|
||||||
notes: [],
|
|
||||||
variables: {},
|
variables: {},
|
||||||
verifiedEmail: "",
|
verifiedEmail: "",
|
||||||
language: "de",
|
language: "de",
|
||||||
person: null,
|
person: null,
|
||||||
contactAttributes: null,
|
contactAttributes: null,
|
||||||
|
meta: {
|
||||||
|
url: "http://localhost",
|
||||||
|
userAgent: {
|
||||||
|
browser: "test-agent-2",
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -90,7 +90,6 @@ export const mapResponsesToTableData = (
|
|||||||
: t("environments.surveys.responses.not_completed"),
|
: t("environments.surveys.responses.not_completed"),
|
||||||
responseId: response.id,
|
responseId: response.id,
|
||||||
tags: response.tags,
|
tags: response.tags,
|
||||||
notes: response.notes,
|
|
||||||
variables: survey.variables.reduce(
|
variables: survey.variables.reduce(
|
||||||
(acc, curr) => {
|
(acc, curr) => {
|
||||||
return Object.assign(acc, { [curr.id]: response.variables[curr.id] });
|
return Object.assign(acc, { [curr.id]: response.variables[curr.id] });
|
||||||
@@ -101,6 +100,7 @@ export const mapResponsesToTableData = (
|
|||||||
language: response.language,
|
language: response.language,
|
||||||
person: response.contact,
|
person: response.contact,
|
||||||
contactAttributes: response.contactAttributes,
|
contactAttributes: response.contactAttributes,
|
||||||
|
meta: response.meta,
|
||||||
}));
|
}));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -28,19 +28,10 @@ vi.mock("@/app/(app)/environments/[environmentId]/surveys/[surveyId]/components/
|
|||||||
CustomFilter: vi.fn(() => <div data-testid="custom-filter">CustomFilter</div>),
|
CustomFilter: vi.fn(() => <div data-testid="custom-filter">CustomFilter</div>),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("@/app/(app)/environments/[environmentId]/surveys/[surveyId]/components/ResultsShareButton", () => ({
|
|
||||||
ResultsShareButton: vi.fn(() => <div data-testid="results-share-button">ResultsShareButton</div>),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock("@/app/lib/surveys/surveys", () => ({
|
vi.mock("@/app/lib/surveys/surveys", () => ({
|
||||||
getFormattedFilters: vi.fn(),
|
getFormattedFilters: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("@/app/share/[sharingKey]/actions", () => ({
|
|
||||||
getResponseCountBySurveySharingKeyAction: vi.fn(),
|
|
||||||
getResponsesBySurveySharingKeyAction: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock("@/lib/utils/recall", () => ({
|
vi.mock("@/lib/utils/recall", () => ({
|
||||||
replaceHeadlineRecall: vi.fn((survey) => survey),
|
replaceHeadlineRecall: vi.fn((survey) => survey),
|
||||||
}));
|
}));
|
||||||
@@ -64,12 +55,6 @@ const mockGetResponseCountAction = vi.mocked(
|
|||||||
(await import("@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/actions"))
|
(await import("@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/actions"))
|
||||||
.getResponseCountAction
|
.getResponseCountAction
|
||||||
);
|
);
|
||||||
const mockGetResponsesBySurveySharingKeyAction = vi.mocked(
|
|
||||||
(await import("@/app/share/[sharingKey]/actions")).getResponsesBySurveySharingKeyAction
|
|
||||||
);
|
|
||||||
const mockGetResponseCountBySurveySharingKeyAction = vi.mocked(
|
|
||||||
(await import("@/app/share/[sharingKey]/actions")).getResponseCountBySurveySharingKeyAction
|
|
||||||
);
|
|
||||||
const mockUseParams = vi.mocked((await import("next/navigation")).useParams);
|
const mockUseParams = vi.mocked((await import("next/navigation")).useParams);
|
||||||
const mockUseSearchParams = vi.mocked((await import("next/navigation")).useSearchParams);
|
const mockUseSearchParams = vi.mocked((await import("next/navigation")).useSearchParams);
|
||||||
const mockGetFormattedFilters = vi.mocked((await import("@/app/lib/surveys/surveys")).getFormattedFilters);
|
const mockGetFormattedFilters = vi.mocked((await import("@/app/lib/surveys/surveys")).getFormattedFilters);
|
||||||
@@ -122,7 +107,6 @@ const mockResponses: TResponse[] = [
|
|||||||
finished: true,
|
finished: true,
|
||||||
data: {},
|
data: {},
|
||||||
meta: { userAgent: {} },
|
meta: { userAgent: {} },
|
||||||
notes: [],
|
|
||||||
tags: [],
|
tags: [],
|
||||||
} as unknown as TResponse,
|
} as unknown as TResponse,
|
||||||
{
|
{
|
||||||
@@ -133,7 +117,6 @@ const mockResponses: TResponse[] = [
|
|||||||
finished: true,
|
finished: true,
|
||||||
data: {},
|
data: {},
|
||||||
meta: { userAgent: {} },
|
meta: { userAgent: {} },
|
||||||
notes: [],
|
|
||||||
tags: [],
|
tags: [],
|
||||||
} as unknown as TResponse,
|
} as unknown as TResponse,
|
||||||
];
|
];
|
||||||
@@ -150,8 +133,6 @@ describe("ResponsePage", () => {
|
|||||||
mockUseResponseFilter.mockReturnValue(mockResponseFilterState);
|
mockUseResponseFilter.mockReturnValue(mockResponseFilterState);
|
||||||
mockGetResponsesAction.mockResolvedValue({ data: mockResponses });
|
mockGetResponsesAction.mockResolvedValue({ data: mockResponses });
|
||||||
mockGetResponseCountAction.mockResolvedValue({ data: 20 });
|
mockGetResponseCountAction.mockResolvedValue({ data: 20 });
|
||||||
mockGetResponsesBySurveySharingKeyAction.mockResolvedValue({ data: mockResponses });
|
|
||||||
mockGetResponseCountBySurveySharingKeyAction.mockResolvedValue({ data: 20 });
|
|
||||||
mockGetFormattedFilters.mockReturnValue({});
|
mockGetFormattedFilters.mockReturnValue({});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -159,28 +140,11 @@ describe("ResponsePage", () => {
|
|||||||
render(<ResponsePage {...defaultProps} />);
|
render(<ResponsePage {...defaultProps} />);
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(screen.getByTestId("custom-filter")).toBeInTheDocument();
|
expect(screen.getByTestId("custom-filter")).toBeInTheDocument();
|
||||||
expect(screen.getByTestId("results-share-button")).toBeInTheDocument();
|
|
||||||
expect(screen.getByTestId("response-data-view")).toBeInTheDocument();
|
expect(screen.getByTestId("response-data-view")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
expect(mockGetResponsesAction).toHaveBeenCalled();
|
expect(mockGetResponsesAction).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("does not render ResultsShareButton when isReadOnly is true", async () => {
|
|
||||||
render(<ResponsePage {...defaultProps} isReadOnly={true} />);
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.queryByTestId("results-share-button")).not.toBeInTheDocument();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test("does not render ResultsShareButton when on sharing page", async () => {
|
|
||||||
mockUseParams.mockReturnValue({ sharingKey: "share123" });
|
|
||||||
render(<ResponsePage {...defaultProps} />);
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.queryByTestId("results-share-button")).not.toBeInTheDocument();
|
|
||||||
});
|
|
||||||
expect(mockGetResponsesBySurveySharingKeyAction).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("fetches next page of responses", async () => {
|
test("fetches next page of responses", async () => {
|
||||||
const { rerender } = render(<ResponsePage {...defaultProps} />);
|
const { rerender } = render(<ResponsePage {...defaultProps} />);
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
|||||||
@@ -4,11 +4,9 @@ import { useResponseFilter } from "@/app/(app)/environments/[environmentId]/comp
|
|||||||
import { getResponsesAction } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/actions";
|
import { getResponsesAction } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/actions";
|
||||||
import { ResponseDataView } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponseDataView";
|
import { ResponseDataView } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponseDataView";
|
||||||
import { CustomFilter } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/components/CustomFilter";
|
import { CustomFilter } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/components/CustomFilter";
|
||||||
import { ResultsShareButton } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/components/ResultsShareButton";
|
|
||||||
import { getFormattedFilters } from "@/app/lib/surveys/surveys";
|
import { getFormattedFilters } from "@/app/lib/surveys/surveys";
|
||||||
import { getResponsesBySurveySharingKeyAction } from "@/app/share/[sharingKey]/actions";
|
|
||||||
import { replaceHeadlineRecall } from "@/lib/utils/recall";
|
import { replaceHeadlineRecall } from "@/lib/utils/recall";
|
||||||
import { useParams, useSearchParams } from "next/navigation";
|
import { useSearchParams } from "next/navigation";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { TEnvironment } from "@formbricks/types/environment";
|
import { TEnvironment } from "@formbricks/types/environment";
|
||||||
import { TResponse } from "@formbricks/types/responses";
|
import { TResponse } from "@formbricks/types/responses";
|
||||||
@@ -20,7 +18,6 @@ interface ResponsePageProps {
|
|||||||
environment: TEnvironment;
|
environment: TEnvironment;
|
||||||
survey: TSurvey;
|
survey: TSurvey;
|
||||||
surveyId: string;
|
surveyId: string;
|
||||||
publicDomain: string;
|
|
||||||
user?: TUser;
|
user?: TUser;
|
||||||
environmentTags: TTag[];
|
environmentTags: TTag[];
|
||||||
responsesPerPage: number;
|
responsesPerPage: number;
|
||||||
@@ -32,17 +29,12 @@ export const ResponsePage = ({
|
|||||||
environment,
|
environment,
|
||||||
survey,
|
survey,
|
||||||
surveyId,
|
surveyId,
|
||||||
publicDomain,
|
|
||||||
user,
|
user,
|
||||||
environmentTags,
|
environmentTags,
|
||||||
responsesPerPage,
|
responsesPerPage,
|
||||||
locale,
|
locale,
|
||||||
isReadOnly,
|
isReadOnly,
|
||||||
}: ResponsePageProps) => {
|
}: ResponsePageProps) => {
|
||||||
const params = useParams();
|
|
||||||
const sharingKey = params.sharingKey as string;
|
|
||||||
const isSharingPage = !!sharingKey;
|
|
||||||
|
|
||||||
const [responses, setResponses] = useState<TResponse[]>([]);
|
const [responses, setResponses] = useState<TResponse[]>([]);
|
||||||
const [page, setPage] = useState<number>(1);
|
const [page, setPage] = useState<number>(1);
|
||||||
const [hasMore, setHasMore] = useState<boolean>(true);
|
const [hasMore, setHasMore] = useState<boolean>(true);
|
||||||
@@ -63,30 +55,20 @@ export const ResponsePage = ({
|
|||||||
|
|
||||||
let newResponses: TResponse[] = [];
|
let newResponses: TResponse[] = [];
|
||||||
|
|
||||||
if (isSharingPage) {
|
const getResponsesActionResponse = await getResponsesAction({
|
||||||
const getResponsesActionResponse = await getResponsesBySurveySharingKeyAction({
|
surveyId,
|
||||||
sharingKey: sharingKey,
|
limit: responsesPerPage,
|
||||||
limit: responsesPerPage,
|
offset: (newPage - 1) * responsesPerPage,
|
||||||
offset: (newPage - 1) * responsesPerPage,
|
filterCriteria: filters,
|
||||||
filterCriteria: filters,
|
});
|
||||||
});
|
newResponses = getResponsesActionResponse?.data || [];
|
||||||
newResponses = getResponsesActionResponse?.data || [];
|
|
||||||
} else {
|
|
||||||
const getResponsesActionResponse = await getResponsesAction({
|
|
||||||
surveyId,
|
|
||||||
limit: responsesPerPage,
|
|
||||||
offset: (newPage - 1) * responsesPerPage,
|
|
||||||
filterCriteria: filters,
|
|
||||||
});
|
|
||||||
newResponses = getResponsesActionResponse?.data || [];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (newResponses.length === 0 || newResponses.length < responsesPerPage) {
|
if (newResponses.length === 0 || newResponses.length < responsesPerPage) {
|
||||||
setHasMore(false);
|
setHasMore(false);
|
||||||
}
|
}
|
||||||
setResponses([...responses, ...newResponses]);
|
setResponses([...responses, ...newResponses]);
|
||||||
setPage(newPage);
|
setPage(newPage);
|
||||||
}, [filters, isSharingPage, page, responses, responsesPerPage, sharingKey, surveyId]);
|
}, [filters, page, responses, responsesPerPage, surveyId]);
|
||||||
|
|
||||||
const deleteResponses = (responseIds: string[]) => {
|
const deleteResponses = (responseIds: string[]) => {
|
||||||
setResponses(responses.filter((response) => !responseIds.includes(response.id)));
|
setResponses(responses.filter((response) => !responseIds.includes(response.id)));
|
||||||
@@ -114,25 +96,14 @@ export const ResponsePage = ({
|
|||||||
setFetchingFirstPage(true);
|
setFetchingFirstPage(true);
|
||||||
let responses: TResponse[] = [];
|
let responses: TResponse[] = [];
|
||||||
|
|
||||||
if (isSharingPage) {
|
const getResponsesActionResponse = await getResponsesAction({
|
||||||
const getResponsesActionResponse = await getResponsesBySurveySharingKeyAction({
|
surveyId,
|
||||||
sharingKey,
|
limit: responsesPerPage,
|
||||||
limit: responsesPerPage,
|
offset: 0,
|
||||||
offset: 0,
|
filterCriteria: filters,
|
||||||
filterCriteria: filters,
|
});
|
||||||
});
|
|
||||||
|
|
||||||
responses = getResponsesActionResponse?.data || [];
|
responses = getResponsesActionResponse?.data || [];
|
||||||
} else {
|
|
||||||
const getResponsesActionResponse = await getResponsesAction({
|
|
||||||
surveyId,
|
|
||||||
limit: responsesPerPage,
|
|
||||||
offset: 0,
|
|
||||||
filterCriteria: filters,
|
|
||||||
});
|
|
||||||
|
|
||||||
responses = getResponsesActionResponse?.data || [];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (responses.length < responsesPerPage) {
|
if (responses.length < responsesPerPage) {
|
||||||
setHasMore(false);
|
setHasMore(false);
|
||||||
@@ -143,7 +114,7 @@ export const ResponsePage = ({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
fetchInitialResponses();
|
fetchInitialResponses();
|
||||||
}, [surveyId, filters, responsesPerPage, sharingKey, isSharingPage]);
|
}, [surveyId, filters, responsesPerPage]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setPage(1);
|
setPage(1);
|
||||||
@@ -155,7 +126,6 @@ export const ResponsePage = ({
|
|||||||
<>
|
<>
|
||||||
<div className="flex gap-1.5">
|
<div className="flex gap-1.5">
|
||||||
<CustomFilter survey={surveyMemoized} />
|
<CustomFilter survey={surveyMemoized} />
|
||||||
{!isReadOnly && !isSharingPage && <ResultsShareButton survey={survey} publicDomain={publicDomain} />}
|
|
||||||
</div>
|
</div>
|
||||||
<ResponseDataView
|
<ResponseDataView
|
||||||
survey={survey}
|
survey={survey}
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
|
import { extractChoiceIdsFromResponse } from "@/lib/response/utils";
|
||||||
import { processResponseData } from "@/lib/responses";
|
import { processResponseData } from "@/lib/responses";
|
||||||
import { getContactIdentifier } from "@/lib/utils/contact";
|
import { getContactIdentifier } from "@/lib/utils/contact";
|
||||||
import { getFormattedDateTimeString } from "@/lib/utils/datetime";
|
import { getFormattedDateTimeString } from "@/lib/utils/datetime";
|
||||||
import { getSelectionColumn } from "@/modules/ui/components/data-table";
|
import { getSelectionColumn } from "@/modules/ui/components/data-table";
|
||||||
import { ResponseBadges } from "@/modules/ui/components/response-badges";
|
|
||||||
import { cleanup } from "@testing-library/react";
|
import { cleanup } from "@testing-library/react";
|
||||||
import { AnyActionArg } from "react";
|
|
||||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||||
import { TResponseNote, TResponseNoteUser, TResponseTableData } from "@formbricks/types/responses";
|
import { TResponseTableData } from "@formbricks/types/responses";
|
||||||
import {
|
import {
|
||||||
TSurvey,
|
TSurvey,
|
||||||
TSurveyQuestion,
|
TSurveyQuestion,
|
||||||
@@ -60,6 +59,7 @@ vi.mock("@/modules/survey/lib/questions", () => ({
|
|||||||
getQuestionIconMap: vi.fn(() => ({
|
getQuestionIconMap: vi.fn(() => ({
|
||||||
[TSurveyQuestionTypeEnum.OpenText]: <span>OT</span>,
|
[TSurveyQuestionTypeEnum.OpenText]: <span>OT</span>,
|
||||||
[TSurveyQuestionTypeEnum.MultipleChoiceSingle]: <span>MCS</span>,
|
[TSurveyQuestionTypeEnum.MultipleChoiceSingle]: <span>MCS</span>,
|
||||||
|
[TSurveyQuestionTypeEnum.MultipleChoiceMulti]: <span>MCM</span>,
|
||||||
[TSurveyQuestionTypeEnum.Matrix]: <span>MX</span>,
|
[TSurveyQuestionTypeEnum.Matrix]: <span>MX</span>,
|
||||||
[TSurveyQuestionTypeEnum.Address]: <span>AD</span>,
|
[TSurveyQuestionTypeEnum.Address]: <span>AD</span>,
|
||||||
[TSurveyQuestionTypeEnum.ContactInfo]: <span>CI</span>,
|
[TSurveyQuestionTypeEnum.ContactInfo]: <span>CI</span>,
|
||||||
@@ -102,6 +102,33 @@ vi.mock("lucide-react", () => ({
|
|||||||
EyeOffIcon: () => <span>EyeOff</span>,
|
EyeOffIcon: () => <span>EyeOff</span>,
|
||||||
MailIcon: () => <span>Mail</span>,
|
MailIcon: () => <span>Mail</span>,
|
||||||
TagIcon: () => <span>Tag</span>,
|
TagIcon: () => <span>Tag</span>,
|
||||||
|
MousePointerClickIcon: () => <span>MousePointerClick</span>,
|
||||||
|
AirplayIcon: () => <span>Airplay</span>,
|
||||||
|
ArrowUpFromDotIcon: () => <span>ArrowUpFromDot</span>,
|
||||||
|
FlagIcon: () => <span>Flag</span>,
|
||||||
|
GlobeIcon: () => <span>Globe</span>,
|
||||||
|
SmartphoneIcon: () => <span>Smartphone</span>,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mock new dependencies
|
||||||
|
vi.mock("@/lib/response/utils", () => ({
|
||||||
|
extractChoiceIdsFromResponse: vi.fn((responseValue) => {
|
||||||
|
// Mock implementation that returns choice IDs based on response value
|
||||||
|
if (Array.isArray(responseValue)) {
|
||||||
|
return responseValue.map((_, index) => `choice-${index + 1}`);
|
||||||
|
} else if (typeof responseValue === "string") {
|
||||||
|
return [`choice-single`];
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/modules/ui/components/id-badge", () => ({
|
||||||
|
IdBadge: vi.fn(({ id }) => <div data-testid="id-badge">{id}</div>),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/modules/ui/lib/utils", () => ({
|
||||||
|
cn: vi.fn((...classes) => classes.filter(Boolean).join(" ")),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const mockSurvey = {
|
const mockSurvey = {
|
||||||
@@ -136,6 +163,28 @@ const mockSurvey = {
|
|||||||
headline: { default: "Contact Info Question" },
|
headline: { default: "Contact Info Question" },
|
||||||
required: false,
|
required: false,
|
||||||
} as unknown as TSurveyQuestion,
|
} as unknown as TSurveyQuestion,
|
||||||
|
{
|
||||||
|
id: "q5single",
|
||||||
|
type: TSurveyQuestionTypeEnum.MultipleChoiceSingle,
|
||||||
|
headline: { default: "Single Choice Question" },
|
||||||
|
required: false,
|
||||||
|
choices: [
|
||||||
|
{ id: "choice-1", label: { default: "Option 1" } },
|
||||||
|
{ id: "choice-2", label: { default: "Option 2" } },
|
||||||
|
{ id: "choice-3", label: { default: "Option 3" } },
|
||||||
|
],
|
||||||
|
} as unknown as TSurveyQuestion,
|
||||||
|
{
|
||||||
|
id: "q6multi",
|
||||||
|
type: TSurveyQuestionTypeEnum.MultipleChoiceMulti,
|
||||||
|
headline: { default: "Multi Choice Question" },
|
||||||
|
required: false,
|
||||||
|
choices: [
|
||||||
|
{ id: "choice-a", label: { default: "Choice A" } },
|
||||||
|
{ id: "choice-b", label: { default: "Choice B" } },
|
||||||
|
{ id: "choice-c", label: { default: "Choice C" } },
|
||||||
|
],
|
||||||
|
} as unknown as TSurveyQuestion,
|
||||||
],
|
],
|
||||||
variables: [
|
variables: [
|
||||||
{ id: "var1", name: "User Segment", type: "text" } as TSurveyVariable,
|
{ id: "var1", name: "User Segment", type: "text" } as TSurveyVariable,
|
||||||
@@ -156,7 +205,6 @@ const mockSurvey = {
|
|||||||
projectOverwrites: null,
|
projectOverwrites: null,
|
||||||
singleUse: null,
|
singleUse: null,
|
||||||
pin: null,
|
pin: null,
|
||||||
resultShareKey: null,
|
|
||||||
surveyClosedMessage: null,
|
surveyClosedMessage: null,
|
||||||
welcomeCard: {
|
welcomeCard: {
|
||||||
enabled: false,
|
enabled: false,
|
||||||
@@ -174,19 +222,13 @@ const mockResponseData = {
|
|||||||
firstName: "John",
|
firstName: "John",
|
||||||
email: "john.doe@example.com",
|
email: "john.doe@example.com",
|
||||||
hf1: "Hidden Field 1 Value",
|
hf1: "Hidden Field 1 Value",
|
||||||
|
q5single: "Option 1", // Single choice response
|
||||||
|
q6multi: ["Choice A", "Choice C"], // Multi choice response
|
||||||
},
|
},
|
||||||
variables: {
|
variables: {
|
||||||
var1: "Segment A",
|
var1: "Segment A",
|
||||||
var2: 100,
|
var2: 100,
|
||||||
},
|
},
|
||||||
notes: [
|
|
||||||
{
|
|
||||||
id: "note1",
|
|
||||||
text: "This is a note",
|
|
||||||
updatedAt: new Date(),
|
|
||||||
user: { name: "User" } as unknown as TResponseNoteUser,
|
|
||||||
} as TResponseNote,
|
|
||||||
],
|
|
||||||
status: "completed",
|
status: "completed",
|
||||||
tags: [{ id: "tag1", name: "Important" } as unknown as TTag],
|
tags: [{ id: "tag1", name: "Important" } as unknown as TTag],
|
||||||
language: "default",
|
language: "default",
|
||||||
@@ -252,14 +294,6 @@ describe("generateResponseTableColumns", () => {
|
|||||||
const hf1Col = columns.find((col) => (col as any).accessorKey === "hf1");
|
const hf1Col = columns.find((col) => (col as any).accessorKey === "hf1");
|
||||||
expect(hf1Col).toBeUndefined();
|
expect(hf1Col).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("should generate Notes column", () => {
|
|
||||||
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
|
||||||
const notesCol = columns.find((col) => (col as any).accessorKey === "notes");
|
|
||||||
expect(notesCol).toBeDefined();
|
|
||||||
(notesCol?.cell as any)?.({ row: { original: mockResponseData } } as any);
|
|
||||||
expect(vi.mocked(processResponseData)).toHaveBeenCalledWith(["This is a note"]);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("ResponseTableColumns", () => {
|
describe("ResponseTableColumns", () => {
|
||||||
@@ -399,36 +433,6 @@ describe("ResponseTableColumns - Column Implementations", () => {
|
|||||||
expect(cellResult).toBeUndefined();
|
expect(cellResult).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("notesColumn renders when notes is an array", () => {
|
|
||||||
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
|
||||||
const notesColumn: any = columns.find((col) => (col as any).accessorKey === "notes");
|
|
||||||
expect(notesColumn).toBeDefined();
|
|
||||||
|
|
||||||
// Mock a response with notes
|
|
||||||
const mockRow = {
|
|
||||||
original: { notes: [{ text: "Note 1" }, { text: "Note 2" }] },
|
|
||||||
} as any;
|
|
||||||
|
|
||||||
// Call the cell function
|
|
||||||
notesColumn?.cell?.({ row: mockRow } as any);
|
|
||||||
expect(vi.mocked(processResponseData)).toHaveBeenCalledWith(["Note 1", "Note 2"]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("notesColumn returns undefined when notes is not an array", () => {
|
|
||||||
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
|
||||||
const notesColumn: any = columns.find((col) => (col as any).accessorKey === "notes");
|
|
||||||
expect(notesColumn).toBeDefined();
|
|
||||||
|
|
||||||
// Mock a response with no notes
|
|
||||||
const mockRow = {
|
|
||||||
original: { notes: null },
|
|
||||||
} as any;
|
|
||||||
|
|
||||||
// Call the cell function
|
|
||||||
const cellResult = notesColumn?.cell?.({ row: mockRow } as any);
|
|
||||||
expect(cellResult).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("variableColumns render variable values correctly", () => {
|
test("variableColumns render variable values correctly", () => {
|
||||||
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
||||||
|
|
||||||
@@ -496,3 +500,281 @@ describe("ResponseTableColumns - Column Implementations", () => {
|
|||||||
expect(hfColumn).toBeUndefined();
|
expect(hfColumn).toBeUndefined();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("ResponseTableColumns - Multiple Choice Questions", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("generates two columns for multipleChoiceSingle questions", () => {
|
||||||
|
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
||||||
|
|
||||||
|
// Should have main response column
|
||||||
|
const mainColumn = columns.find((col) => (col as any).accessorKey === "q5single");
|
||||||
|
expect(mainColumn).toBeDefined();
|
||||||
|
|
||||||
|
// Should have option IDs column
|
||||||
|
const optionIdsColumn = columns.find((col) => (col as any).accessorKey === "q5singleoptionIds");
|
||||||
|
expect(optionIdsColumn).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("generates two columns for multipleChoiceMulti questions", () => {
|
||||||
|
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
||||||
|
|
||||||
|
// Should have main response column
|
||||||
|
const mainColumn = columns.find((col) => (col as any).accessorKey === "q6multi");
|
||||||
|
expect(mainColumn).toBeDefined();
|
||||||
|
|
||||||
|
// Should have option IDs column
|
||||||
|
const optionIdsColumn = columns.find((col) => (col as any).accessorKey === "q6multioptionIds");
|
||||||
|
expect(optionIdsColumn).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("multipleChoiceSingle main column renders RenderResponse component", () => {
|
||||||
|
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
||||||
|
const mainColumn: any = columns.find((col) => (col as any).accessorKey === "q5single");
|
||||||
|
|
||||||
|
const mockRow = {
|
||||||
|
original: {
|
||||||
|
responseData: { q5single: "Option 1" },
|
||||||
|
language: "default",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const cellResult = mainColumn?.cell?.({ row: mockRow } as any);
|
||||||
|
// Check that RenderResponse component is returned
|
||||||
|
expect(cellResult).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("multipleChoiceMulti main column renders RenderResponse component", () => {
|
||||||
|
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
||||||
|
const mainColumn: any = columns.find((col) => (col as any).accessorKey === "q6multi");
|
||||||
|
|
||||||
|
const mockRow = {
|
||||||
|
original: {
|
||||||
|
responseData: { q6multi: ["Choice A", "Choice C"] },
|
||||||
|
language: "default",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const cellResult = mainColumn?.cell?.({ row: mockRow } as any);
|
||||||
|
// Check that RenderResponse component is returned
|
||||||
|
expect(cellResult).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("ResponseTableColumns - Choice ID Columns", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("option IDs column calls extractChoiceIdsFromResponse for string response", () => {
|
||||||
|
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
||||||
|
const optionIdsColumn: any = columns.find((col) => (col as any).accessorKey === "q5singleoptionIds");
|
||||||
|
|
||||||
|
const mockRow = {
|
||||||
|
original: {
|
||||||
|
responseData: { q5single: "Option 1" },
|
||||||
|
language: "default",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
optionIdsColumn?.cell?.({ row: mockRow } as any);
|
||||||
|
|
||||||
|
expect(vi.mocked(extractChoiceIdsFromResponse)).toHaveBeenCalledWith(
|
||||||
|
"Option 1",
|
||||||
|
expect.objectContaining({ id: "q5single", type: "multipleChoiceSingle" }),
|
||||||
|
"default"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("option IDs column calls extractChoiceIdsFromResponse for array response", () => {
|
||||||
|
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
||||||
|
const optionIdsColumn: any = columns.find((col) => (col as any).accessorKey === "q6multioptionIds");
|
||||||
|
|
||||||
|
const mockRow = {
|
||||||
|
original: {
|
||||||
|
responseData: { q6multi: ["Choice A", "Choice C"] },
|
||||||
|
language: "default",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
optionIdsColumn?.cell?.({ row: mockRow } as any);
|
||||||
|
|
||||||
|
expect(vi.mocked(extractChoiceIdsFromResponse)).toHaveBeenCalledWith(
|
||||||
|
["Choice A", "Choice C"],
|
||||||
|
expect.objectContaining({ id: "q6multi", type: "multipleChoiceMulti" }),
|
||||||
|
"default"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("option IDs column renders IdBadge components for choice IDs", () => {
|
||||||
|
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
||||||
|
const optionIdsColumn: any = columns.find((col) => (col as any).accessorKey === "q6multioptionIds");
|
||||||
|
|
||||||
|
const mockRow = {
|
||||||
|
original: {
|
||||||
|
responseData: { q6multi: ["Choice A", "Choice C"] },
|
||||||
|
language: "default",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Mock extractChoiceIdsFromResponse to return specific choice IDs
|
||||||
|
vi.mocked(extractChoiceIdsFromResponse).mockReturnValueOnce(["choice-1", "choice-3"]);
|
||||||
|
|
||||||
|
const cellResult = optionIdsColumn?.cell?.({ row: mockRow } as any);
|
||||||
|
|
||||||
|
// Should render something for choice IDs
|
||||||
|
expect(cellResult).toBeDefined();
|
||||||
|
// Verify that extractChoiceIdsFromResponse was called
|
||||||
|
expect(vi.mocked(extractChoiceIdsFromResponse)).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("option IDs column returns null for non-string/array response values", () => {
|
||||||
|
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
||||||
|
const optionIdsColumn: any = columns.find((col) => (col as any).accessorKey === "q5singleoptionIds");
|
||||||
|
|
||||||
|
const mockRow = {
|
||||||
|
original: {
|
||||||
|
responseData: { q5single: 123 }, // Invalid type
|
||||||
|
language: "default",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const cellResult = optionIdsColumn?.cell?.({ row: mockRow } as any);
|
||||||
|
|
||||||
|
expect(cellResult).toBeNull();
|
||||||
|
expect(vi.mocked(extractChoiceIdsFromResponse)).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("option IDs column returns null when no choice IDs found", () => {
|
||||||
|
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
||||||
|
const optionIdsColumn: any = columns.find((col) => (col as any).accessorKey === "q5singleoptionIds");
|
||||||
|
|
||||||
|
const mockRow = {
|
||||||
|
original: {
|
||||||
|
responseData: { q5single: "Non-existent option" },
|
||||||
|
language: "default",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Mock extractChoiceIdsFromResponse to return empty array
|
||||||
|
vi.mocked(extractChoiceIdsFromResponse).mockReturnValueOnce([]);
|
||||||
|
|
||||||
|
const cellResult = optionIdsColumn?.cell?.({ row: mockRow } as any);
|
||||||
|
|
||||||
|
expect(cellResult).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("option IDs column handles missing language gracefully", () => {
|
||||||
|
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
||||||
|
const optionIdsColumn: any = columns.find((col) => (col as any).accessorKey === "q5singleoptionIds");
|
||||||
|
|
||||||
|
const mockRow = {
|
||||||
|
original: {
|
||||||
|
responseData: { q5single: "Option 1" },
|
||||||
|
language: null, // No language
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
optionIdsColumn?.cell?.({ row: mockRow } as any);
|
||||||
|
|
||||||
|
expect(vi.mocked(extractChoiceIdsFromResponse)).toHaveBeenCalledWith(
|
||||||
|
"Option 1",
|
||||||
|
expect.objectContaining({ id: "q5single" }),
|
||||||
|
undefined
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("ResponseTableColumns - Helper Functions", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("question headers are properly created for multiple choice questions", () => {
|
||||||
|
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
||||||
|
const mainColumn: any = columns.find((col) => (col as any).accessorKey === "q5single");
|
||||||
|
const optionIdsColumn: any = columns.find((col) => (col as any).accessorKey === "q5singleoptionIds");
|
||||||
|
|
||||||
|
// Test main column header
|
||||||
|
const mainHeader = mainColumn?.header?.();
|
||||||
|
expect(mainHeader).toBeDefined();
|
||||||
|
expect(mainHeader?.props?.className).toContain("flex items-center justify-between");
|
||||||
|
|
||||||
|
// Test option IDs column header
|
||||||
|
const optionHeader = optionIdsColumn?.header?.();
|
||||||
|
expect(optionHeader).toBeDefined();
|
||||||
|
expect(optionHeader?.props?.className).toContain("flex items-center justify-between");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("question headers include proper icons for multiple choice questions", () => {
|
||||||
|
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
||||||
|
const singleChoiceColumn: any = columns.find((col) => (col as any).accessorKey === "q5single");
|
||||||
|
const multiChoiceColumn: any = columns.find((col) => (col as any).accessorKey === "q6multi");
|
||||||
|
|
||||||
|
// Headers should be functions that return JSX
|
||||||
|
expect(typeof singleChoiceColumn?.header).toBe("function");
|
||||||
|
expect(typeof multiChoiceColumn?.header).toBe("function");
|
||||||
|
|
||||||
|
// Call headers to ensure they don't throw
|
||||||
|
expect(() => singleChoiceColumn?.header?.()).not.toThrow();
|
||||||
|
expect(() => multiChoiceColumn?.header?.()).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("ResponseTableColumns - Integration Tests", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("multiple choice questions work end-to-end with real data", () => {
|
||||||
|
const columns = generateResponseTableColumns(mockSurvey, false, true, t as any);
|
||||||
|
|
||||||
|
// Find all multiple choice related columns
|
||||||
|
const singleMainCol = columns.find((col) => (col as any).accessorKey === "q5single");
|
||||||
|
const singleIdsCol = columns.find((col) => (col as any).accessorKey === "q5singleoptionIds");
|
||||||
|
const multiMainCol = columns.find((col) => (col as any).accessorKey === "q6multi");
|
||||||
|
const multiIdsCol = columns.find((col) => (col as any).accessorKey === "q6multioptionIds");
|
||||||
|
|
||||||
|
expect(singleMainCol).toBeDefined();
|
||||||
|
expect(singleIdsCol).toBeDefined();
|
||||||
|
expect(multiMainCol).toBeDefined();
|
||||||
|
expect(multiIdsCol).toBeDefined();
|
||||||
|
|
||||||
|
// Test with actual mock response data
|
||||||
|
const mockRow = { original: mockResponseData };
|
||||||
|
|
||||||
|
// Test single choice main column
|
||||||
|
const singleMainResult = (singleMainCol?.cell as any)?.({ row: mockRow });
|
||||||
|
expect(singleMainResult).toBeDefined();
|
||||||
|
|
||||||
|
// Test multi choice main column
|
||||||
|
const multiMainResult = (multiMainCol?.cell as any)?.({ row: mockRow });
|
||||||
|
expect(multiMainResult).toBeDefined();
|
||||||
|
|
||||||
|
// Test that choice ID columns exist and can be called
|
||||||
|
const singleIdsResult = (singleIdsCol?.cell as any)?.({ row: mockRow });
|
||||||
|
const multiIdsResult = (multiIdsCol?.cell as any)?.({ row: mockRow });
|
||||||
|
|
||||||
|
// Should not error when calling the cell functions
|
||||||
|
expect(() => singleIdsResult).not.toThrow();
|
||||||
|
expect(() => multiIdsResult).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,58 +1,31 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { getLocalizedValue } from "@/lib/i18n/utils";
|
import { getLocalizedValue } from "@/lib/i18n/utils";
|
||||||
import { processResponseData } from "@/lib/responses";
|
import { extractChoiceIdsFromResponse } from "@/lib/response/utils";
|
||||||
import { getContactIdentifier } from "@/lib/utils/contact";
|
import { getContactIdentifier } from "@/lib/utils/contact";
|
||||||
import { getFormattedDateTimeString } from "@/lib/utils/datetime";
|
import { getFormattedDateTimeString } from "@/lib/utils/datetime";
|
||||||
import { recallToHeadline } from "@/lib/utils/recall";
|
import { recallToHeadline } from "@/lib/utils/recall";
|
||||||
import { RenderResponse } from "@/modules/analysis/components/SingleResponseCard/components/RenderResponse";
|
import { RenderResponse } from "@/modules/analysis/components/SingleResponseCard/components/RenderResponse";
|
||||||
import { VARIABLES_ICON_MAP, getQuestionIconMap } from "@/modules/survey/lib/questions";
|
import { VARIABLES_ICON_MAP, getQuestionIconMap } from "@/modules/survey/lib/questions";
|
||||||
import { getSelectionColumn } from "@/modules/ui/components/data-table";
|
import { getSelectionColumn } from "@/modules/ui/components/data-table";
|
||||||
|
import { IdBadge } from "@/modules/ui/components/id-badge";
|
||||||
import { ResponseBadges } from "@/modules/ui/components/response-badges";
|
import { ResponseBadges } from "@/modules/ui/components/response-badges";
|
||||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/modules/ui/components/tooltip";
|
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/modules/ui/components/tooltip";
|
||||||
|
import { cn } from "@/modules/ui/lib/utils";
|
||||||
import { ColumnDef } from "@tanstack/react-table";
|
import { ColumnDef } from "@tanstack/react-table";
|
||||||
import { TFnType } from "@tolgee/react";
|
import { TFnType } from "@tolgee/react";
|
||||||
import { CircleHelpIcon, EyeOffIcon, MailIcon, TagIcon } from "lucide-react";
|
import { CircleHelpIcon, EyeOffIcon, MailIcon, TagIcon } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { TResponseTableData } from "@formbricks/types/responses";
|
import { TResponseTableData } from "@formbricks/types/responses";
|
||||||
import { TSurvey, TSurveyQuestion } from "@formbricks/types/surveys/types";
|
import { TSurvey, TSurveyQuestion } from "@formbricks/types/surveys/types";
|
||||||
|
import {
|
||||||
const getAddressFieldLabel = (field: string, t: TFnType) => {
|
COLUMNS_ICON_MAP,
|
||||||
switch (field) {
|
METADATA_FIELDS,
|
||||||
case "addressLine1":
|
getAddressFieldLabel,
|
||||||
return t("environments.surveys.responses.address_line_1");
|
getContactInfoFieldLabel,
|
||||||
case "addressLine2":
|
getMetadataFieldLabel,
|
||||||
return t("environments.surveys.responses.address_line_2");
|
getMetadataValue,
|
||||||
case "city":
|
} from "../lib/utils";
|
||||||
return t("environments.surveys.responses.city");
|
|
||||||
case "state":
|
|
||||||
return t("environments.surveys.responses.state_region");
|
|
||||||
case "zip":
|
|
||||||
return t("environments.surveys.responses.zip_post_code");
|
|
||||||
case "country":
|
|
||||||
return t("environments.surveys.responses.country");
|
|
||||||
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getContactInfoFieldLabel = (field: string, t: TFnType) => {
|
|
||||||
switch (field) {
|
|
||||||
case "firstName":
|
|
||||||
return t("environments.surveys.responses.first_name");
|
|
||||||
case "lastName":
|
|
||||||
return t("environments.surveys.responses.last_name");
|
|
||||||
case "email":
|
|
||||||
return t("environments.surveys.responses.email");
|
|
||||||
case "phone":
|
|
||||||
return t("environments.surveys.responses.phone");
|
|
||||||
case "company":
|
|
||||||
return t("environments.surveys.responses.company");
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getQuestionColumnsData = (
|
const getQuestionColumnsData = (
|
||||||
question: TSurveyQuestion,
|
question: TSurveyQuestion,
|
||||||
@@ -61,6 +34,42 @@ const getQuestionColumnsData = (
|
|||||||
t: TFnType
|
t: TFnType
|
||||||
): ColumnDef<TResponseTableData>[] => {
|
): ColumnDef<TResponseTableData>[] => {
|
||||||
const QUESTIONS_ICON_MAP = getQuestionIconMap(t);
|
const QUESTIONS_ICON_MAP = getQuestionIconMap(t);
|
||||||
|
|
||||||
|
// Helper function to create consistent column headers
|
||||||
|
const createQuestionHeader = (questionType: string, headline: string, suffix?: string) => {
|
||||||
|
const title = suffix ? `${headline} - ${suffix}` : headline;
|
||||||
|
const QuestionHeader = () => (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center space-x-2 overflow-hidden">
|
||||||
|
<span className="h-4 w-4">{QUESTIONS_ICON_MAP[questionType]}</span>
|
||||||
|
<span className="truncate">{title}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
QuestionHeader.displayName = "QuestionHeader";
|
||||||
|
return QuestionHeader;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper function to get localized question headline
|
||||||
|
const getQuestionHeadline = (question: TSurveyQuestion, survey: TSurvey) => {
|
||||||
|
return getLocalizedValue(recallToHeadline(question.headline, survey, false, "default"), "default");
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper function to render choice ID badges
|
||||||
|
const renderChoiceIdBadges = (choiceIds: string[], isExpanded: boolean) => {
|
||||||
|
if (choiceIds.length === 0) return null;
|
||||||
|
|
||||||
|
const containerClasses = cn("flex gap-x-1 w-full", isExpanded && "flex-wrap gap-y-1");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={containerClasses}>
|
||||||
|
{choiceIds.map((choiceId, index) => (
|
||||||
|
<IdBadge key={`${choiceId}-${index}`} id={choiceId} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
switch (question.type) {
|
switch (question.type) {
|
||||||
case "matrix":
|
case "matrix":
|
||||||
return question.rows.map((matrixRow) => {
|
return question.rows.map((matrixRow) => {
|
||||||
@@ -137,6 +146,50 @@ const getQuestionColumnsData = (
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
case "multipleChoiceMulti":
|
||||||
|
case "multipleChoiceSingle":
|
||||||
|
case "ranking":
|
||||||
|
case "pictureSelection": {
|
||||||
|
const questionHeadline = getQuestionHeadline(question, survey);
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
accessorKey: question.id,
|
||||||
|
header: createQuestionHeader(question.type, questionHeadline),
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const responseValue = row.original.responseData[question.id];
|
||||||
|
const language = row.original.language;
|
||||||
|
return (
|
||||||
|
<RenderResponse
|
||||||
|
question={question}
|
||||||
|
survey={survey}
|
||||||
|
responseData={responseValue}
|
||||||
|
language={language}
|
||||||
|
isExpanded={isExpanded}
|
||||||
|
showId={false}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: question.id + "optionIds",
|
||||||
|
header: createQuestionHeader(question.type, questionHeadline, t("common.option_id")),
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const responseValue = row.original.responseData[question.id];
|
||||||
|
// Type guard to ensure responseValue is the correct type
|
||||||
|
if (typeof responseValue === "string" || Array.isArray(responseValue)) {
|
||||||
|
const choiceIds = extractChoiceIdsFromResponse(
|
||||||
|
responseValue,
|
||||||
|
question,
|
||||||
|
row.original.language || undefined
|
||||||
|
);
|
||||||
|
return renderChoiceIdBadges(choiceIds, isExpanded);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
@@ -164,6 +217,7 @@ const getQuestionColumnsData = (
|
|||||||
responseData={responseValue}
|
responseData={responseValue}
|
||||||
language={language}
|
language={language}
|
||||||
isExpanded={isExpanded}
|
isExpanded={isExpanded}
|
||||||
|
showId={false}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
@@ -172,6 +226,33 @@ const getQuestionColumnsData = (
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getMetadataColumnsData = (t: TFnType): ColumnDef<TResponseTableData>[] => {
|
||||||
|
const metadataColumns: ColumnDef<TResponseTableData>[] = [];
|
||||||
|
|
||||||
|
METADATA_FIELDS.forEach((label) => {
|
||||||
|
const IconComponent = COLUMNS_ICON_MAP[label];
|
||||||
|
|
||||||
|
metadataColumns.push({
|
||||||
|
accessorKey: label,
|
||||||
|
header: () => (
|
||||||
|
<div className="flex items-center space-x-2 overflow-hidden">
|
||||||
|
<span className="h-4 w-4">{IconComponent && <IconComponent className="h-4 w-4" />}</span>
|
||||||
|
<span className="truncate">{getMetadataFieldLabel(label, t)}</span>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const value = getMetadataValue(row.original.meta, label);
|
||||||
|
if (value) {
|
||||||
|
return <div className="truncate text-slate-900">{value}</div>;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return metadataColumns;
|
||||||
|
};
|
||||||
|
|
||||||
export const generateResponseTableColumns = (
|
export const generateResponseTableColumns = (
|
||||||
survey: TSurvey,
|
survey: TSurvey,
|
||||||
isExpanded: boolean,
|
isExpanded: boolean,
|
||||||
@@ -230,7 +311,7 @@ export const generateResponseTableColumns = (
|
|||||||
header: t("common.status"),
|
header: t("common.status"),
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const status = row.original.status;
|
const status = row.original.status;
|
||||||
return <ResponseBadges items={[status]} />;
|
return <ResponseBadges items={[{ value: status }]} showId={false} />;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -243,27 +324,16 @@ export const generateResponseTableColumns = (
|
|||||||
const tagsArray = tags.map((tag) => tag.name);
|
const tagsArray = tags.map((tag) => tag.name);
|
||||||
return (
|
return (
|
||||||
<ResponseBadges
|
<ResponseBadges
|
||||||
items={tagsArray}
|
items={tagsArray.map((tag) => ({ value: tag }))}
|
||||||
isExpanded={isExpanded}
|
isExpanded={isExpanded}
|
||||||
icon={<TagIcon className="h-4 w-4 text-slate-500" />}
|
icon={<TagIcon className="h-4 w-4 text-slate-500" />}
|
||||||
|
showId={false}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const notesColumn: ColumnDef<TResponseTableData> = {
|
|
||||||
accessorKey: "notes",
|
|
||||||
header: t("common.notes"),
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const notes = row.original.notes;
|
|
||||||
if (Array.isArray(notes)) {
|
|
||||||
const notesArray = notes.map((note) => note.text);
|
|
||||||
return processResponseData(notesArray);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
const variableColumns: ColumnDef<TResponseTableData>[] = survey.variables.map((variable) => {
|
const variableColumns: ColumnDef<TResponseTableData>[] = survey.variables.map((variable) => {
|
||||||
return {
|
return {
|
||||||
accessorKey: variable.id,
|
accessorKey: variable.id,
|
||||||
@@ -304,6 +374,8 @@ export const generateResponseTableColumns = (
|
|||||||
})
|
})
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
|
const metadataColumns = getMetadataColumnsData(t);
|
||||||
|
|
||||||
const verifiedEmailColumn: ColumnDef<TResponseTableData> = {
|
const verifiedEmailColumn: ColumnDef<TResponseTableData> = {
|
||||||
accessorKey: "verifiedEmail",
|
accessorKey: "verifiedEmail",
|
||||||
header: () => (
|
header: () => (
|
||||||
@@ -317,7 +389,6 @@ export const generateResponseTableColumns = (
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Combine the selection column with the dynamic question columns
|
// Combine the selection column with the dynamic question columns
|
||||||
|
|
||||||
const baseColumns = [
|
const baseColumns = [
|
||||||
personColumn,
|
personColumn,
|
||||||
dateColumn,
|
dateColumn,
|
||||||
@@ -326,8 +397,8 @@ export const generateResponseTableColumns = (
|
|||||||
...questionColumns,
|
...questionColumns,
|
||||||
...variableColumns,
|
...variableColumns,
|
||||||
...hiddenFieldColumns,
|
...hiddenFieldColumns,
|
||||||
|
...metadataColumns,
|
||||||
tagsColumn,
|
tagsColumn,
|
||||||
notesColumn,
|
|
||||||
];
|
];
|
||||||
|
|
||||||
return isReadOnly ? baseColumns : [getSelectionColumn(), ...baseColumns];
|
return isReadOnly ? baseColumns : [getSelectionColumn(), ...baseColumns];
|
||||||
|
|||||||
@@ -0,0 +1,204 @@
|
|||||||
|
import "@testing-library/jest-dom/vitest";
|
||||||
|
import {
|
||||||
|
AirplayIcon,
|
||||||
|
ArrowUpFromDotIcon,
|
||||||
|
FlagIcon,
|
||||||
|
GlobeIcon,
|
||||||
|
MousePointerClickIcon,
|
||||||
|
SmartphoneIcon,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { describe, expect, test, vi } from "vitest";
|
||||||
|
import {
|
||||||
|
COLUMNS_ICON_MAP,
|
||||||
|
getAddressFieldLabel,
|
||||||
|
getContactInfoFieldLabel,
|
||||||
|
getMetadataFieldLabel,
|
||||||
|
getMetadataValue,
|
||||||
|
} from "./utils";
|
||||||
|
|
||||||
|
describe("utils", () => {
|
||||||
|
const mockT = vi.fn((key: string) => {
|
||||||
|
const translations: Record<string, string> = {
|
||||||
|
"environments.surveys.responses.address_line_1": "Address Line 1",
|
||||||
|
"environments.surveys.responses.address_line_2": "Address Line 2",
|
||||||
|
"environments.surveys.responses.city": "City",
|
||||||
|
"environments.surveys.responses.state_region": "State/Region",
|
||||||
|
"environments.surveys.responses.zip_post_code": "ZIP/Post Code",
|
||||||
|
"environments.surveys.responses.country": "Country",
|
||||||
|
"environments.surveys.responses.first_name": "First Name",
|
||||||
|
"environments.surveys.responses.last_name": "Last Name",
|
||||||
|
"environments.surveys.responses.email": "Email",
|
||||||
|
"environments.surveys.responses.phone": "Phone",
|
||||||
|
"environments.surveys.responses.company": "Company",
|
||||||
|
"common.action": "Action",
|
||||||
|
"environments.surveys.responses.os": "OS",
|
||||||
|
"environments.surveys.responses.device": "Device",
|
||||||
|
"environments.surveys.responses.browser": "Browser",
|
||||||
|
"common.url": "URL",
|
||||||
|
"environments.surveys.responses.source": "Source",
|
||||||
|
};
|
||||||
|
return translations[key] || key;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getAddressFieldLabel", () => {
|
||||||
|
test("returns correct label for addressLine1", () => {
|
||||||
|
const result = getAddressFieldLabel("addressLine1", mockT);
|
||||||
|
expect(result).toBe("Address Line 1");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.address_line_1");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct label for addressLine2", () => {
|
||||||
|
const result = getAddressFieldLabel("addressLine2", mockT);
|
||||||
|
expect(result).toBe("Address Line 2");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.address_line_2");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct label for city", () => {
|
||||||
|
const result = getAddressFieldLabel("city", mockT);
|
||||||
|
expect(result).toBe("City");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.city");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct label for state", () => {
|
||||||
|
const result = getAddressFieldLabel("state", mockT);
|
||||||
|
expect(result).toBe("State/Region");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.state_region");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct label for zip", () => {
|
||||||
|
const result = getAddressFieldLabel("zip", mockT);
|
||||||
|
expect(result).toBe("ZIP/Post Code");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.zip_post_code");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct label for country", () => {
|
||||||
|
const result = getAddressFieldLabel("country", mockT);
|
||||||
|
expect(result).toBe("Country");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.country");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns undefined for unknown field", () => {
|
||||||
|
const result = getAddressFieldLabel("unknown", mockT);
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
expect(mockT).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getContactInfoFieldLabel", () => {
|
||||||
|
test("returns correct label for firstName", () => {
|
||||||
|
const result = getContactInfoFieldLabel("firstName", mockT);
|
||||||
|
expect(result).toBe("First Name");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.first_name");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct label for lastName", () => {
|
||||||
|
const result = getContactInfoFieldLabel("lastName", mockT);
|
||||||
|
expect(result).toBe("Last Name");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.last_name");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct label for email", () => {
|
||||||
|
const result = getContactInfoFieldLabel("email", mockT);
|
||||||
|
expect(result).toBe("Email");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.email");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct label for phone", () => {
|
||||||
|
const result = getContactInfoFieldLabel("phone", mockT);
|
||||||
|
expect(result).toBe("Phone");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.phone");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct label for company", () => {
|
||||||
|
const result = getContactInfoFieldLabel("company", mockT);
|
||||||
|
expect(result).toBe("Company");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.company");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns undefined for unknown field", () => {
|
||||||
|
const result = getContactInfoFieldLabel("unknown", mockT);
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
expect(mockT).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getMetadataFieldLabel", () => {
|
||||||
|
test("returns correct label for action", () => {
|
||||||
|
const result = getMetadataFieldLabel("action", mockT);
|
||||||
|
expect(result).toBe("Action");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("common.action");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct label for country", () => {
|
||||||
|
const result = getMetadataFieldLabel("country", mockT);
|
||||||
|
expect(result).toBe("Country");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.country");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct label for os", () => {
|
||||||
|
const result = getMetadataFieldLabel("os", mockT);
|
||||||
|
expect(result).toBe("OS");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.os");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct label for device", () => {
|
||||||
|
const result = getMetadataFieldLabel("device", mockT);
|
||||||
|
expect(result).toBe("Device");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.device");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct label for browser", () => {
|
||||||
|
const result = getMetadataFieldLabel("browser", mockT);
|
||||||
|
expect(result).toBe("Browser");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.browser");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct label for url", () => {
|
||||||
|
const result = getMetadataFieldLabel("url", mockT);
|
||||||
|
expect(result).toBe("URL");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("common.url");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct label for source", () => {
|
||||||
|
const result = getMetadataFieldLabel("source", mockT);
|
||||||
|
expect(result).toBe("Source");
|
||||||
|
expect(mockT).toHaveBeenCalledWith("environments.surveys.responses.source");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns capitalized label for unknown field", () => {
|
||||||
|
const result = getMetadataFieldLabel("customField", mockT);
|
||||||
|
expect(result).toBe("Customfield");
|
||||||
|
expect(mockT).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns capitalized label for field with underscores", () => {
|
||||||
|
const result = getMetadataFieldLabel("custom_field", mockT);
|
||||||
|
expect(result).toBe("Custom_field");
|
||||||
|
expect(mockT).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("COLUMNS_ICON_MAP", () => {
|
||||||
|
test("contains correct icon mappings", () => {
|
||||||
|
expect(COLUMNS_ICON_MAP.action).toBe(MousePointerClickIcon);
|
||||||
|
expect(COLUMNS_ICON_MAP.country).toBe(FlagIcon);
|
||||||
|
expect(COLUMNS_ICON_MAP.browser).toBe(GlobeIcon);
|
||||||
|
expect(COLUMNS_ICON_MAP.os).toBe(AirplayIcon);
|
||||||
|
expect(COLUMNS_ICON_MAP.device).toBe(SmartphoneIcon);
|
||||||
|
expect(COLUMNS_ICON_MAP.source).toBe(ArrowUpFromDotIcon);
|
||||||
|
expect(COLUMNS_ICON_MAP.url).toBe(GlobeIcon);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getMetadataValue", () => {
|
||||||
|
test("returns correct value for action", () => {
|
||||||
|
const result = getMetadataValue({ action: "action_column" }, "action");
|
||||||
|
expect(result).toBe("action_column");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns correct value for userAgent", () => {
|
||||||
|
const result = getMetadataValue({ userAgent: { browser: "browser_column" } }, "browser");
|
||||||
|
expect(result).toBe("browser_column");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { TFnType } from "@tolgee/react";
|
||||||
|
import { capitalize } from "lodash";
|
||||||
|
import {
|
||||||
|
AirplayIcon,
|
||||||
|
ArrowUpFromDotIcon,
|
||||||
|
FlagIcon,
|
||||||
|
GlobeIcon,
|
||||||
|
MousePointerClickIcon,
|
||||||
|
SmartphoneIcon,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { TResponseMeta } from "@formbricks/types/responses";
|
||||||
|
|
||||||
|
export const getAddressFieldLabel = (field: string, t: TFnType) => {
|
||||||
|
switch (field) {
|
||||||
|
case "addressLine1":
|
||||||
|
return t("environments.surveys.responses.address_line_1");
|
||||||
|
case "addressLine2":
|
||||||
|
return t("environments.surveys.responses.address_line_2");
|
||||||
|
case "city":
|
||||||
|
return t("environments.surveys.responses.city");
|
||||||
|
case "state":
|
||||||
|
return t("environments.surveys.responses.state_region");
|
||||||
|
case "zip":
|
||||||
|
return t("environments.surveys.responses.zip_post_code");
|
||||||
|
case "country":
|
||||||
|
return t("environments.surveys.responses.country");
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getContactInfoFieldLabel = (field: string, t: TFnType) => {
|
||||||
|
switch (field) {
|
||||||
|
case "firstName":
|
||||||
|
return t("environments.surveys.responses.first_name");
|
||||||
|
case "lastName":
|
||||||
|
return t("environments.surveys.responses.last_name");
|
||||||
|
case "email":
|
||||||
|
return t("environments.surveys.responses.email");
|
||||||
|
case "phone":
|
||||||
|
return t("environments.surveys.responses.phone");
|
||||||
|
case "company":
|
||||||
|
return t("environments.surveys.responses.company");
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getMetadataFieldLabel = (label: string, t: TFnType) => {
|
||||||
|
switch (label) {
|
||||||
|
case "action":
|
||||||
|
return t("common.action");
|
||||||
|
case "country":
|
||||||
|
return t("environments.surveys.responses.country");
|
||||||
|
case "os":
|
||||||
|
return t("environments.surveys.responses.os");
|
||||||
|
case "device":
|
||||||
|
return t("environments.surveys.responses.device");
|
||||||
|
case "browser":
|
||||||
|
return t("environments.surveys.responses.browser");
|
||||||
|
case "url":
|
||||||
|
return t("common.url");
|
||||||
|
case "source":
|
||||||
|
return t("environments.surveys.responses.source");
|
||||||
|
default:
|
||||||
|
return capitalize(label);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const COLUMNS_ICON_MAP = {
|
||||||
|
action: MousePointerClickIcon,
|
||||||
|
country: FlagIcon,
|
||||||
|
browser: GlobeIcon,
|
||||||
|
os: AirplayIcon,
|
||||||
|
device: SmartphoneIcon,
|
||||||
|
source: ArrowUpFromDotIcon,
|
||||||
|
url: GlobeIcon,
|
||||||
|
};
|
||||||
|
|
||||||
|
const userAgentFields = ["browser", "os", "device"];
|
||||||
|
export const METADATA_FIELDS = ["action", "country", ...userAgentFields, "source", "url"];
|
||||||
|
|
||||||
|
export const getMetadataValue = (meta: TResponseMeta, label: string) => {
|
||||||
|
if (userAgentFields.includes(label)) {
|
||||||
|
return meta.userAgent?.[label];
|
||||||
|
}
|
||||||
|
return meta[label];
|
||||||
|
};
|
||||||
@@ -3,6 +3,7 @@ import { SurveyAnalysisNavigation } from "@/app/(app)/environments/[environmentI
|
|||||||
import { ResponsePage } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponsePage";
|
import { ResponsePage } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponsePage";
|
||||||
import Page from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/page";
|
import Page from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/page";
|
||||||
import { SurveyAnalysisCTA } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SurveyAnalysisCTA";
|
import { SurveyAnalysisCTA } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SurveyAnalysisCTA";
|
||||||
|
import { getDisplayCountBySurveyId } from "@/lib/display/service";
|
||||||
import { getPublicDomain } from "@/lib/getPublicUrl";
|
import { getPublicDomain } from "@/lib/getPublicUrl";
|
||||||
import { getResponseCountBySurveyId } from "@/lib/response/service";
|
import { getResponseCountBySurveyId } from "@/lib/response/service";
|
||||||
import { getSurvey } from "@/lib/survey/service";
|
import { getSurvey } from "@/lib/survey/service";
|
||||||
@@ -73,6 +74,10 @@ vi.mock("@/lib/response/service", () => ({
|
|||||||
getResponseCountBySurveyId: vi.fn(),
|
getResponseCountBySurveyId: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/display/service", () => ({
|
||||||
|
getDisplayCountBySurveyId: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
vi.mock("@/lib/survey/service", () => ({
|
vi.mock("@/lib/survey/service", () => ({
|
||||||
getSurvey: vi.fn(),
|
getSurvey: vi.fn(),
|
||||||
}));
|
}));
|
||||||
@@ -115,7 +120,6 @@ vi.mock("next/navigation", () => ({
|
|||||||
useParams: () => ({
|
useParams: () => ({
|
||||||
environmentId: "test-env-id",
|
environmentId: "test-env-id",
|
||||||
surveyId: "test-survey-id",
|
surveyId: "test-survey-id",
|
||||||
sharingKey: null,
|
|
||||||
}),
|
}),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -178,6 +182,7 @@ describe("ResponsesPage", () => {
|
|||||||
vi.mocked(getUser).mockResolvedValue(mockUser);
|
vi.mocked(getUser).mockResolvedValue(mockUser);
|
||||||
vi.mocked(getTagsByEnvironmentId).mockResolvedValue(mockTags);
|
vi.mocked(getTagsByEnvironmentId).mockResolvedValue(mockTags);
|
||||||
vi.mocked(getResponseCountBySurveyId).mockResolvedValue(10);
|
vi.mocked(getResponseCountBySurveyId).mockResolvedValue(10);
|
||||||
|
vi.mocked(getDisplayCountBySurveyId).mockResolvedValue(5);
|
||||||
vi.mocked(findMatchingLocale).mockResolvedValue(mockLocale);
|
vi.mocked(findMatchingLocale).mockResolvedValue(mockLocale);
|
||||||
vi.mocked(getPublicDomain).mockReturnValue(mockPublicDomain);
|
vi.mocked(getPublicDomain).mockReturnValue(mockPublicDomain);
|
||||||
});
|
});
|
||||||
@@ -206,6 +211,8 @@ describe("ResponsesPage", () => {
|
|||||||
isReadOnly: false,
|
isReadOnly: false,
|
||||||
user: mockUser,
|
user: mockUser,
|
||||||
publicDomain: mockPublicDomain,
|
publicDomain: mockPublicDomain,
|
||||||
|
responseCount: 10,
|
||||||
|
displayCount: 5,
|
||||||
}),
|
}),
|
||||||
undefined
|
undefined
|
||||||
);
|
);
|
||||||
@@ -224,12 +231,10 @@ describe("ResponsesPage", () => {
|
|||||||
environment: mockEnvironment,
|
environment: mockEnvironment,
|
||||||
survey: mockSurvey,
|
survey: mockSurvey,
|
||||||
surveyId: mockSurveyId,
|
surveyId: mockSurveyId,
|
||||||
publicDomain: mockPublicDomain,
|
|
||||||
environmentTags: mockTags,
|
environmentTags: mockTags,
|
||||||
user: mockUser,
|
user: mockUser,
|
||||||
responsesPerPage: 10,
|
responsesPerPage: 10,
|
||||||
locale: mockLocale,
|
locale: mockLocale,
|
||||||
isReadOnly: false,
|
|
||||||
}),
|
}),
|
||||||
undefined
|
undefined
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { SurveyAnalysisNavigation } from "@/app/(app)/environments/[environmentI
|
|||||||
import { ResponsePage } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponsePage";
|
import { ResponsePage } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/responses/components/ResponsePage";
|
||||||
import { SurveyAnalysisCTA } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SurveyAnalysisCTA";
|
import { SurveyAnalysisCTA } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SurveyAnalysisCTA";
|
||||||
import { IS_FORMBRICKS_CLOUD, RESPONSES_PER_PAGE } from "@/lib/constants";
|
import { IS_FORMBRICKS_CLOUD, RESPONSES_PER_PAGE } from "@/lib/constants";
|
||||||
|
import { getDisplayCountBySurveyId } from "@/lib/display/service";
|
||||||
import { getPublicDomain } from "@/lib/getPublicUrl";
|
import { getPublicDomain } from "@/lib/getPublicUrl";
|
||||||
import { getResponseCountBySurveyId } from "@/lib/response/service";
|
import { getResponseCountBySurveyId } from "@/lib/response/service";
|
||||||
import { getSurvey } from "@/lib/survey/service";
|
import { getSurvey } from "@/lib/survey/service";
|
||||||
@@ -40,6 +41,7 @@ const Page = async (props) => {
|
|||||||
|
|
||||||
// Get response count for the CTA component
|
// Get response count for the CTA component
|
||||||
const responseCount = await getResponseCountBySurveyId(params.surveyId);
|
const responseCount = await getResponseCountBySurveyId(params.surveyId);
|
||||||
|
const displayCount = await getDisplayCountBySurveyId(params.surveyId);
|
||||||
|
|
||||||
const locale = await findMatchingLocale();
|
const locale = await findMatchingLocale();
|
||||||
const publicDomain = getPublicDomain();
|
const publicDomain = getPublicDomain();
|
||||||
@@ -56,6 +58,7 @@ const Page = async (props) => {
|
|||||||
user={user}
|
user={user}
|
||||||
publicDomain={publicDomain}
|
publicDomain={publicDomain}
|
||||||
responseCount={responseCount}
|
responseCount={responseCount}
|
||||||
|
displayCount={displayCount}
|
||||||
segments={segments}
|
segments={segments}
|
||||||
isContactsEnabled={isContactsEnabled}
|
isContactsEnabled={isContactsEnabled}
|
||||||
isFormbricksCloud={IS_FORMBRICKS_CLOUD}
|
isFormbricksCloud={IS_FORMBRICKS_CLOUD}
|
||||||
@@ -67,7 +70,6 @@ const Page = async (props) => {
|
|||||||
environment={environment}
|
environment={environment}
|
||||||
survey={survey}
|
survey={survey}
|
||||||
surveyId={params.surveyId}
|
surveyId={params.surveyId}
|
||||||
publicDomain={publicDomain}
|
|
||||||
environmentTags={tags}
|
environmentTags={tags}
|
||||||
user={user}
|
user={user}
|
||||||
responsesPerPage={RESPONSES_PER_PAGE}
|
responsesPerPage={RESPONSES_PER_PAGE}
|
||||||
|
|||||||
@@ -14,10 +14,10 @@ import { generatePersonalLinks } from "@/modules/ee/contacts/lib/contacts";
|
|||||||
import { getIsContactsEnabled } from "@/modules/ee/license-check/lib/utils";
|
import { getIsContactsEnabled } from "@/modules/ee/license-check/lib/utils";
|
||||||
import { getOrganizationLogoUrl } from "@/modules/ee/whitelabel/email-customization/lib/organization";
|
import { getOrganizationLogoUrl } from "@/modules/ee/whitelabel/email-customization/lib/organization";
|
||||||
import { sendEmbedSurveyPreviewEmail } from "@/modules/email";
|
import { sendEmbedSurveyPreviewEmail } from "@/modules/email";
|
||||||
import { customAlphabet } from "nanoid";
|
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { ZId } from "@formbricks/types/common";
|
import { ZId } from "@formbricks/types/common";
|
||||||
import { OperationNotAllowedError, ResourceNotFoundError, UnknownError } from "@formbricks/types/errors";
|
import { OperationNotAllowedError, ResourceNotFoundError, UnknownError } from "@formbricks/types/errors";
|
||||||
|
import { deleteResponsesAndDisplaysForSurvey } from "./lib/survey";
|
||||||
|
|
||||||
const ZSendEmbedSurveyPreviewEmailAction = z.object({
|
const ZSendEmbedSurveyPreviewEmailAction = z.object({
|
||||||
surveyId: ZId,
|
surveyId: ZId,
|
||||||
@@ -64,143 +64,60 @@ export const sendEmbedSurveyPreviewEmailAction = authenticatedActionClient
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
const ZGenerateResultShareUrlAction = z.object({
|
const ZResetSurveyAction = z.object({
|
||||||
surveyId: ZId,
|
surveyId: ZId,
|
||||||
|
organizationId: ZId,
|
||||||
|
projectId: ZId,
|
||||||
});
|
});
|
||||||
|
|
||||||
export const generateResultShareUrlAction = authenticatedActionClient
|
export const resetSurveyAction = authenticatedActionClient.schema(ZResetSurveyAction).action(
|
||||||
.schema(ZGenerateResultShareUrlAction)
|
withAuditLogging(
|
||||||
.action(
|
"updated",
|
||||||
withAuditLogging(
|
"survey",
|
||||||
"updated",
|
async ({
|
||||||
"survey",
|
ctx,
|
||||||
async ({
|
parsedInput,
|
||||||
ctx,
|
}: {
|
||||||
parsedInput,
|
ctx: AuthenticatedActionClientCtx;
|
||||||
}: {
|
parsedInput: z.infer<typeof ZResetSurveyAction>;
|
||||||
ctx: AuthenticatedActionClientCtx;
|
}) => {
|
||||||
parsedInput: Record<string, any>;
|
await checkAuthorizationUpdated({
|
||||||
}) => {
|
userId: ctx.user.id,
|
||||||
const organizationId = await getOrganizationIdFromSurveyId(parsedInput.surveyId);
|
organizationId: parsedInput.organizationId,
|
||||||
await checkAuthorizationUpdated({
|
access: [
|
||||||
userId: ctx.user.id,
|
{
|
||||||
organizationId: organizationId,
|
type: "organization",
|
||||||
access: [
|
roles: ["owner", "manager"],
|
||||||
{
|
},
|
||||||
type: "organization",
|
{
|
||||||
roles: ["owner", "manager"],
|
type: "projectTeam",
|
||||||
},
|
minPermission: "readWrite",
|
||||||
{
|
projectId: parsedInput.projectId,
|
||||||
type: "projectTeam",
|
},
|
||||||
minPermission: "readWrite",
|
],
|
||||||
projectId: await getProjectIdFromSurveyId(parsedInput.surveyId),
|
});
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
const survey = await getSurvey(parsedInput.surveyId);
|
ctx.auditLoggingCtx.organizationId = parsedInput.organizationId;
|
||||||
if (!survey) {
|
ctx.auditLoggingCtx.surveyId = parsedInput.surveyId;
|
||||||
throw new ResourceNotFoundError("Survey", parsedInput.surveyId);
|
ctx.auditLoggingCtx.oldObject = null;
|
||||||
}
|
|
||||||
|
|
||||||
const resultShareKey = customAlphabet(
|
const { deletedResponsesCount, deletedDisplaysCount } = await deleteResponsesAndDisplaysForSurvey(
|
||||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
|
parsedInput.surveyId
|
||||||
20
|
);
|
||||||
)();
|
|
||||||
|
|
||||||
ctx.auditLoggingCtx.organizationId = organizationId;
|
ctx.auditLoggingCtx.newObject = {
|
||||||
ctx.auditLoggingCtx.surveyId = parsedInput.surveyId;
|
deletedResponsesCount: deletedResponsesCount,
|
||||||
ctx.auditLoggingCtx.oldObject = survey;
|
deletedDisplaysCount: deletedDisplaysCount,
|
||||||
|
};
|
||||||
|
|
||||||
const newSurvey = await updateSurvey({ ...survey, resultShareKey });
|
return {
|
||||||
ctx.auditLoggingCtx.newObject = newSurvey;
|
success: true,
|
||||||
|
deletedResponsesCount: deletedResponsesCount,
|
||||||
return resultShareKey;
|
deletedDisplaysCount: deletedDisplaysCount,
|
||||||
}
|
};
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
const ZGetResultShareUrlAction = z.object({
|
|
||||||
surveyId: ZId,
|
|
||||||
});
|
|
||||||
|
|
||||||
export const getResultShareUrlAction = authenticatedActionClient
|
|
||||||
.schema(ZGetResultShareUrlAction)
|
|
||||||
.action(async ({ ctx, parsedInput }) => {
|
|
||||||
await checkAuthorizationUpdated({
|
|
||||||
userId: ctx.user.id,
|
|
||||||
organizationId: await getOrganizationIdFromSurveyId(parsedInput.surveyId),
|
|
||||||
access: [
|
|
||||||
{
|
|
||||||
type: "organization",
|
|
||||||
roles: ["owner", "manager"],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "projectTeam",
|
|
||||||
projectId: await getProjectIdFromSurveyId(parsedInput.surveyId),
|
|
||||||
minPermission: "readWrite",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
const survey = await getSurvey(parsedInput.surveyId);
|
|
||||||
if (!survey) {
|
|
||||||
throw new ResourceNotFoundError("Survey", parsedInput.surveyId);
|
|
||||||
}
|
}
|
||||||
|
)
|
||||||
return survey.resultShareKey;
|
);
|
||||||
});
|
|
||||||
|
|
||||||
const ZDeleteResultShareUrlAction = z.object({
|
|
||||||
surveyId: ZId,
|
|
||||||
});
|
|
||||||
|
|
||||||
export const deleteResultShareUrlAction = authenticatedActionClient
|
|
||||||
.schema(ZDeleteResultShareUrlAction)
|
|
||||||
.action(
|
|
||||||
withAuditLogging(
|
|
||||||
"updated",
|
|
||||||
"survey",
|
|
||||||
async ({
|
|
||||||
ctx,
|
|
||||||
parsedInput,
|
|
||||||
}: {
|
|
||||||
ctx: AuthenticatedActionClientCtx;
|
|
||||||
parsedInput: Record<string, any>;
|
|
||||||
}) => {
|
|
||||||
const organizationId = await getOrganizationIdFromSurveyId(parsedInput.surveyId);
|
|
||||||
await checkAuthorizationUpdated({
|
|
||||||
userId: ctx.user.id,
|
|
||||||
organizationId: organizationId,
|
|
||||||
access: [
|
|
||||||
{
|
|
||||||
type: "organization",
|
|
||||||
roles: ["owner", "manager"],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "projectTeam",
|
|
||||||
minPermission: "readWrite",
|
|
||||||
projectId: await getProjectIdFromSurveyId(parsedInput.surveyId),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
const survey = await getSurvey(parsedInput.surveyId);
|
|
||||||
if (!survey) {
|
|
||||||
throw new ResourceNotFoundError("Survey", parsedInput.surveyId);
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.auditLoggingCtx.organizationId = organizationId;
|
|
||||||
ctx.auditLoggingCtx.surveyId = parsedInput.surveyId;
|
|
||||||
ctx.auditLoggingCtx.oldObject = survey;
|
|
||||||
|
|
||||||
const newSurvey = await updateSurvey({ ...survey, resultShareKey: null });
|
|
||||||
ctx.auditLoggingCtx.newObject = newSurvey;
|
|
||||||
|
|
||||||
return newSurvey;
|
|
||||||
}
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
const ZGetEmailHtmlAction = z.object({
|
const ZGetEmailHtmlAction = z.object({
|
||||||
surveyId: ZId,
|
surveyId: ZId,
|
||||||
|
|||||||
@@ -7,6 +7,13 @@ vi.mock("@/modules/ui/components/avatars", () => ({
|
|||||||
PersonAvatar: ({ personId }: any) => <div data-testid="avatar">{personId}</div>,
|
PersonAvatar: ({ personId }: any) => <div data-testid="avatar">{personId}</div>,
|
||||||
}));
|
}));
|
||||||
vi.mock("./QuestionSummaryHeader", () => ({ QuestionSummaryHeader: () => <div data-testid="header" /> }));
|
vi.mock("./QuestionSummaryHeader", () => ({ QuestionSummaryHeader: () => <div data-testid="header" /> }));
|
||||||
|
vi.mock("@/modules/ui/components/id-badge", () => ({
|
||||||
|
IdBadge: ({ id }: { id: string }) => (
|
||||||
|
<div data-testid="id-badge" data-id={id}>
|
||||||
|
ID: {id}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
describe("MultipleChoiceSummary", () => {
|
describe("MultipleChoiceSummary", () => {
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -160,8 +167,8 @@ describe("MultipleChoiceSummary", () => {
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
const btns = screen.getAllByRole("button");
|
const btns = screen.getAllByRole("button");
|
||||||
expect(btns[0]).toHaveTextContent("2 - Y50%2 common.selections");
|
expect(btns[0]).toHaveTextContent("2 - YID: other2 common.selections50%");
|
||||||
expect(btns[1]).toHaveTextContent("1 - X50%1 common.selection");
|
expect(btns[1]).toHaveTextContent("1 - XID: other1 common.selection50%");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("places choice with others after one without when reversed inputs", () => {
|
test("places choice with others after one without when reversed inputs", () => {
|
||||||
@@ -272,4 +279,127 @@ describe("MultipleChoiceSummary", () => {
|
|||||||
["O5"]
|
["O5"]
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// New tests for IdBadge functionality
|
||||||
|
test("renders IdBadge when choice ID is found", () => {
|
||||||
|
const setFilter = vi.fn();
|
||||||
|
const q = {
|
||||||
|
question: {
|
||||||
|
id: "q6",
|
||||||
|
headline: "H6",
|
||||||
|
type: "multipleChoiceSingle",
|
||||||
|
choices: [
|
||||||
|
{ id: "choice1", label: { default: "Option A" } },
|
||||||
|
{ id: "choice2", label: { default: "Option B" } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
choices: {
|
||||||
|
"Option A": { value: "Option A", count: 5, percentage: 50, others: [] },
|
||||||
|
"Option B": { value: "Option B", count: 5, percentage: 50, others: [] },
|
||||||
|
},
|
||||||
|
type: "multipleChoiceSingle",
|
||||||
|
selectionCount: 0,
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
render(
|
||||||
|
<MultipleChoiceSummary
|
||||||
|
questionSummary={q}
|
||||||
|
environmentId="env"
|
||||||
|
surveyType="link"
|
||||||
|
survey={baseSurvey}
|
||||||
|
setFilter={setFilter}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
const idBadges = screen.getAllByTestId("id-badge");
|
||||||
|
expect(idBadges).toHaveLength(2);
|
||||||
|
expect(idBadges[0]).toHaveAttribute("data-id", "choice1");
|
||||||
|
expect(idBadges[1]).toHaveAttribute("data-id", "choice2");
|
||||||
|
expect(idBadges[0]).toHaveTextContent("ID: choice1");
|
||||||
|
expect(idBadges[1]).toHaveTextContent("ID: choice2");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("getChoiceIdByValue function correctly maps values to IDs", () => {
|
||||||
|
const setFilter = vi.fn();
|
||||||
|
const q = {
|
||||||
|
question: {
|
||||||
|
id: "q8",
|
||||||
|
headline: "H8",
|
||||||
|
type: "multipleChoiceMulti",
|
||||||
|
choices: [
|
||||||
|
{ id: "id-apple", label: { default: "Apple" } },
|
||||||
|
{ id: "id-banana", label: { default: "Banana" } },
|
||||||
|
{ id: "id-cherry", label: { default: "Cherry" } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
choices: {
|
||||||
|
Apple: { value: "Apple", count: 3, percentage: 30, others: [] },
|
||||||
|
Banana: { value: "Banana", count: 4, percentage: 40, others: [] },
|
||||||
|
Cherry: { value: "Cherry", count: 3, percentage: 30, others: [] },
|
||||||
|
},
|
||||||
|
type: "multipleChoiceMulti",
|
||||||
|
selectionCount: 0,
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
render(
|
||||||
|
<MultipleChoiceSummary
|
||||||
|
questionSummary={q}
|
||||||
|
environmentId="env"
|
||||||
|
surveyType="link"
|
||||||
|
survey={baseSurvey}
|
||||||
|
setFilter={setFilter}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
const idBadges = screen.getAllByTestId("id-badge");
|
||||||
|
expect(idBadges).toHaveLength(3);
|
||||||
|
|
||||||
|
// Check that each badge has the correct ID
|
||||||
|
const expectedMappings = [
|
||||||
|
{ text: "Banana", id: "id-banana" }, // Highest count appears first
|
||||||
|
{ text: "Apple", id: "id-apple" },
|
||||||
|
{ text: "Cherry", id: "id-cherry" },
|
||||||
|
];
|
||||||
|
|
||||||
|
expectedMappings.forEach(({ text, id }, index) => {
|
||||||
|
expect(screen.getByText(`${3 - index} - ${text}`)).toBeInTheDocument();
|
||||||
|
expect(idBadges[index]).toHaveAttribute("data-id", id);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("handles choices with special characters in labels", () => {
|
||||||
|
const setFilter = vi.fn();
|
||||||
|
const q = {
|
||||||
|
question: {
|
||||||
|
id: "q9",
|
||||||
|
headline: "H9",
|
||||||
|
type: "multipleChoiceSingle",
|
||||||
|
choices: [
|
||||||
|
{ id: "special-1", label: { default: "Option & Choice" } },
|
||||||
|
{ id: "special-2", label: { default: "Choice with 'quotes'" } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
choices: {
|
||||||
|
"Option & Choice": { value: "Option & Choice", count: 2, percentage: 50, others: [] },
|
||||||
|
"Choice with 'quotes'": { value: "Choice with 'quotes'", count: 2, percentage: 50, others: [] },
|
||||||
|
},
|
||||||
|
type: "multipleChoiceSingle",
|
||||||
|
selectionCount: 0,
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
render(
|
||||||
|
<MultipleChoiceSummary
|
||||||
|
questionSummary={q}
|
||||||
|
environmentId="env"
|
||||||
|
surveyType="link"
|
||||||
|
survey={baseSurvey}
|
||||||
|
setFilter={setFilter}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
const idBadges = screen.getAllByTestId("id-badge");
|
||||||
|
expect(idBadges).toHaveLength(2);
|
||||||
|
expect(idBadges[0]).toHaveAttribute("data-id", "special-1");
|
||||||
|
expect(idBadges[1]).toHaveAttribute("data-id", "special-2");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { getChoiceIdByValue } from "@/lib/response/utils";
|
||||||
import { getContactIdentifier } from "@/lib/utils/contact";
|
import { getContactIdentifier } from "@/lib/utils/contact";
|
||||||
import { PersonAvatar } from "@/modules/ui/components/avatars";
|
import { PersonAvatar } from "@/modules/ui/components/avatars";
|
||||||
import { Button } from "@/modules/ui/components/button";
|
import { Button } from "@/modules/ui/components/button";
|
||||||
|
import { IdBadge } from "@/modules/ui/components/id-badge";
|
||||||
import { ProgressBar } from "@/modules/ui/components/progress-bar";
|
import { ProgressBar } from "@/modules/ui/components/progress-bar";
|
||||||
import { useTranslate } from "@tolgee/react";
|
import { useTranslate } from "@tolgee/react";
|
||||||
import { InboxIcon } from "lucide-react";
|
import { InboxIcon } from "lucide-react";
|
||||||
@@ -84,90 +86,95 @@ export const MultipleChoiceSummary = ({
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<div className="space-y-5 px-4 pb-6 pt-4 text-sm md:px-6 md:text-base">
|
<div className="space-y-5 px-4 pb-6 pt-4 text-sm md:px-6 md:text-base">
|
||||||
{results.map((result, resultsIdx) => (
|
{results.map((result, resultsIdx) => {
|
||||||
<Fragment key={result.value}>
|
const choiceId = getChoiceIdByValue(result.value, questionSummary.question);
|
||||||
<button
|
return (
|
||||||
className="group w-full cursor-pointer"
|
<Fragment key={result.value}>
|
||||||
onClick={() =>
|
<button
|
||||||
setFilter(
|
type="button"
|
||||||
questionSummary.question.id,
|
className="group w-full cursor-pointer"
|
||||||
questionSummary.question.headline,
|
onClick={() =>
|
||||||
questionSummary.question.type,
|
setFilter(
|
||||||
questionSummary.type === "multipleChoiceSingle" || otherValue === result.value
|
questionSummary.question.id,
|
||||||
? t("environments.surveys.summary.includes_either")
|
questionSummary.question.headline,
|
||||||
: t("environments.surveys.summary.includes_all"),
|
questionSummary.question.type,
|
||||||
[result.value]
|
questionSummary.type === "multipleChoiceSingle" || otherValue === result.value
|
||||||
)
|
? t("environments.surveys.summary.includes_either")
|
||||||
}>
|
: t("environments.surveys.summary.includes_all"),
|
||||||
<div className="text flex flex-col justify-between px-2 pb-2 sm:flex-row">
|
[result.value]
|
||||||
<div className="mr-8 flex w-full justify-between space-x-1 sm:justify-normal">
|
)
|
||||||
<p className="font-semibold text-slate-700 underline-offset-4 group-hover:underline">
|
}>
|
||||||
{results.length - resultsIdx} - {result.value}
|
<div className="text flex flex-col justify-between px-2 pb-2 sm:flex-row">
|
||||||
</p>
|
<div className="mr-8 flex w-full justify-between space-x-2 sm:justify-normal">
|
||||||
<div>
|
<p className="font-semibold text-slate-700 underline-offset-4 group-hover:underline">
|
||||||
|
{results.length - resultsIdx} - {result.value}
|
||||||
|
</p>
|
||||||
|
{choiceId && <IdBadge id={choiceId} />}
|
||||||
|
</div>
|
||||||
|
<div className="flex w-full space-x-2">
|
||||||
|
<p className="flex w-full pt-1 text-slate-600 sm:items-end sm:justify-end sm:pt-0">
|
||||||
|
{result.count} {result.count === 1 ? t("common.selection") : t("common.selections")}
|
||||||
|
</p>
|
||||||
<p className="rounded-lg bg-slate-100 px-2 text-slate-700">
|
<p className="rounded-lg bg-slate-100 px-2 text-slate-700">
|
||||||
{convertFloatToNDecimal(result.percentage, 2)}%
|
{convertFloatToNDecimal(result.percentage, 2)}%
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p className="flex w-full pt-1 text-slate-600 sm:items-end sm:justify-end sm:pt-0">
|
<div className="group-hover:opacity-80">
|
||||||
{result.count} {result.count === 1 ? t("common.selection") : t("common.selections")}
|
<ProgressBar barColor="bg-brand-dark" progress={result.percentage / 100} />
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="group-hover:opacity-80">
|
|
||||||
<ProgressBar barColor="bg-brand-dark" progress={result.percentage / 100} />
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
{result.others && result.others.length > 0 && (
|
|
||||||
<div className="mt-4 rounded-lg border border-slate-200">
|
|
||||||
<div className="grid h-12 grid-cols-2 content-center rounded-t-lg bg-slate-100 text-left text-sm font-semibold text-slate-900">
|
|
||||||
<div className="col-span-1 pl-6">
|
|
||||||
{t("environments.surveys.summary.other_values_found")}
|
|
||||||
</div>
|
|
||||||
<div className="col-span-1 pl-6">{surveyType === "app" && t("common.user")}</div>
|
|
||||||
</div>
|
</div>
|
||||||
{result.others
|
</button>
|
||||||
.filter((otherValue) => otherValue.value !== "")
|
{result.others && result.others.length > 0 && (
|
||||||
.slice(0, visibleOtherResponses)
|
<div className="mt-4 rounded-lg border border-slate-200">
|
||||||
.map((otherValue, idx) => (
|
<div className="grid h-12 grid-cols-2 content-center rounded-t-lg bg-slate-100 text-left text-sm font-semibold text-slate-900">
|
||||||
<div key={`${idx}-${otherValue}`} dir="auto">
|
<div className="col-span-1 pl-6">
|
||||||
{surveyType === "link" && (
|
{t("environments.surveys.summary.other_values_found")}
|
||||||
<div className="ph-no-capture col-span-1 m-2 flex h-10 items-center rounded-lg pl-4 text-sm font-medium text-slate-900">
|
</div>
|
||||||
<span>{otherValue.value}</span>
|
<div className="col-span-1 pl-6">{surveyType === "app" && t("common.user")}</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
{result.others
|
||||||
{surveyType === "app" && otherValue.contact && (
|
.filter((otherValue) => otherValue.value !== "")
|
||||||
<Link
|
.slice(0, visibleOtherResponses)
|
||||||
href={
|
.map((otherValue, idx) => (
|
||||||
otherValue.contact.id
|
<div key={`${idx}-${otherValue}`} dir="auto">
|
||||||
? `/environments/${environmentId}/contacts/${otherValue.contact.id}`
|
{surveyType === "link" && (
|
||||||
: { pathname: null }
|
<div className="ph-no-capture col-span-1 m-2 flex h-10 items-center rounded-lg pl-4 text-sm font-medium text-slate-900">
|
||||||
}
|
|
||||||
className="m-2 grid h-16 grid-cols-2 items-center rounded-lg text-sm hover:bg-slate-100">
|
|
||||||
<div className="ph-no-capture col-span-1 pl-4 font-medium text-slate-900">
|
|
||||||
<span>{otherValue.value}</span>
|
<span>{otherValue.value}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="ph-no-capture col-span-1 flex items-center space-x-4 pl-6 font-medium text-slate-900">
|
)}
|
||||||
{otherValue.contact.id && <PersonAvatar personId={otherValue.contact.id} />}
|
{surveyType === "app" && otherValue.contact && (
|
||||||
<span>
|
<Link
|
||||||
{getContactIdentifier(otherValue.contact, otherValue.contactAttributes)}
|
href={
|
||||||
</span>
|
otherValue.contact.id
|
||||||
</div>
|
? `/environments/${environmentId}/contacts/${otherValue.contact.id}`
|
||||||
</Link>
|
: { pathname: null }
|
||||||
)}
|
}
|
||||||
|
className="m-2 grid h-16 grid-cols-2 items-center rounded-lg text-sm hover:bg-slate-100">
|
||||||
|
<div className="ph-no-capture col-span-1 pl-4 font-medium text-slate-900">
|
||||||
|
<span>{otherValue.value}</span>
|
||||||
|
</div>
|
||||||
|
<div className="ph-no-capture col-span-1 flex items-center space-x-4 pl-6 font-medium text-slate-900">
|
||||||
|
{otherValue.contact.id && <PersonAvatar personId={otherValue.contact.id} />}
|
||||||
|
<span>
|
||||||
|
{getContactIdentifier(otherValue.contact, otherValue.contactAttributes)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{visibleOtherResponses < result.others.length && (
|
||||||
|
<div className="flex justify-center py-4">
|
||||||
|
<Button onClick={handleLoadMore} variant="secondary" size="sm">
|
||||||
|
{t("common.load_more")}
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
)}
|
||||||
{visibleOtherResponses < result.others.length && (
|
</div>
|
||||||
<div className="flex justify-center py-4">
|
)}
|
||||||
<Button onClick={handleLoadMore} variant="secondary" size="sm">
|
</Fragment>
|
||||||
{t("common.load_more")}
|
);
|
||||||
</Button>
|
})}
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</Fragment>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
import { cleanup, render, screen } from "@testing-library/react";
|
import { cleanup, render, screen } from "@testing-library/react";
|
||||||
import userEvent from "@testing-library/user-event";
|
import userEvent from "@testing-library/user-event";
|
||||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||||
import { TSurvey, TSurveyQuestionTypeEnum } from "@formbricks/types/surveys/types";
|
import {
|
||||||
|
TSurvey,
|
||||||
|
TSurveyPictureSelectionQuestion,
|
||||||
|
TSurveyQuestionTypeEnum,
|
||||||
|
} from "@formbricks/types/surveys/types";
|
||||||
import { PictureChoiceSummary } from "./PictureChoiceSummary";
|
import { PictureChoiceSummary } from "./PictureChoiceSummary";
|
||||||
|
|
||||||
vi.mock("@/modules/ui/components/progress-bar", () => ({
|
vi.mock("@/modules/ui/components/progress-bar", () => ({
|
||||||
@@ -12,6 +16,19 @@ vi.mock("@/modules/ui/components/progress-bar", () => ({
|
|||||||
vi.mock("./QuestionSummaryHeader", () => ({
|
vi.mock("./QuestionSummaryHeader", () => ({
|
||||||
QuestionSummaryHeader: ({ additionalInfo }: any) => <div data-testid="header">{additionalInfo}</div>,
|
QuestionSummaryHeader: ({ additionalInfo }: any) => <div data-testid="header">{additionalInfo}</div>,
|
||||||
}));
|
}));
|
||||||
|
vi.mock("@/modules/ui/components/id-badge", () => ({
|
||||||
|
IdBadge: ({ id }: { id: string }) => (
|
||||||
|
<div data-testid="id-badge" data-id={id}>
|
||||||
|
ID: {id}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/response/utils", () => ({
|
||||||
|
getChoiceIdByValue: (value: string, question: TSurveyPictureSelectionQuestion) => {
|
||||||
|
return question.choices?.find((choice) => choice.imageUrl === value)?.id ?? "other";
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
// mock next image
|
// mock next image
|
||||||
vi.mock("next/image", () => ({
|
vi.mock("next/image", () => ({
|
||||||
@@ -88,4 +105,73 @@ describe("PictureChoiceSummary", () => {
|
|||||||
|
|
||||||
expect(screen.getByTestId("header")).toBeEmptyDOMElement();
|
expect(screen.getByTestId("header")).toBeEmptyDOMElement();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// New tests for IdBadge functionality
|
||||||
|
test("renders IdBadge when choice ID is found via imageUrl", () => {
|
||||||
|
const choices = [
|
||||||
|
{ id: "choice1", imageUrl: "https://example.com/img1.png", percentage: 50, count: 5 },
|
||||||
|
{ id: "choice2", imageUrl: "https://example.com/img2.png", percentage: 50, count: 5 },
|
||||||
|
];
|
||||||
|
const questionSummary = {
|
||||||
|
choices,
|
||||||
|
question: {
|
||||||
|
id: "q2",
|
||||||
|
type: TSurveyQuestionTypeEnum.PictureSelection,
|
||||||
|
headline: "Picture Question",
|
||||||
|
allowMulti: true,
|
||||||
|
choices: [
|
||||||
|
{ id: "pic-choice-1", imageUrl: "https://example.com/img1.png" },
|
||||||
|
{ id: "pic-choice-2", imageUrl: "https://example.com/img2.png" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
selectionCount: 10,
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
render(<PictureChoiceSummary questionSummary={questionSummary} survey={survey} setFilter={() => {}} />);
|
||||||
|
|
||||||
|
const idBadges = screen.getAllByTestId("id-badge");
|
||||||
|
expect(idBadges).toHaveLength(2);
|
||||||
|
expect(idBadges[0]).toHaveAttribute("data-id", "pic-choice-1");
|
||||||
|
expect(idBadges[1]).toHaveAttribute("data-id", "pic-choice-2");
|
||||||
|
expect(idBadges[0]).toHaveTextContent("ID: pic-choice-1");
|
||||||
|
expect(idBadges[1]).toHaveTextContent("ID: pic-choice-2");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("getChoiceIdByValue function correctly maps imageUrl to choice ID", () => {
|
||||||
|
const choices = [
|
||||||
|
{ id: "choice1", imageUrl: "https://cdn.example.com/photo1.jpg", percentage: 33.33, count: 2 },
|
||||||
|
{ id: "choice2", imageUrl: "https://cdn.example.com/photo2.jpg", percentage: 33.33, count: 2 },
|
||||||
|
{ id: "choice3", imageUrl: "https://cdn.example.com/photo3.jpg", percentage: 33.33, count: 2 },
|
||||||
|
];
|
||||||
|
const questionSummary = {
|
||||||
|
choices,
|
||||||
|
question: {
|
||||||
|
id: "q4",
|
||||||
|
type: TSurveyQuestionTypeEnum.PictureSelection,
|
||||||
|
headline: "Photo Selection",
|
||||||
|
allowMulti: true,
|
||||||
|
choices: [
|
||||||
|
{ id: "photo-a", imageUrl: "https://cdn.example.com/photo1.jpg" },
|
||||||
|
{ id: "photo-b", imageUrl: "https://cdn.example.com/photo2.jpg" },
|
||||||
|
{ id: "photo-c", imageUrl: "https://cdn.example.com/photo3.jpg" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
selectionCount: 6,
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
render(<PictureChoiceSummary questionSummary={questionSummary} survey={survey} setFilter={() => {}} />);
|
||||||
|
|
||||||
|
const idBadges = screen.getAllByTestId("id-badge");
|
||||||
|
expect(idBadges).toHaveLength(3);
|
||||||
|
expect(idBadges[0]).toHaveAttribute("data-id", "photo-a");
|
||||||
|
expect(idBadges[1]).toHaveAttribute("data-id", "photo-b");
|
||||||
|
expect(idBadges[2]).toHaveAttribute("data-id", "photo-c");
|
||||||
|
|
||||||
|
// Verify the images are also rendered correctly
|
||||||
|
const images = screen.getAllByRole("img");
|
||||||
|
expect(images).toHaveLength(3);
|
||||||
|
expect(images[0]).toHaveAttribute("src", "https://cdn.example.com/photo1.jpg");
|
||||||
|
expect(images[1]).toHaveAttribute("src", "https://cdn.example.com/photo2.jpg");
|
||||||
|
expect(images[2]).toHaveAttribute("src", "https://cdn.example.com/photo3.jpg");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { getChoiceIdByValue } from "@/lib/response/utils";
|
||||||
|
import { IdBadge } from "@/modules/ui/components/id-badge";
|
||||||
import { ProgressBar } from "@/modules/ui/components/progress-bar";
|
import { ProgressBar } from "@/modules/ui/components/progress-bar";
|
||||||
import { useTranslate } from "@tolgee/react";
|
import { useTranslate } from "@tolgee/react";
|
||||||
import { InboxIcon } from "lucide-react";
|
import { InboxIcon } from "lucide-react";
|
||||||
@@ -29,6 +31,7 @@ interface PictureChoiceSummaryProps {
|
|||||||
export const PictureChoiceSummary = ({ questionSummary, survey, setFilter }: PictureChoiceSummaryProps) => {
|
export const PictureChoiceSummary = ({ questionSummary, survey, setFilter }: PictureChoiceSummaryProps) => {
|
||||||
const results = questionSummary.choices;
|
const results = questionSummary.choices;
|
||||||
const { t } = useTranslate();
|
const { t } = useTranslate();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="rounded-xl border border-slate-200 bg-white shadow-sm">
|
<div className="rounded-xl border border-slate-200 bg-white shadow-sm">
|
||||||
<QuestionSummaryHeader
|
<QuestionSummaryHeader
|
||||||
@@ -44,43 +47,48 @@ export const PictureChoiceSummary = ({ questionSummary, survey, setFilter }: Pic
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<div className="space-y-5 px-4 pb-6 pt-4 text-sm md:px-6 md:text-base">
|
<div className="space-y-5 px-4 pb-6 pt-4 text-sm md:px-6 md:text-base">
|
||||||
{results.map((result, index) => (
|
{results.map((result, index) => {
|
||||||
<button
|
const choiceId = getChoiceIdByValue(result.imageUrl, questionSummary.question);
|
||||||
className="w-full cursor-pointer hover:opacity-80"
|
return (
|
||||||
key={result.id}
|
<button
|
||||||
onClick={() =>
|
type="button"
|
||||||
setFilter(
|
className="w-full cursor-pointer hover:opacity-80"
|
||||||
questionSummary.question.id,
|
key={result.id}
|
||||||
questionSummary.question.headline,
|
onClick={() =>
|
||||||
questionSummary.question.type,
|
setFilter(
|
||||||
t("environments.surveys.summary.includes_all"),
|
questionSummary.question.id,
|
||||||
[`${t("environments.surveys.edit.picture_idx", { idx: index + 1 })}`]
|
questionSummary.question.headline,
|
||||||
)
|
questionSummary.question.type,
|
||||||
}>
|
t("environments.surveys.summary.includes_all"),
|
||||||
<div className="text flex flex-col justify-between px-2 pb-2 sm:flex-row">
|
[`${t("environments.surveys.edit.picture_idx", { idx: index + 1 })}`]
|
||||||
<div className="mr-8 flex w-full justify-between space-x-1 sm:justify-normal">
|
)
|
||||||
<div className="relative h-32 w-[220px]">
|
}>
|
||||||
<Image
|
<div className="text flex flex-col justify-between px-2 pb-2 sm:flex-row">
|
||||||
src={result.imageUrl}
|
<div className="mr-8 flex w-full justify-between space-x-2 sm:justify-normal">
|
||||||
alt="choice-image"
|
<div className="relative h-32 w-[220px]">
|
||||||
layout="fill"
|
<Image
|
||||||
objectFit="cover"
|
src={result.imageUrl}
|
||||||
className="rounded-md"
|
alt="choice-image"
|
||||||
/>
|
layout="fill"
|
||||||
|
objectFit="cover"
|
||||||
|
className="rounded-md"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="self-end">{choiceId && <IdBadge id={choiceId} />}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="self-end">
|
<div className="flex w-full space-x-2">
|
||||||
<p className="rounded-lg bg-slate-100 px-2 text-slate-700">
|
<p className="flex w-full pt-1 text-slate-600 sm:items-end sm:justify-end sm:pt-0">
|
||||||
|
{result.count} {result.count === 1 ? t("common.selection") : t("common.selections")}
|
||||||
|
</p>
|
||||||
|
<p className="self-end rounded-lg bg-slate-100 px-2 text-slate-700">
|
||||||
{convertFloatToNDecimal(result.percentage, 2)}%
|
{convertFloatToNDecimal(result.percentage, 2)}%
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p className="flex w-full pt-1 text-slate-600 sm:items-end sm:justify-end sm:pt-0">
|
<ProgressBar barColor="bg-brand-dark" progress={result.percentage / 100 || 0} />
|
||||||
{result.count} {result.count === 1 ? t("common.selection") : t("common.selections")}
|
</button>
|
||||||
</p>
|
);
|
||||||
</div>
|
})}
|
||||||
<ProgressBar barColor="bg-brand-dark" progress={result.percentage / 100 || 0} />
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -27,10 +27,10 @@ vi.mock("@/modules/survey/lib/questions", () => ({
|
|||||||
],
|
],
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("@/modules/ui/components/settings-id", () => ({
|
vi.mock("@/modules/ui/components/id-badge", () => ({
|
||||||
SettingsId: ({ title, id }: { title: string; id: string }) => (
|
IdBadge: ({ label, id }: { label: string; id: string }) => (
|
||||||
<div data-testid="settings-id">
|
<div data-testid="id-badge">
|
||||||
{title}: {id}
|
{label}: {id}
|
||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
}));
|
}));
|
||||||
@@ -76,7 +76,7 @@ describe("QuestionSummaryHeader", () => {
|
|||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
|
|
||||||
expect(screen.getByTestId("question-icon")).toBeInTheDocument();
|
expect(screen.getByTestId("question-icon")).toBeInTheDocument();
|
||||||
expect(screen.getByTestId("settings-id")).toHaveTextContent("common.question_id: q1");
|
expect(screen.getByTestId("id-badge")).toHaveTextContent("common.question_id: q1");
|
||||||
expect(screen.queryByText("environments.surveys.edit.optional")).not.toBeInTheDocument();
|
expect(screen.queryByText("environments.surveys.edit.optional")).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
import { recallToHeadline } from "@/lib/utils/recall";
|
import { recallToHeadline } from "@/lib/utils/recall";
|
||||||
import { formatTextWithSlashes } from "@/modules/survey/editor/lib/utils";
|
import { formatTextWithSlashes } from "@/modules/survey/editor/lib/utils";
|
||||||
import { getQuestionTypes } from "@/modules/survey/lib/questions";
|
import { getQuestionTypes } from "@/modules/survey/lib/questions";
|
||||||
import { SettingsId } from "@/modules/ui/components/settings-id";
|
import { IdBadge } from "@/modules/ui/components/id-badge";
|
||||||
import { useTranslate } from "@tolgee/react";
|
import { useTranslate } from "@tolgee/react";
|
||||||
import { InboxIcon } from "lucide-react";
|
import { InboxIcon } from "lucide-react";
|
||||||
import type { JSX } from "react";
|
import type { JSX } from "react";
|
||||||
@@ -55,7 +55,7 @@ export const QuestionSummaryHeader = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<SettingsId title={t("common.question_id")} id={questionSummary.question.id}></SettingsId>
|
<IdBadge id={questionSummary.question.id} label={t("common.question_id")} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { cleanup, render, screen } from "@testing-library/react";
|
import { cleanup, render, screen } from "@testing-library/react";
|
||||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||||
import { TSurvey, TSurveyQuestionSummaryRanking, TSurveyType } from "@formbricks/types/surveys/types";
|
import { TSurvey, TSurveyQuestionSummaryRanking } from "@formbricks/types/surveys/types";
|
||||||
import { RankingSummary } from "./RankingSummary";
|
import { RankingSummary } from "./RankingSummary";
|
||||||
|
|
||||||
// Mock dependencies
|
// Mock dependencies
|
||||||
@@ -12,17 +12,32 @@ vi.mock("../lib/utils", () => ({
|
|||||||
convertFloatToNDecimal: (value: number) => value.toFixed(2),
|
convertFloatToNDecimal: (value: number) => value.toFixed(2),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/modules/ui/components/id-badge", () => ({
|
||||||
|
IdBadge: ({ id }: { id: string }) => (
|
||||||
|
<div data-testid="id-badge" data-id={id}>
|
||||||
|
ID: {id}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
describe("RankingSummary", () => {
|
describe("RankingSummary", () => {
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
cleanup();
|
cleanup();
|
||||||
});
|
});
|
||||||
|
|
||||||
const survey = {} as TSurvey;
|
const survey = {} as TSurvey;
|
||||||
const surveyType: TSurveyType = "app";
|
|
||||||
|
|
||||||
test("renders ranking results in correct order", () => {
|
test("renders ranking results in correct order", () => {
|
||||||
const questionSummary = {
|
const questionSummary = {
|
||||||
question: { id: "q1", headline: "Rank the following" },
|
question: {
|
||||||
|
id: "q1",
|
||||||
|
headline: "Rank the following",
|
||||||
|
choices: [
|
||||||
|
{ id: "choice1", label: { default: "Option A" } },
|
||||||
|
{ id: "choice2", label: { default: "Option B" } },
|
||||||
|
{ id: "choice3", label: { default: "Option C" } },
|
||||||
|
],
|
||||||
|
},
|
||||||
choices: {
|
choices: {
|
||||||
option1: { value: "Option A", avgRanking: 1.5, others: [] },
|
option1: { value: "Option A", avgRanking: 1.5, others: [] },
|
||||||
option2: { value: "Option B", avgRanking: 2.3, others: [] },
|
option2: { value: "Option B", avgRanking: 2.3, others: [] },
|
||||||
@@ -30,7 +45,7 @@ describe("RankingSummary", () => {
|
|||||||
},
|
},
|
||||||
} as unknown as TSurveyQuestionSummaryRanking;
|
} as unknown as TSurveyQuestionSummaryRanking;
|
||||||
|
|
||||||
render(<RankingSummary questionSummary={questionSummary} survey={survey} surveyType={surveyType} />);
|
render(<RankingSummary questionSummary={questionSummary} survey={survey} />);
|
||||||
|
|
||||||
expect(screen.getByTestId("question-summary-header")).toBeInTheDocument();
|
expect(screen.getByTestId("question-summary-header")).toBeInTheDocument();
|
||||||
|
|
||||||
@@ -51,43 +66,13 @@ describe("RankingSummary", () => {
|
|||||||
expect(screen.getByText("#2.30")).toBeInTheDocument();
|
expect(screen.getByText("#2.30")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("renders 'other values found' section when others exist", () => {
|
|
||||||
const questionSummary = {
|
|
||||||
question: { id: "q1", headline: "Rank the following" },
|
|
||||||
choices: {
|
|
||||||
option1: {
|
|
||||||
value: "Option A",
|
|
||||||
avgRanking: 1.0,
|
|
||||||
others: [{ value: "Other value", count: 2 }],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as unknown as TSurveyQuestionSummaryRanking;
|
|
||||||
|
|
||||||
render(<RankingSummary questionSummary={questionSummary} survey={survey} surveyType={surveyType} />);
|
|
||||||
|
|
||||||
expect(screen.getByText("environments.surveys.summary.other_values_found")).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("shows 'User' column in other values section for app survey type", () => {
|
|
||||||
const questionSummary = {
|
|
||||||
question: { id: "q1", headline: "Rank the following" },
|
|
||||||
choices: {
|
|
||||||
option1: {
|
|
||||||
value: "Option A",
|
|
||||||
avgRanking: 1.0,
|
|
||||||
others: [{ value: "Other value", count: 1 }],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as unknown as TSurveyQuestionSummaryRanking;
|
|
||||||
|
|
||||||
render(<RankingSummary questionSummary={questionSummary} survey={survey} surveyType="app" />);
|
|
||||||
|
|
||||||
expect(screen.getByText("common.user")).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("doesn't show 'User' column for link survey type", () => {
|
test("doesn't show 'User' column for link survey type", () => {
|
||||||
const questionSummary = {
|
const questionSummary = {
|
||||||
question: { id: "q1", headline: "Rank the following" },
|
question: {
|
||||||
|
id: "q1",
|
||||||
|
headline: "Rank the following",
|
||||||
|
choices: [{ id: "choice1", label: { default: "Option A" } }],
|
||||||
|
},
|
||||||
choices: {
|
choices: {
|
||||||
option1: {
|
option1: {
|
||||||
value: "Option A",
|
value: "Option A",
|
||||||
@@ -97,8 +82,132 @@ describe("RankingSummary", () => {
|
|||||||
},
|
},
|
||||||
} as unknown as TSurveyQuestionSummaryRanking;
|
} as unknown as TSurveyQuestionSummaryRanking;
|
||||||
|
|
||||||
render(<RankingSummary questionSummary={questionSummary} survey={survey} surveyType="link" />);
|
render(<RankingSummary questionSummary={questionSummary} survey={survey} />);
|
||||||
|
|
||||||
expect(screen.queryByText("common.user")).not.toBeInTheDocument();
|
expect(screen.queryByText("common.user")).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// New tests for IdBadge functionality
|
||||||
|
test("renders IdBadge when choice ID is found via label", () => {
|
||||||
|
const questionSummary = {
|
||||||
|
question: {
|
||||||
|
id: "q2",
|
||||||
|
headline: "Rank these options",
|
||||||
|
choices: [
|
||||||
|
{ id: "rank-choice-1", label: { default: "First Option" } },
|
||||||
|
{ id: "rank-choice-2", label: { default: "Second Option" } },
|
||||||
|
{ id: "rank-choice-3", label: { default: "Third Option" } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
choices: {
|
||||||
|
option1: { value: "First Option", avgRanking: 1.5, others: [] },
|
||||||
|
option2: { value: "Second Option", avgRanking: 2.1, others: [] },
|
||||||
|
option3: { value: "Third Option", avgRanking: 2.8, others: [] },
|
||||||
|
},
|
||||||
|
} as unknown as TSurveyQuestionSummaryRanking;
|
||||||
|
|
||||||
|
render(<RankingSummary questionSummary={questionSummary} survey={survey} />);
|
||||||
|
|
||||||
|
const idBadges = screen.getAllByTestId("id-badge");
|
||||||
|
expect(idBadges).toHaveLength(3);
|
||||||
|
expect(idBadges[0]).toHaveAttribute("data-id", "rank-choice-1");
|
||||||
|
expect(idBadges[1]).toHaveAttribute("data-id", "rank-choice-2");
|
||||||
|
expect(idBadges[2]).toHaveAttribute("data-id", "rank-choice-3");
|
||||||
|
expect(idBadges[0]).toHaveTextContent("ID: rank-choice-1");
|
||||||
|
expect(idBadges[1]).toHaveTextContent("ID: rank-choice-2");
|
||||||
|
expect(idBadges[2]).toHaveTextContent("ID: rank-choice-3");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("getChoiceIdByValue function correctly maps ranking values to choice IDs", () => {
|
||||||
|
const questionSummary = {
|
||||||
|
question: {
|
||||||
|
id: "q4",
|
||||||
|
headline: "Rate importance",
|
||||||
|
choices: [
|
||||||
|
{ id: "importance-high", label: { default: "Very Important" } },
|
||||||
|
{ id: "importance-medium", label: { default: "Somewhat Important" } },
|
||||||
|
{ id: "importance-low", label: { default: "Not Important" } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
choices: {
|
||||||
|
option1: { value: "Very Important", avgRanking: 1.2, others: [] },
|
||||||
|
option2: { value: "Somewhat Important", avgRanking: 2.0, others: [] },
|
||||||
|
option3: { value: "Not Important", avgRanking: 2.8, others: [] },
|
||||||
|
},
|
||||||
|
} as unknown as TSurveyQuestionSummaryRanking;
|
||||||
|
|
||||||
|
render(<RankingSummary questionSummary={questionSummary} survey={survey} />);
|
||||||
|
|
||||||
|
const idBadges = screen.getAllByTestId("id-badge");
|
||||||
|
expect(idBadges).toHaveLength(3);
|
||||||
|
|
||||||
|
// Should be ordered by avgRanking (ascending)
|
||||||
|
expect(screen.getByText("Very Important")).toBeInTheDocument(); // avgRanking: 1.2
|
||||||
|
expect(screen.getByText("Somewhat Important")).toBeInTheDocument(); // avgRanking: 2.0
|
||||||
|
expect(screen.getByText("Not Important")).toBeInTheDocument(); // avgRanking: 2.8
|
||||||
|
|
||||||
|
expect(idBadges[0]).toHaveAttribute("data-id", "importance-high");
|
||||||
|
expect(idBadges[1]).toHaveAttribute("data-id", "importance-medium");
|
||||||
|
expect(idBadges[2]).toHaveAttribute("data-id", "importance-low");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("handles mixed choices with and without matching IDs", () => {
|
||||||
|
const questionSummary = {
|
||||||
|
question: {
|
||||||
|
id: "q5",
|
||||||
|
headline: "Mixed options",
|
||||||
|
choices: [
|
||||||
|
{ id: "valid-choice-1", label: { default: "Valid Option" } },
|
||||||
|
{ id: "valid-choice-2", label: { default: "Another Valid Option" } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
choices: {
|
||||||
|
option1: { value: "Valid Option", avgRanking: 1.5, others: [] },
|
||||||
|
option2: { value: "Unknown Option", avgRanking: 2.0, others: [] },
|
||||||
|
option3: { value: "Another Valid Option", avgRanking: 2.5, others: [] },
|
||||||
|
},
|
||||||
|
} as unknown as TSurveyQuestionSummaryRanking;
|
||||||
|
|
||||||
|
render(<RankingSummary questionSummary={questionSummary} survey={survey} />);
|
||||||
|
|
||||||
|
const idBadges = screen.getAllByTestId("id-badge");
|
||||||
|
expect(idBadges).toHaveLength(3); // Only 2 out of 3 should have badges
|
||||||
|
|
||||||
|
// Check that all options are still displayed
|
||||||
|
expect(screen.getByText("Valid Option")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Unknown Option")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Another Valid Option")).toBeInTheDocument();
|
||||||
|
|
||||||
|
// Check that only the valid choices have badges
|
||||||
|
expect(idBadges[0]).toHaveAttribute("data-id", "valid-choice-1");
|
||||||
|
expect(idBadges[1]).toHaveAttribute("data-id", "other");
|
||||||
|
expect(idBadges[2]).toHaveAttribute("data-id", "valid-choice-2");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("handles special characters in choice labels", () => {
|
||||||
|
const questionSummary = {
|
||||||
|
question: {
|
||||||
|
id: "q6",
|
||||||
|
headline: "Special characters test",
|
||||||
|
choices: [
|
||||||
|
{ id: "special-1", label: { default: "Option with 'quotes'" } },
|
||||||
|
{ id: "special-2", label: { default: "Option & Ampersand" } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
choices: {
|
||||||
|
option1: { value: "Option with 'quotes'", avgRanking: 1.0, others: [] },
|
||||||
|
option2: { value: "Option & Ampersand", avgRanking: 2.0, others: [] },
|
||||||
|
},
|
||||||
|
} as unknown as TSurveyQuestionSummaryRanking;
|
||||||
|
|
||||||
|
render(<RankingSummary questionSummary={questionSummary} survey={survey} />);
|
||||||
|
|
||||||
|
const idBadges = screen.getAllByTestId("id-badge");
|
||||||
|
expect(idBadges).toHaveLength(2);
|
||||||
|
expect(idBadges[0]).toHaveAttribute("data-id", "special-1");
|
||||||
|
expect(idBadges[1]).toHaveAttribute("data-id", "special-2");
|
||||||
|
|
||||||
|
expect(screen.getByText("Option with 'quotes'")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Option & Ampersand")).toBeInTheDocument();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,15 +1,16 @@
|
|||||||
|
import { getChoiceIdByValue } from "@/lib/response/utils";
|
||||||
|
import { IdBadge } from "@/modules/ui/components/id-badge";
|
||||||
import { useTranslate } from "@tolgee/react";
|
import { useTranslate } from "@tolgee/react";
|
||||||
import { TSurvey, TSurveyQuestionSummaryRanking, TSurveyType } from "@formbricks/types/surveys/types";
|
import { TSurvey, TSurveyQuestionSummaryRanking } from "@formbricks/types/surveys/types";
|
||||||
import { convertFloatToNDecimal } from "../lib/utils";
|
import { convertFloatToNDecimal } from "../lib/utils";
|
||||||
import { QuestionSummaryHeader } from "./QuestionSummaryHeader";
|
import { QuestionSummaryHeader } from "./QuestionSummaryHeader";
|
||||||
|
|
||||||
interface RankingSummaryProps {
|
interface RankingSummaryProps {
|
||||||
questionSummary: TSurveyQuestionSummaryRanking;
|
questionSummary: TSurveyQuestionSummaryRanking;
|
||||||
surveyType: TSurveyType;
|
|
||||||
survey: TSurvey;
|
survey: TSurvey;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const RankingSummary = ({ questionSummary, surveyType, survey }: RankingSummaryProps) => {
|
export const RankingSummary = ({ questionSummary, survey }: RankingSummaryProps) => {
|
||||||
// sort by count and transform to array
|
// sort by count and transform to array
|
||||||
const { t } = useTranslate();
|
const { t } = useTranslate();
|
||||||
const results = Object.values(questionSummary.choices).sort((a, b) => {
|
const results = Object.values(questionSummary.choices).sort((a, b) => {
|
||||||
@@ -20,35 +21,30 @@ export const RankingSummary = ({ questionSummary, surveyType, survey }: RankingS
|
|||||||
<div className="rounded-xl border border-slate-200 bg-white shadow-sm">
|
<div className="rounded-xl border border-slate-200 bg-white shadow-sm">
|
||||||
<QuestionSummaryHeader questionSummary={questionSummary} survey={survey} />
|
<QuestionSummaryHeader questionSummary={questionSummary} survey={survey} />
|
||||||
<div className="space-y-5 px-4 pb-6 pt-4 text-sm md:px-6 md:text-base">
|
<div className="space-y-5 px-4 pb-6 pt-4 text-sm md:px-6 md:text-base">
|
||||||
{results.map((result, resultsIdx) => (
|
{results.map((result, resultsIdx) => {
|
||||||
<div key={result.value} className="group cursor-pointer">
|
const choiceId = getChoiceIdByValue(result.value, questionSummary.question);
|
||||||
<div className="text flex flex-col justify-between px-2 pb-2 sm:flex-row">
|
return (
|
||||||
<div className="mr-8 flex w-full justify-between space-x-1 sm:justify-normal">
|
<div key={result.value} className="group cursor-pointer">
|
||||||
<div className="flex w-full items-center">
|
<div className="text flex flex-col justify-between px-2 pb-2 sm:flex-row">
|
||||||
<span className="mr-2 text-slate-400">#{resultsIdx + 1}</span>
|
<div className="mr-8 flex w-full justify-between space-x-2 sm:justify-normal">
|
||||||
<div className="rounded bg-slate-100 px-2 py-1">{result.value}</div>
|
<div className="flex w-full items-center">
|
||||||
<span className="ml-auto flex items-center space-x-1">
|
<div className="flex items-center space-x-2">
|
||||||
<span className="font-bold text-slate-600">
|
<span className="mr-2 text-slate-400">#{resultsIdx + 1}</span>
|
||||||
#{convertFloatToNDecimal(result.avgRanking, 2)}
|
<div className="rounded bg-slate-100 px-2 py-1">{result.value}</div>
|
||||||
|
{choiceId && <IdBadge id={choiceId} />}
|
||||||
|
</div>
|
||||||
|
<span className="ml-auto flex items-center space-x-1">
|
||||||
|
<span className="font-bold text-slate-600">
|
||||||
|
#{convertFloatToNDecimal(result.avgRanking, 2)}
|
||||||
|
</span>
|
||||||
|
<span>{t("environments.surveys.summary.average")}</span>
|
||||||
</span>
|
</span>
|
||||||
<span>{t("environments.surveys.summary.average")}</span>
|
</div>
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
);
|
||||||
{result.others && result.others.length > 0 && (
|
})}
|
||||||
<div className="mt-4 rounded-lg border border-slate-200">
|
|
||||||
<div className="grid h-12 grid-cols-2 content-center rounded-t-lg bg-slate-100 text-left text-sm font-semibold text-slate-900">
|
|
||||||
<div className="col-span-1 pl-6">
|
|
||||||
{t("environments.surveys.summary.other_values_found")}
|
|
||||||
</div>
|
|
||||||
<div className="col-span-1 pl-6">{surveyType === "app" && t("common.user")}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,150 +0,0 @@
|
|||||||
import { ShareSurveyResults } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/ShareSurveyResults";
|
|
||||||
import { cleanup, render, screen } from "@testing-library/react";
|
|
||||||
import userEvent from "@testing-library/user-event";
|
|
||||||
import { toast } from "react-hot-toast";
|
|
||||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
|
||||||
|
|
||||||
// Mock Button
|
|
||||||
vi.mock("@/modules/ui/components/button", () => ({
|
|
||||||
Button: vi.fn(({ children, onClick, asChild, ...props }: any) => {
|
|
||||||
if (asChild) {
|
|
||||||
// For 'asChild', Button renders its children, potentially passing props via Slot.
|
|
||||||
// Mocking simply renders children inside a div that can receive Button's props.
|
|
||||||
return <div {...props}>{children}</div>;
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
<button onClick={onClick} {...props}>
|
|
||||||
{children}
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Mock Dialog
|
|
||||||
vi.mock("@/modules/ui/components/dialog", () => ({
|
|
||||||
Dialog: vi.fn(({ children, open, onOpenChange }) =>
|
|
||||||
open ? (
|
|
||||||
<div data-testid="dialog" role="dialog">
|
|
||||||
{children}
|
|
||||||
<button onClick={() => onOpenChange(false)}>Close Dialog</button>
|
|
||||||
</div>
|
|
||||||
) : null
|
|
||||||
),
|
|
||||||
DialogContent: vi.fn(({ children, ...props }) => (
|
|
||||||
<div data-testid="dialog-content" {...props}>
|
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
)),
|
|
||||||
DialogBody: vi.fn(({ children }) => <div data-testid="dialog-body">{children}</div>),
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Mock useTranslate
|
|
||||||
vi.mock("@tolgee/react", () => ({
|
|
||||||
useTranslate: vi.fn(() => ({
|
|
||||||
t: (key: string) => key,
|
|
||||||
})),
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Mock Next Link
|
|
||||||
vi.mock("next/link", () => ({
|
|
||||||
default: vi.fn(({ children, href, target, rel, ...props }) => (
|
|
||||||
<a href={href} target={target} rel={rel} {...props}>
|
|
||||||
{children}
|
|
||||||
</a>
|
|
||||||
)),
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Mock react-hot-toast
|
|
||||||
vi.mock("react-hot-toast", () => ({
|
|
||||||
toast: {
|
|
||||||
success: vi.fn(),
|
|
||||||
error: vi.fn(),
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
const mockSetOpen = vi.fn();
|
|
||||||
const mockHandlePublish = vi.fn();
|
|
||||||
const mockHandleUnpublish = vi.fn();
|
|
||||||
const surveyUrl = "https://app.formbricks.com/s/some-survey-id";
|
|
||||||
|
|
||||||
const defaultProps = {
|
|
||||||
open: true,
|
|
||||||
setOpen: mockSetOpen,
|
|
||||||
handlePublish: mockHandlePublish,
|
|
||||||
handleUnpublish: mockHandleUnpublish,
|
|
||||||
showPublishModal: false,
|
|
||||||
surveyUrl: "",
|
|
||||||
};
|
|
||||||
|
|
||||||
describe("ShareSurveyResults", () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks();
|
|
||||||
// Mock navigator.clipboard
|
|
||||||
Object.defineProperty(global.navigator, "clipboard", {
|
|
||||||
value: {
|
|
||||||
writeText: vi.fn(() => Promise.resolve()),
|
|
||||||
},
|
|
||||||
configurable: true,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
cleanup();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("renders publish warning when showPublishModal is false", async () => {
|
|
||||||
render(<ShareSurveyResults {...defaultProps} />);
|
|
||||||
expect(screen.getByText("environments.surveys.summary.publish_to_web_warning")).toBeInTheDocument();
|
|
||||||
expect(
|
|
||||||
screen.getByText("environments.surveys.summary.publish_to_web_warning_description")
|
|
||||||
).toBeInTheDocument();
|
|
||||||
const publishButton = screen.getByText("environments.surveys.summary.publish_to_web");
|
|
||||||
expect(publishButton).toBeInTheDocument();
|
|
||||||
await userEvent.click(publishButton);
|
|
||||||
expect(mockHandlePublish).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("renders survey public info when showPublishModal is true and surveyUrl is provided", async () => {
|
|
||||||
render(<ShareSurveyResults {...defaultProps} showPublishModal={true} surveyUrl={surveyUrl} />);
|
|
||||||
expect(screen.getByText("environments.surveys.summary.survey_results_are_public")).toBeInTheDocument();
|
|
||||||
expect(
|
|
||||||
screen.getByText("environments.surveys.summary.survey_results_are_shared_with_anyone_who_has_the_link")
|
|
||||||
).toBeInTheDocument();
|
|
||||||
expect(screen.getByText(surveyUrl)).toBeInTheDocument();
|
|
||||||
|
|
||||||
const copyButton = screen.getByRole("button", { name: "Copy survey link to clipboard" });
|
|
||||||
expect(copyButton).toBeInTheDocument();
|
|
||||||
await userEvent.click(copyButton);
|
|
||||||
expect(navigator.clipboard.writeText).toHaveBeenCalledWith(surveyUrl);
|
|
||||||
expect(vi.mocked(toast.success)).toHaveBeenCalledWith("common.link_copied");
|
|
||||||
|
|
||||||
const unpublishButton = screen.getByText("environments.surveys.summary.unpublish_from_web");
|
|
||||||
expect(unpublishButton).toBeInTheDocument();
|
|
||||||
await userEvent.click(unpublishButton);
|
|
||||||
expect(mockHandleUnpublish).toHaveBeenCalledTimes(1);
|
|
||||||
|
|
||||||
const viewSiteLink = screen.getByText("environments.surveys.summary.view_site");
|
|
||||||
expect(viewSiteLink).toBeInTheDocument();
|
|
||||||
const anchor = viewSiteLink.closest("a");
|
|
||||||
expect(anchor).toHaveAttribute("href", surveyUrl);
|
|
||||||
expect(anchor).toHaveAttribute("target", "_blank");
|
|
||||||
expect(anchor).toHaveAttribute("rel", "noopener noreferrer");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("does not render content when modal is closed (open is false)", () => {
|
|
||||||
render(<ShareSurveyResults {...defaultProps} open={false} />);
|
|
||||||
expect(screen.queryByTestId("dialog")).not.toBeInTheDocument();
|
|
||||||
expect(screen.queryByText("environments.surveys.summary.publish_to_web_warning")).not.toBeInTheDocument();
|
|
||||||
expect(
|
|
||||||
screen.queryByText("environments.surveys.summary.survey_results_are_public")
|
|
||||||
).not.toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("renders publish warning if surveyUrl is empty even if showPublishModal is true", () => {
|
|
||||||
render(<ShareSurveyResults {...defaultProps} showPublishModal={true} surveyUrl="" />);
|
|
||||||
expect(screen.getByText("environments.surveys.summary.publish_to_web_warning")).toBeInTheDocument();
|
|
||||||
expect(
|
|
||||||
screen.queryByText("environments.surveys.summary.survey_results_are_public")
|
|
||||||
).not.toBeInTheDocument();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Button } from "@/modules/ui/components/button";
|
|
||||||
import { Dialog, DialogBody, DialogContent } from "@/modules/ui/components/dialog";
|
|
||||||
import { useTranslate } from "@tolgee/react";
|
|
||||||
import { AlertCircleIcon, CheckCircle2Icon } from "lucide-react";
|
|
||||||
import { Clipboard } from "lucide-react";
|
|
||||||
import Link from "next/link";
|
|
||||||
import { toast } from "react-hot-toast";
|
|
||||||
|
|
||||||
interface ShareEmbedSurveyProps {
|
|
||||||
open: boolean;
|
|
||||||
setOpen: React.Dispatch<React.SetStateAction<boolean>>;
|
|
||||||
handlePublish: () => void;
|
|
||||||
handleUnpublish: () => void;
|
|
||||||
showPublishModal: boolean;
|
|
||||||
surveyUrl: string;
|
|
||||||
}
|
|
||||||
export const ShareSurveyResults = ({
|
|
||||||
open,
|
|
||||||
setOpen,
|
|
||||||
handlePublish,
|
|
||||||
handleUnpublish,
|
|
||||||
showPublishModal,
|
|
||||||
surveyUrl,
|
|
||||||
}: ShareEmbedSurveyProps) => {
|
|
||||||
const { t } = useTranslate();
|
|
||||||
return (
|
|
||||||
<Dialog open={open} onOpenChange={setOpen}>
|
|
||||||
<DialogContent>
|
|
||||||
<DialogBody>
|
|
||||||
{showPublishModal && surveyUrl ? (
|
|
||||||
<div className="flex flex-col items-center gap-y-6 text-center">
|
|
||||||
<CheckCircle2Icon className="text-primary h-20 w-20" />
|
|
||||||
<div>
|
|
||||||
<p className="text-primary text-lg font-medium">
|
|
||||||
{t("environments.surveys.summary.survey_results_are_public")}
|
|
||||||
</p>
|
|
||||||
<p className="text-balanced mt-2 text-sm text-slate-500">
|
|
||||||
{t("environments.surveys.summary.survey_results_are_shared_with_anyone_who_has_the_link")}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<div className="whitespace-nowrap rounded-lg border border-slate-300 bg-white px-3 py-2 text-slate-800">
|
|
||||||
<span>{surveyUrl}</span>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
size="sm"
|
|
||||||
title="Copy survey link to clipboard"
|
|
||||||
aria-label="Copy survey link to clipboard"
|
|
||||||
className="hover:cursor-pointer"
|
|
||||||
onClick={() => {
|
|
||||||
navigator.clipboard.writeText(surveyUrl);
|
|
||||||
toast.success(t("common.link_copied"));
|
|
||||||
}}>
|
|
||||||
<Clipboard />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
variant="secondary"
|
|
||||||
className="text-center"
|
|
||||||
onClick={() => handleUnpublish()}>
|
|
||||||
{t("environments.surveys.summary.unpublish_from_web")}
|
|
||||||
</Button>
|
|
||||||
<Button className="text-center" asChild>
|
|
||||||
<Link href={surveyUrl} target="_blank" rel="noopener noreferrer">
|
|
||||||
{t("environments.surveys.summary.view_site")}
|
|
||||||
</Link>
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="flex flex-col rounded-2xl bg-white p-8">
|
|
||||||
<div className="flex flex-col items-center gap-y-6 text-center">
|
|
||||||
<AlertCircleIcon className="h-20 w-20 text-slate-300" />
|
|
||||||
<div>
|
|
||||||
<p className="text-lg font-medium text-slate-600">
|
|
||||||
{t("environments.surveys.summary.publish_to_web_warning")}
|
|
||||||
</p>
|
|
||||||
<p className="text-balanced mt-2 text-sm text-slate-500">
|
|
||||||
{t("environments.surveys.summary.publish_to_web_warning_description")}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Button type="submit" className="h-full text-center" onClick={() => handlePublish()}>
|
|
||||||
{t("environments.surveys.summary.publish_to_web")}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</DialogBody>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -74,7 +74,6 @@ describe("SuccessMessage", () => {
|
|||||||
surveyClosedMessage: null,
|
surveyClosedMessage: null,
|
||||||
hiddenFields: { enabled: false, fieldIds: [] },
|
hiddenFields: { enabled: false, fieldIds: [] },
|
||||||
variables: [],
|
variables: [],
|
||||||
resultShareKey: null,
|
|
||||||
displayPercentage: null,
|
displayPercentage: null,
|
||||||
} as unknown as TSurvey;
|
} as unknown as TSurvey;
|
||||||
|
|
||||||
|
|||||||
@@ -177,7 +177,6 @@ const mockSurvey = {
|
|||||||
autoClose: null,
|
autoClose: null,
|
||||||
triggers: [],
|
triggers: [],
|
||||||
languages: [],
|
languages: [],
|
||||||
resultShareKey: null,
|
|
||||||
singleUse: null,
|
singleUse: null,
|
||||||
styling: null,
|
styling: null,
|
||||||
surveyClosedMessage: null,
|
surveyClosedMessage: null,
|
||||||
@@ -192,7 +191,7 @@ const mockSurvey = {
|
|||||||
variables: [],
|
variables: [],
|
||||||
} as unknown as TSurvey;
|
} as unknown as TSurvey;
|
||||||
|
|
||||||
const mockSelectedFilter = { filter: [], onlyComplete: false };
|
const mockSelectedFilter = { filter: [], responseStatus: "all" };
|
||||||
const mockSetSelectedFilter = vi.fn();
|
const mockSetSelectedFilter = vi.fn();
|
||||||
|
|
||||||
const defaultProps = {
|
const defaultProps = {
|
||||||
@@ -310,17 +309,13 @@ describe("SummaryList", () => {
|
|||||||
|
|
||||||
test("renders EmptySpaceFiller when responseCount is 0 and summary is not empty (no responses match filter)", () => {
|
test("renders EmptySpaceFiller when responseCount is 0 and summary is not empty (no responses match filter)", () => {
|
||||||
const summaryWithItem = [createMockQuestionSummary("q1", TSurveyQuestionTypeEnum.OpenText)];
|
const summaryWithItem = [createMockQuestionSummary("q1", TSurveyQuestionTypeEnum.OpenText)];
|
||||||
render(
|
render(<SummaryList {...defaultProps} summary={summaryWithItem} responseCount={0} />);
|
||||||
<SummaryList {...defaultProps} summary={summaryWithItem} responseCount={0} totalResponseCount={10} />
|
|
||||||
);
|
|
||||||
expect(screen.getByText("Mocked EmptySpaceFiller")).toBeInTheDocument();
|
expect(screen.getByText("Mocked EmptySpaceFiller")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("renders EmptySpaceFiller when responseCount is 0 and totalResponseCount is 0 (no responses at all)", () => {
|
test("renders EmptySpaceFiller when responseCount is 0 and totalResponseCount is 0 (no responses at all)", () => {
|
||||||
const summaryWithItem = [createMockQuestionSummary("q1", TSurveyQuestionTypeEnum.OpenText)];
|
const summaryWithItem = [createMockQuestionSummary("q1", TSurveyQuestionTypeEnum.OpenText)];
|
||||||
render(
|
render(<SummaryList {...defaultProps} summary={summaryWithItem} responseCount={0} />);
|
||||||
<SummaryList {...defaultProps} summary={summaryWithItem} responseCount={0} totalResponseCount={0} />
|
|
||||||
);
|
|
||||||
expect(screen.getByText("Mocked EmptySpaceFiller")).toBeInTheDocument();
|
expect(screen.getByText("Mocked EmptySpaceFiller")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -398,7 +393,7 @@ describe("SummaryList", () => {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
onlyComplete: false,
|
responseStatus: "all",
|
||||||
});
|
});
|
||||||
// Ensure vi.mocked(toast.success) refers to the spy from the named export
|
// Ensure vi.mocked(toast.success) refers to the spy from the named export
|
||||||
expect(vi.mocked(toast).success).toHaveBeenCalledWith("Custom add message", { duration: 5000 });
|
expect(vi.mocked(toast).success).toHaveBeenCalledWith("Custom add message", { duration: 5000 });
|
||||||
@@ -426,7 +421,7 @@ describe("SummaryList", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
vi.mocked(useResponseFilter).mockReturnValue({
|
vi.mocked(useResponseFilter).mockReturnValue({
|
||||||
selectedFilter: { filter: [existingFilter], onlyComplete: false },
|
selectedFilter: { filter: [existingFilter], responseStatus: "all" },
|
||||||
setSelectedFilter: mockSetSelectedFilter,
|
setSelectedFilter: mockSetSelectedFilter,
|
||||||
resetFilter: vi.fn(),
|
resetFilter: vi.fn(),
|
||||||
} as any);
|
} as any);
|
||||||
@@ -455,7 +450,7 @@ describe("SummaryList", () => {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
onlyComplete: false,
|
responseStatus: "all",
|
||||||
});
|
});
|
||||||
expect(vi.mocked(toast.success)).toHaveBeenCalledWith(
|
expect(vi.mocked(toast.success)).toHaveBeenCalledWith(
|
||||||
"environments.surveys.summary.filter_updated_successfully",
|
"environments.surveys.summary.filter_updated_successfully",
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user