mirror of
https://github.com/formbricks/formbricks.git
synced 2026-01-06 05:40:02 -06:00
Compare commits
1 Commits
fix/e2e-ci
...
fix/local-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fdfbed26f5 |
@@ -16,10 +16,9 @@ Formbricks uses a **hybrid caching approach** optimized for enterprise scale:
|
|||||||
## Key Files
|
## Key Files
|
||||||
|
|
||||||
### Core Cache Infrastructure
|
### Core Cache Infrastructure
|
||||||
- [packages/cache/src/service.ts](mdc:packages/cache/src/service.ts) - Redis cache service
|
- [apps/web/modules/cache/lib/service.ts](mdc:apps/web/modules/cache/lib/service.ts) - Redis cache service
|
||||||
- [packages/cache/src/client.ts](mdc:packages/cache/src/client.ts) - Cache client initialization and singleton management
|
- [apps/web/modules/cache/lib/withCache.ts](mdc:apps/web/modules/cache/lib/withCache.ts) - Cache wrapper utilities
|
||||||
- [apps/web/lib/cache/index.ts](mdc:apps/web/lib/cache/index.ts) - Cache service proxy for web app
|
- [apps/web/modules/cache/lib/cacheKeys.ts](mdc:apps/web/modules/cache/lib/cacheKeys.ts) - Enterprise cache key patterns and utilities
|
||||||
- [packages/cache/src/index.ts](mdc:packages/cache/src/index.ts) - Cache package exports and utilities
|
|
||||||
|
|
||||||
### Environment State Caching (Critical Endpoint)
|
### Environment State Caching (Critical Endpoint)
|
||||||
- [apps/web/app/api/v1/client/[environmentId]/environment/route.ts](mdc:apps/web/app/api/v1/client/[environmentId]/environment/route.ts) - Main endpoint serving hundreds of thousands of SDK clients
|
- [apps/web/app/api/v1/client/[environmentId]/environment/route.ts](mdc:apps/web/app/api/v1/client/[environmentId]/environment/route.ts) - Main endpoint serving hundreds of thousands of SDK clients
|
||||||
@@ -27,7 +26,7 @@ Formbricks uses a **hybrid caching approach** optimized for enterprise scale:
|
|||||||
|
|
||||||
## Enterprise-Grade Cache Key Patterns
|
## Enterprise-Grade Cache Key Patterns
|
||||||
|
|
||||||
**Always use** the `createCacheKey` utilities from the cache package:
|
**Always use** the `createCacheKey` utilities from [cacheKeys.ts](mdc:apps/web/modules/cache/lib/cacheKeys.ts):
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// ✅ Correct patterns
|
// ✅ Correct patterns
|
||||||
@@ -51,14 +50,14 @@ export const getEnterpriseLicense = reactCache(async () => {
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
### Use `cache.withCache()` for Simple Database Queries
|
### Use `withCache()` for Simple Database Queries
|
||||||
```typescript
|
```typescript
|
||||||
// ✅ Simple caching with automatic fallback (TTL in milliseconds)
|
// ✅ Simple caching with automatic fallback (TTL in milliseconds)
|
||||||
export const getActionClasses = (environmentId: string) => {
|
export const getActionClasses = (environmentId: string) => {
|
||||||
return cache.withCache(() => fetchActionClassesFromDB(environmentId),
|
return withCache(() => fetchActionClassesFromDB(environmentId), {
|
||||||
createCacheKey.environment.actionClasses(environmentId),
|
key: createCacheKey.environment.actionClasses(environmentId),
|
||||||
60 * 30 * 1000 // 30 minutes in milliseconds
|
ttl: 60 * 30 * 1000, // 30 minutes in milliseconds
|
||||||
);
|
})();
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ description: >
|
|||||||
globs: []
|
globs: []
|
||||||
alwaysApply: agent-requested
|
alwaysApply: agent-requested
|
||||||
---
|
---
|
||||||
|
|
||||||
# Formbricks Database Schema Reference
|
# Formbricks Database Schema Reference
|
||||||
|
|
||||||
This rule provides a reference to the Formbricks database structure. For the most up-to-date and complete schema definitions, please refer to the schema.prisma file directly.
|
This rule provides a reference to the Formbricks database structure. For the most up-to-date and complete schema definitions, please refer to the schema.prisma file directly.
|
||||||
@@ -17,7 +16,6 @@ This rule provides a reference to the Formbricks database structure. For the mos
|
|||||||
Formbricks uses PostgreSQL with Prisma ORM. The schema is designed for multi-tenancy with strong data isolation between organizations.
|
Formbricks uses PostgreSQL with Prisma ORM. The schema is designed for multi-tenancy with strong data isolation between organizations.
|
||||||
|
|
||||||
### Core Hierarchy
|
### Core Hierarchy
|
||||||
|
|
||||||
```
|
```
|
||||||
Organization
|
Organization
|
||||||
└── Project
|
└── Project
|
||||||
@@ -31,7 +29,6 @@ Organization
|
|||||||
## Schema Reference
|
## Schema Reference
|
||||||
|
|
||||||
For the complete and up-to-date database schema, please refer to:
|
For the complete and up-to-date database schema, please refer to:
|
||||||
|
|
||||||
- Main schema: `packages/database/schema.prisma`
|
- Main schema: `packages/database/schema.prisma`
|
||||||
- JSON type definitions: `packages/database/json-types.ts`
|
- JSON type definitions: `packages/database/json-types.ts`
|
||||||
|
|
||||||
@@ -40,22 +37,17 @@ The schema.prisma file contains all model definitions, relationships, enums, and
|
|||||||
## Data Access Patterns
|
## Data Access Patterns
|
||||||
|
|
||||||
### Multi-tenancy
|
### Multi-tenancy
|
||||||
|
|
||||||
- All data is scoped by Organization
|
- All data is scoped by Organization
|
||||||
- Environment-level isolation for surveys and contacts
|
- Environment-level isolation for surveys and contacts
|
||||||
- Project-level grouping for related surveys
|
- Project-level grouping for related surveys
|
||||||
|
|
||||||
### Soft Deletion
|
### Soft Deletion
|
||||||
|
|
||||||
Some models use soft deletion patterns:
|
Some models use soft deletion patterns:
|
||||||
|
|
||||||
- Check `isActive` fields where present
|
- Check `isActive` fields where present
|
||||||
- Use proper filtering in queries
|
- Use proper filtering in queries
|
||||||
|
|
||||||
### Cascading Deletes
|
### Cascading Deletes
|
||||||
|
|
||||||
Configured cascade relationships:
|
Configured cascade relationships:
|
||||||
|
|
||||||
- Organization deletion cascades to all child entities
|
- Organization deletion cascades to all child entities
|
||||||
- Survey deletion removes responses, displays, triggers
|
- Survey deletion removes responses, displays, triggers
|
||||||
- Contact deletion removes attributes and responses
|
- Contact deletion removes attributes and responses
|
||||||
@@ -63,7 +55,6 @@ Configured cascade relationships:
|
|||||||
## Common Query Patterns
|
## Common Query Patterns
|
||||||
|
|
||||||
### Survey with Responses
|
### Survey with Responses
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// Include response count and latest responses
|
// Include response count and latest responses
|
||||||
const survey = await prisma.survey.findUnique({
|
const survey = await prisma.survey.findUnique({
|
||||||
@@ -71,40 +62,40 @@ const survey = await prisma.survey.findUnique({
|
|||||||
include: {
|
include: {
|
||||||
responses: {
|
responses: {
|
||||||
take: 10,
|
take: 10,
|
||||||
orderBy: { createdAt: "desc" },
|
orderBy: { createdAt: 'desc' }
|
||||||
},
|
},
|
||||||
_count: {
|
_count: {
|
||||||
select: { responses: true },
|
select: { responses: true }
|
||||||
},
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
### Environment Scoping
|
### Environment Scoping
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// Always scope by environment
|
// Always scope by environment
|
||||||
const surveys = await prisma.survey.findMany({
|
const surveys = await prisma.survey.findMany({
|
||||||
where: {
|
where: {
|
||||||
environmentId: environmentId,
|
environmentId: environmentId,
|
||||||
// Additional filters...
|
// Additional filters...
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
### Contact with Attributes
|
### Contact with Attributes
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
const contact = await prisma.contact.findUnique({
|
const contact = await prisma.contact.findUnique({
|
||||||
where: { id: contactId },
|
where: { id: contactId },
|
||||||
include: {
|
include: {
|
||||||
attributes: {
|
attributes: {
|
||||||
include: {
|
include: {
|
||||||
attributeKey: true,
|
attributeKey: true
|
||||||
},
|
}
|
||||||
},
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
This schema supports Formbricks' core functionality: multi-tenant survey management, user targeting, response collection, and analysis, all while maintaining strict data isolation and security.
|
This schema supports Formbricks' core functionality: multi-tenant survey management, user targeting, response collection, and analysis, all while maintaining strict data isolation and security.
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
---
|
|
||||||
description: Guideline for writing end-user facing documentation in the apps/docs folder
|
|
||||||
globs:
|
|
||||||
alwaysApply: false
|
|
||||||
---
|
|
||||||
|
|
||||||
Follow these instructions and guidelines when asked to write documentation in the apps/docs folder
|
|
||||||
|
|
||||||
Follow this structure to write the title, describtion and pick a matching icon and insert it at the top of the MDX file:
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
title: "FEATURE NAME"
|
|
||||||
description: "1 concise sentence to describe WHEN the feature is being used and FOR WHAT BENEFIT."
|
|
||||||
icon: "link"
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
- Description: 1 concise sentence to describe WHEN the feature is being used and FOR WHAT BENEFIT.
|
|
||||||
- Make ample use of the Mintlify components you can find here https://mintlify.com/docs/llms.txt - e.g. if docs describe consecutive steps, always use Mintlify Step component.
|
|
||||||
- In all Headlines, only capitalize the current feature and nothing else, to Camel Case.
|
|
||||||
- The page should never start with H1 headline, because it's already part of the template.
|
|
||||||
- Tonality: Keep it concise and to the point. Avoid Jargon where possible.
|
|
||||||
- If a feature is part of the Enterprise Edition, use this note:
|
|
||||||
|
|
||||||
<Note>
|
|
||||||
FEATURE NAME is part of the [Enterprise Edition](/self-hosting/advanced/license)
|
|
||||||
</Note>
|
|
||||||
@@ -18,6 +18,7 @@ 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
|
||||||
@@ -42,6 +43,7 @@ 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
|
||||||
|
|
||||||
|
|||||||
@@ -1,232 +0,0 @@
|
|||||||
---
|
|
||||||
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,216 +0,0 @@
|
|||||||
---
|
|
||||||
description: Migrate deprecated UI components to a unified component
|
|
||||||
globs:
|
|
||||||
alwaysApply: false
|
|
||||||
---
|
|
||||||
# Component Migration Automation Rule
|
|
||||||
|
|
||||||
## Overview
|
|
||||||
This rule automates the migration of deprecated components to new component systems in React/TypeScript codebases.
|
|
||||||
|
|
||||||
## Trigger
|
|
||||||
When the user requests component migration (e.g., "migrate [DeprecatedComponent] to [NewComponent]" or "component migration").
|
|
||||||
|
|
||||||
## Process
|
|
||||||
|
|
||||||
### Step 1: Discovery and Planning
|
|
||||||
1. **Identify migration parameters:**
|
|
||||||
- Ask user for deprecated component name (e.g., "Modal")
|
|
||||||
- Ask user for new component name(s) (e.g., "Dialog")
|
|
||||||
- Ask for any components to exclude (e.g., "ModalWithTabs")
|
|
||||||
- Ask for specific import paths if needed
|
|
||||||
|
|
||||||
2. **Scan codebase** for deprecated components:
|
|
||||||
- Search for `import.*[DeprecatedComponent]` patterns
|
|
||||||
- Exclude specified components that should not be migrated
|
|
||||||
- List all found components with file paths
|
|
||||||
- Present numbered list to user for confirmation
|
|
||||||
|
|
||||||
### Step 2: Component-by-Component Migration
|
|
||||||
For each component, follow this exact sequence:
|
|
||||||
|
|
||||||
#### 2.1 Component Migration
|
|
||||||
- **Import changes:**
|
|
||||||
- Ask user to provide the new import structure
|
|
||||||
- Example transformation pattern:
|
|
||||||
```typescript
|
|
||||||
// FROM:
|
|
||||||
import { [DeprecatedComponent] } from "@/components/ui/[DeprecatedComponent]"
|
|
||||||
|
|
||||||
// TO:
|
|
||||||
import {
|
|
||||||
[NewComponent],
|
|
||||||
[NewComponentPart1],
|
|
||||||
[NewComponentPart2],
|
|
||||||
// ... other parts
|
|
||||||
} from "@/components/ui/[NewComponent]"
|
|
||||||
```
|
|
||||||
|
|
||||||
- **Props transformation:**
|
|
||||||
- Ask user for prop mapping rules (e.g., `open` → `open`, `setOpen` → `onOpenChange`)
|
|
||||||
- Ask for props to remove (e.g., `noPadding`, `closeOnOutsideClick`, `size`)
|
|
||||||
- Apply transformations based on user specifications
|
|
||||||
|
|
||||||
- **Structure transformation:**
|
|
||||||
- Ask user for the new component structure pattern
|
|
||||||
- Apply the transformation maintaining all functionality
|
|
||||||
- Preserve all existing logic, state management, and event handlers
|
|
||||||
|
|
||||||
#### 2.2 Wait for User Approval
|
|
||||||
- Present the migration changes
|
|
||||||
- Wait for explicit user approval before proceeding
|
|
||||||
- If rejected, ask for specific feedback and iterate
|
|
||||||
#### 2.3 Re-read and Apply Additional Changes
|
|
||||||
- Re-read the component file to capture any user modifications
|
|
||||||
- Apply any additional improvements the user made
|
|
||||||
- Ensure all changes are incorporated
|
|
||||||
|
|
||||||
#### 2.4 Test File Updates
|
|
||||||
- **Find corresponding test file** (same name with `.test.tsx` or `.test.ts`)
|
|
||||||
- **Update test mocks:**
|
|
||||||
- Ask user for new component mock structure
|
|
||||||
- Replace old component mocks with new ones
|
|
||||||
- Example pattern:
|
|
||||||
```typescript
|
|
||||||
// Add to test setup:
|
|
||||||
jest.mock("@/components/ui/[NewComponent]", () => ({
|
|
||||||
[NewComponent]: ({ children, [props] }: any) => ([mock implementation]),
|
|
||||||
[NewComponentPart1]: ({ children }: any) => <div data-testid="[new-component-part1]">{children}</div>,
|
|
||||||
[NewComponentPart2]: ({ children }: any) => <div data-testid="[new-component-part2]">{children}</div>,
|
|
||||||
// ... other parts
|
|
||||||
}));
|
|
||||||
```
|
|
||||||
- **Update test expectations:**
|
|
||||||
- Change test IDs from old component to new component
|
|
||||||
- Update any component-specific assertions
|
|
||||||
- Ensure all new component parts used in the component are mocked
|
|
||||||
|
|
||||||
#### 2.5 Run Tests and Optimize
|
|
||||||
- Execute `Node package manager test -- ComponentName.test.tsx`
|
|
||||||
- Fix any failing tests
|
|
||||||
- Optimize code quality (imports, formatting, etc.)
|
|
||||||
- Re-run tests until all pass
|
|
||||||
- **Maximum 3 iterations** - if still failing, ask user for guidance
|
|
||||||
|
|
||||||
#### 2.6 Wait for Final Approval
|
|
||||||
- Present test results and any optimizations made
|
|
||||||
- Wait for user approval of the complete migration
|
|
||||||
- If rejected, iterate based on feedback
|
|
||||||
|
|
||||||
#### 2.7 Git Commit
|
|
||||||
- Run: `git add .`
|
|
||||||
- Run: `git commit -m "migrate [ComponentName] from [DeprecatedComponent] to [NewComponent]"`
|
|
||||||
- Confirm commit was successful
|
|
||||||
|
|
||||||
### Step 3: Final Report Generation
|
|
||||||
After all components are migrated, generate a comprehensive GitHub PR report:
|
|
||||||
|
|
||||||
#### PR Title
|
|
||||||
```
|
|
||||||
feat: migrate [DeprecatedComponent] components to [NewComponent] system
|
|
||||||
```
|
|
||||||
|
|
||||||
#### PR Description Template
|
|
||||||
```markdown
|
|
||||||
## 🔄 [DeprecatedComponent] to [NewComponent] Migration
|
|
||||||
|
|
||||||
### Overview
|
|
||||||
Migrated [X] [DeprecatedComponent] components to the new [NewComponent] component system to modernize the UI architecture and improve consistency.
|
|
||||||
|
|
||||||
### Components Migrated
|
|
||||||
[List each component with file path]
|
|
||||||
|
|
||||||
### Technical Changes
|
|
||||||
- **Imports:** Replaced `[DeprecatedComponent]` with `[NewComponent], [NewComponentParts...]`
|
|
||||||
- **Props:** [List prop transformations]
|
|
||||||
- **Structure:** Implemented proper [NewComponent] component hierarchy
|
|
||||||
- **Styling:** [Describe styling changes]
|
|
||||||
- **Tests:** Updated all test mocks and expectations
|
|
||||||
|
|
||||||
### Migration Pattern
|
|
||||||
```typescript
|
|
||||||
// Before
|
|
||||||
<[DeprecatedComponent] [oldProps]>
|
|
||||||
[oldStructure]
|
|
||||||
</[DeprecatedComponent]>
|
|
||||||
|
|
||||||
// After
|
|
||||||
<[NewComponent] [newProps]>
|
|
||||||
[newStructure]
|
|
||||||
</[NewComponent]>
|
|
||||||
```
|
|
||||||
|
|
||||||
### Testing
|
|
||||||
- ✅ All existing tests updated and passing
|
|
||||||
- ✅ Component functionality preserved
|
|
||||||
- ✅ UI/UX behavior maintained
|
|
||||||
|
|
||||||
### How to Test This PR
|
|
||||||
1. **Functional Testing:**
|
|
||||||
- Navigate to each migrated component's usage
|
|
||||||
- Verify [component] opens and closes correctly
|
|
||||||
- Test all interactive elements within [components]
|
|
||||||
- Confirm styling and layout are preserved
|
|
||||||
|
|
||||||
2. **Automated Testing:**
|
|
||||||
```bash
|
|
||||||
Node package manager test
|
|
||||||
```
|
|
||||||
|
|
||||||
3. **Visual Testing:**
|
|
||||||
- Check that all [components] maintain proper styling
|
|
||||||
- Verify responsive behavior
|
|
||||||
- Test keyboard navigation and accessibility
|
|
||||||
|
|
||||||
### Breaking Changes
|
|
||||||
[List any breaking changes or state "None - this is a drop-in replacement maintaining all existing functionality."]
|
|
||||||
|
|
||||||
### Notes
|
|
||||||
- [Any excluded components] were preserved as they already use [NewComponent] internally
|
|
||||||
- All form validation and complex state management preserved
|
|
||||||
- Enhanced code quality with better imports and formatting
|
|
||||||
```
|
|
||||||
|
|
||||||
## Special Considerations
|
|
||||||
|
|
||||||
### Excluded Components
|
|
||||||
- **DO NOT MIGRATE** components specified by user as exclusions
|
|
||||||
- They may already use the new component internally or have other reasons
|
|
||||||
- Inform user these are skipped and why
|
|
||||||
|
|
||||||
### Complex Components
|
|
||||||
- Preserve all existing functionality (forms, validation, state management)
|
|
||||||
- Maintain prop interfaces
|
|
||||||
- Keep all event handlers and callbacks
|
|
||||||
- Preserve accessibility features
|
|
||||||
|
|
||||||
### Test Coverage
|
|
||||||
- Ensure all new component parts are mocked when used
|
|
||||||
- Mock all new component parts that appear in the component
|
|
||||||
- Update test IDs from old component to new component
|
|
||||||
- Maintain all existing test scenarios
|
|
||||||
|
|
||||||
### Error Handling
|
|
||||||
- If tests fail after 3 iterations, stop and ask user for guidance
|
|
||||||
- If component is too complex, ask user for specific guidance
|
|
||||||
- If unsure about functionality preservation, ask for clarification
|
|
||||||
|
|
||||||
### Migration Patterns
|
|
||||||
- Always ask user for specific migration patterns before starting
|
|
||||||
- Confirm import structures, prop mappings, and component hierarchies
|
|
||||||
- Adapt to different component architectures (simple replacements, complex restructuring, etc.)
|
|
||||||
|
|
||||||
## Success Criteria
|
|
||||||
- All deprecated components successfully migrated to new components
|
|
||||||
- All tests passing
|
|
||||||
- No functionality lost
|
|
||||||
- Code quality maintained or improved
|
|
||||||
- User approval on each component
|
|
||||||
- Successful git commits for each migration
|
|
||||||
- Comprehensive PR report generated
|
|
||||||
|
|
||||||
## Usage Examples
|
|
||||||
- "migrate Modal to Dialog"
|
|
||||||
- "migrate Button to NewButton"
|
|
||||||
- "migrate Card to ModernCard"
|
|
||||||
- "component migration" (will prompt for details)
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
---
|
|
||||||
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: [],
|
||||||
responseStatus: "all",
|
onlyComplete: false,
|
||||||
},
|
},
|
||||||
setSelectedFilter: vi.fn(),
|
setSelectedFilter: vi.fn(),
|
||||||
selectedOptions: {
|
selectedOptions: {
|
||||||
@@ -291,6 +291,11 @@ 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(() => {
|
||||||
|
|||||||
17
.env.example
17
.env.example
@@ -62,6 +62,9 @@ SMTP_PASSWORD=smtpPassword
|
|||||||
|
|
||||||
# Uncomment the variables you would like to use and customize the values.
|
# Uncomment the variables you would like to use and customize the values.
|
||||||
|
|
||||||
|
# Custom local storage path for file uploads
|
||||||
|
#UPLOADS_DIR=
|
||||||
|
|
||||||
##############
|
##############
|
||||||
# S3 STORAGE #
|
# S3 STORAGE #
|
||||||
##############
|
##############
|
||||||
@@ -77,8 +80,8 @@ S3_ENDPOINT_URL=
|
|||||||
# Force path style for S3 compatible storage (0 for disabled, 1 for enabled)
|
# Force path style for S3 compatible storage (0 for disabled, 1 for enabled)
|
||||||
S3_FORCE_PATH_STYLE=0
|
S3_FORCE_PATH_STYLE=0
|
||||||
|
|
||||||
# Set this URL to add a public domain for all your client facing routes(default is WEBAPP_URL)
|
# Set this URL to add a custom domain to your survey links(default is WEBAPP_URL)
|
||||||
# PUBLIC_URL=https://survey.example.com
|
# SURVEY_URL=https://survey.example.com
|
||||||
|
|
||||||
#####################
|
#####################
|
||||||
# Disable Features #
|
# Disable Features #
|
||||||
@@ -96,6 +99,8 @@ PASSWORD_RESET_DISABLED=1
|
|||||||
# Organization Invite. Disable the ability for invited users to create an account.
|
# Organization Invite. Disable the ability for invited users to create an account.
|
||||||
# INVITE_DISABLED=1
|
# INVITE_DISABLED=1
|
||||||
|
|
||||||
|
# Docker cron jobs. Disable the supercronic cron jobs in the Docker image (useful for cluster setups).
|
||||||
|
# DOCKER_CRON_ENABLED=1
|
||||||
|
|
||||||
##########
|
##########
|
||||||
# Other #
|
# Other #
|
||||||
@@ -184,11 +189,15 @@ ENTERPRISE_LICENSE_KEY=
|
|||||||
UNSPLASH_ACCESS_KEY=
|
UNSPLASH_ACCESS_KEY=
|
||||||
|
|
||||||
# The below is used for Next Caching (uses In-Memory from Next Cache if not provided)
|
# The below is used for Next Caching (uses In-Memory from Next Cache if not provided)
|
||||||
|
# You can also add more configuration to Redis using the redis.conf file in the root directory
|
||||||
REDIS_URL=redis://localhost:6379
|
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=
|
||||||
|
|
||||||
@@ -201,8 +210,6 @@ REDIS_URL=redis://localhost:6379
|
|||||||
# The SENTRY_AUTH_TOKEN variable is picked up by the Sentry Build Plugin.
|
# The SENTRY_AUTH_TOKEN variable is picked up by the Sentry Build Plugin.
|
||||||
# It's used automatically by Sentry during the build for authentication when uploading source maps.
|
# It's used automatically by Sentry during the build for authentication when uploading source maps.
|
||||||
# SENTRY_AUTH_TOKEN=
|
# SENTRY_AUTH_TOKEN=
|
||||||
# The SENTRY_ENVIRONMENT is the environment which the error will belong to in the Sentry dashboard
|
|
||||||
# SENTRY_ENVIRONMENT=
|
|
||||||
|
|
||||||
# Configure the minimum role for user management from UI(owner, manager, disabled)
|
# Configure the minimum role for user management from UI(owner, manager, disabled)
|
||||||
# USER_MANAGEMENT_MINIMUM_ROLE="manager"
|
# USER_MANAGEMENT_MINIMUM_ROLE="manager"
|
||||||
@@ -210,7 +217,7 @@ REDIS_URL=redis://localhost:6379
|
|||||||
# Configure the maximum age for the session in seconds. Default is 86400 (24 hours)
|
# Configure the maximum age for the session in seconds. Default is 86400 (24 hours)
|
||||||
# SESSION_MAX_AGE=86400
|
# SESSION_MAX_AGE=86400
|
||||||
|
|
||||||
# Audit logs options. Default 0.
|
# Audit logs options. Requires REDIS_URL env varibale. Default 0.
|
||||||
# AUDIT_LOG_ENABLED=0
|
# AUDIT_LOG_ENABLED=0
|
||||||
# If the ip should be added in the log or not. Default 0
|
# If the ip should be added in the log or not. Default 0
|
||||||
# AUDIT_LOG_GET_USER_IP=0
|
# AUDIT_LOG_GET_USER_IP=0
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
root: true,
|
|
||||||
ignorePatterns: ["node_modules/", "dist/", "coverage/"],
|
|
||||||
overrides: [
|
|
||||||
{
|
|
||||||
files: ["packages/cache/**/*.{ts,js}"],
|
|
||||||
extends: ["@formbricks/eslint-config/library.js"],
|
|
||||||
parserOptions: {
|
|
||||||
project: "./packages/cache/tsconfig.json",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
1
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
1
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@@ -1,7 +1,6 @@
|
|||||||
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: true
|
blank_issues_enabled: false
|
||||||
contact_links:
|
contact_links:
|
||||||
- name: Questions
|
- name: Questions
|
||||||
url: https://github.com/formbricks/formbricks/discussions
|
url: https://github.com/formbricks/formbricks/discussions
|
||||||
|
|||||||
1
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
1
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@@ -1,7 +1,6 @@
|
|||||||
name: Feature request
|
name: Feature request
|
||||||
description: "Suggest an idea for this project \U0001F680"
|
description: "Suggest an idea for this project \U0001F680"
|
||||||
type: feature
|
type: feature
|
||||||
projects: "formbricks/21"
|
|
||||||
body:
|
body:
|
||||||
- type: textarea
|
- type: textarea
|
||||||
id: problem-description
|
id: problem-description
|
||||||
|
|||||||
11
.github/ISSUE_TEMPLATE/task.yml
vendored
Normal file
11
.github/ISSUE_TEMPLATE/task.yml
vendored
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
name: Task (internal)
|
||||||
|
description: "Template for creating a task. Used by the Formbricks Team only \U0001f4e5"
|
||||||
|
type: task
|
||||||
|
body:
|
||||||
|
- type: textarea
|
||||||
|
id: task-summary
|
||||||
|
attributes:
|
||||||
|
label: Task description
|
||||||
|
description: A clear detailed-rich description of the task.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
312
.github/actions/build-and-push-docker/action.yml
vendored
312
.github/actions/build-and-push-docker/action.yml
vendored
@@ -1,312 +0,0 @@
|
|||||||
name: Build and Push Docker Image
|
|
||||||
description: |
|
|
||||||
Unified Docker build and push action for both ECR and GHCR registries.
|
|
||||||
|
|
||||||
Supports:
|
|
||||||
- ECR builds for Formbricks Cloud deployment
|
|
||||||
- GHCR builds for community self-hosting
|
|
||||||
- Automatic version resolution and tagging
|
|
||||||
- Conditional signing and deployment tags
|
|
||||||
|
|
||||||
inputs:
|
|
||||||
registry_type:
|
|
||||||
description: "Registry type: 'ecr' or 'ghcr'"
|
|
||||||
required: true
|
|
||||||
|
|
||||||
# Version input
|
|
||||||
version:
|
|
||||||
description: "Explicit version (SemVer only, e.g., 1.2.3). If provided, this version is used directly. If empty, version is auto-generated from branch name."
|
|
||||||
required: false
|
|
||||||
experimental_mode:
|
|
||||||
description: "Enable experimental timestamped versions"
|
|
||||||
required: false
|
|
||||||
default: "false"
|
|
||||||
|
|
||||||
# ECR specific inputs
|
|
||||||
ecr_registry:
|
|
||||||
description: "ECR registry URL (required for ECR builds)"
|
|
||||||
required: false
|
|
||||||
ecr_repository:
|
|
||||||
description: "ECR repository name (required for ECR builds)"
|
|
||||||
required: false
|
|
||||||
ecr_region:
|
|
||||||
description: "ECR AWS region (required for ECR builds)"
|
|
||||||
required: false
|
|
||||||
aws_role_arn:
|
|
||||||
description: "AWS role ARN for ECR authentication (required for ECR builds)"
|
|
||||||
required: false
|
|
||||||
|
|
||||||
# GHCR specific inputs
|
|
||||||
ghcr_image_name:
|
|
||||||
description: "GHCR image name (required for GHCR builds)"
|
|
||||||
required: false
|
|
||||||
|
|
||||||
# Deployment options
|
|
||||||
deploy_production:
|
|
||||||
description: "Tag image for production deployment"
|
|
||||||
required: false
|
|
||||||
default: "false"
|
|
||||||
deploy_staging:
|
|
||||||
description: "Tag image for staging deployment"
|
|
||||||
required: false
|
|
||||||
default: "false"
|
|
||||||
is_prerelease:
|
|
||||||
description: "Whether this is a prerelease (auto-tags for staging/production)"
|
|
||||||
required: false
|
|
||||||
default: "false"
|
|
||||||
|
|
||||||
# Build options
|
|
||||||
dockerfile:
|
|
||||||
description: "Path to Dockerfile"
|
|
||||||
required: false
|
|
||||||
default: "apps/web/Dockerfile"
|
|
||||||
context:
|
|
||||||
description: "Build context"
|
|
||||||
required: false
|
|
||||||
default: "."
|
|
||||||
|
|
||||||
outputs:
|
|
||||||
image_tag:
|
|
||||||
description: "Resolved image tag used for the build"
|
|
||||||
value: ${{ steps.version.outputs.version }}
|
|
||||||
registry_tags:
|
|
||||||
description: "Complete registry tags that were pushed"
|
|
||||||
value: ${{ steps.build.outputs.tags }}
|
|
||||||
image_digest:
|
|
||||||
description: "Image digest from the build"
|
|
||||||
value: ${{ steps.build.outputs.digest }}
|
|
||||||
|
|
||||||
runs:
|
|
||||||
using: "composite"
|
|
||||||
steps:
|
|
||||||
- name: Validate inputs
|
|
||||||
shell: bash
|
|
||||||
env:
|
|
||||||
REGISTRY_TYPE: ${{ inputs.registry_type }}
|
|
||||||
ECR_REGISTRY: ${{ inputs.ecr_registry }}
|
|
||||||
ECR_REPOSITORY: ${{ inputs.ecr_repository }}
|
|
||||||
ECR_REGION: ${{ inputs.ecr_region }}
|
|
||||||
AWS_ROLE_ARN: ${{ inputs.aws_role_arn }}
|
|
||||||
GHCR_IMAGE_NAME: ${{ inputs.ghcr_image_name }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
if [[ "$REGISTRY_TYPE" != "ecr" && "$REGISTRY_TYPE" != "ghcr" ]]; then
|
|
||||||
echo "ERROR: registry_type must be 'ecr' or 'ghcr', got: $REGISTRY_TYPE"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ "$REGISTRY_TYPE" == "ecr" ]]; then
|
|
||||||
if [[ -z "$ECR_REGISTRY" || -z "$ECR_REPOSITORY" || -z "$ECR_REGION" || -z "$AWS_ROLE_ARN" ]]; then
|
|
||||||
echo "ERROR: ECR builds require ecr_registry, ecr_repository, ecr_region, and aws_role_arn"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ "$REGISTRY_TYPE" == "ghcr" ]]; then
|
|
||||||
if [[ -z "$GHCR_IMAGE_NAME" ]]; then
|
|
||||||
echo "ERROR: GHCR builds require ghcr_image_name"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "SUCCESS: Input validation passed for $REGISTRY_TYPE build"
|
|
||||||
|
|
||||||
- name: Resolve Docker version
|
|
||||||
id: version
|
|
||||||
uses: ./.github/actions/resolve-docker-version
|
|
||||||
with:
|
|
||||||
version: ${{ inputs.version }}
|
|
||||||
current_branch: ${{ github.ref_name }}
|
|
||||||
experimental_mode: ${{ inputs.experimental_mode }}
|
|
||||||
|
|
||||||
- name: Update package.json version
|
|
||||||
uses: ./.github/actions/update-package-version
|
|
||||||
with:
|
|
||||||
version: ${{ steps.version.outputs.version }}
|
|
||||||
|
|
||||||
- name: Configure AWS credentials (ECR only)
|
|
||||||
if: ${{ inputs.registry_type == 'ecr' }}
|
|
||||||
uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4.2.0
|
|
||||||
with:
|
|
||||||
role-to-assume: ${{ inputs.aws_role_arn }}
|
|
||||||
aws-region: ${{ inputs.ecr_region }}
|
|
||||||
|
|
||||||
- name: Log in to Amazon ECR (ECR only)
|
|
||||||
if: ${{ inputs.registry_type == 'ecr' }}
|
|
||||||
uses: aws-actions/amazon-ecr-login@062b18b96a7aff071d4dc91bc00c4c1a7945b076 # v2.0.1
|
|
||||||
|
|
||||||
- name: Set up Docker build tools
|
|
||||||
uses: ./.github/actions/docker-build-setup
|
|
||||||
with:
|
|
||||||
registry: ${{ inputs.registry_type == 'ghcr' && 'ghcr.io' || '' }}
|
|
||||||
setup_cosign: ${{ inputs.registry_type == 'ghcr' && 'true' || 'false' }}
|
|
||||||
skip_login_on_pr: ${{ inputs.registry_type == 'ghcr' && 'true' || 'false' }}
|
|
||||||
|
|
||||||
- name: Build ECR tag list
|
|
||||||
if: ${{ inputs.registry_type == 'ecr' }}
|
|
||||||
id: ecr-tags
|
|
||||||
shell: bash
|
|
||||||
env:
|
|
||||||
IMAGE_TAG: ${{ steps.version.outputs.version }}
|
|
||||||
ECR_REGISTRY: ${{ inputs.ecr_registry }}
|
|
||||||
ECR_REPOSITORY: ${{ inputs.ecr_repository }}
|
|
||||||
DEPLOY_PRODUCTION: ${{ inputs.deploy_production }}
|
|
||||||
DEPLOY_STAGING: ${{ inputs.deploy_staging }}
|
|
||||||
IS_PRERELEASE: ${{ inputs.is_prerelease }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
# Start with the base image tag
|
|
||||||
TAGS="${ECR_REGISTRY}/${ECR_REPOSITORY}:${IMAGE_TAG}"
|
|
||||||
|
|
||||||
# Handle automatic tagging based on release type
|
|
||||||
if [[ "${IS_PRERELEASE}" == "true" ]]; then
|
|
||||||
TAGS="${TAGS}\n${ECR_REGISTRY}/${ECR_REPOSITORY}:staging"
|
|
||||||
echo "Adding staging tag for prerelease"
|
|
||||||
elif [[ "${IS_PRERELEASE}" == "false" ]]; then
|
|
||||||
TAGS="${TAGS}\n${ECR_REGISTRY}/${ECR_REPOSITORY}:production"
|
|
||||||
echo "Adding production tag for stable release"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Handle manual deployment overrides
|
|
||||||
if [[ "${DEPLOY_PRODUCTION}" == "true" ]]; then
|
|
||||||
TAGS="${TAGS}\n${ECR_REGISTRY}/${ECR_REPOSITORY}:production"
|
|
||||||
echo "Adding production tag (manual override)"
|
|
||||||
fi
|
|
||||||
if [[ "${DEPLOY_STAGING}" == "true" ]]; then
|
|
||||||
TAGS="${TAGS}\n${ECR_REGISTRY}/${ECR_REPOSITORY}:staging"
|
|
||||||
echo "Adding staging tag (manual override)"
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "ECR tags generated:"
|
|
||||||
echo -e "${TAGS}"
|
|
||||||
|
|
||||||
{
|
|
||||||
echo "tags<<EOF"
|
|
||||||
echo -e "${TAGS}"
|
|
||||||
echo "EOF"
|
|
||||||
} >> "${GITHUB_OUTPUT}"
|
|
||||||
|
|
||||||
- name: Generate additional GHCR tags for releases
|
|
||||||
if: ${{ inputs.registry_type == 'ghcr' && inputs.experimental_mode == 'false' && (github.event_name == 'workflow_call' || github.event_name == 'release' || github.event_name == 'workflow_dispatch') }}
|
|
||||||
id: ghcr-extra-tags
|
|
||||||
shell: bash
|
|
||||||
env:
|
|
||||||
VERSION: ${{ steps.version.outputs.version }}
|
|
||||||
IMAGE_NAME: ${{ inputs.ghcr_image_name }}
|
|
||||||
IS_PRERELEASE: ${{ inputs.is_prerelease }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
# Start with base version tag
|
|
||||||
TAGS="ghcr.io/${IMAGE_NAME}:${VERSION}"
|
|
||||||
|
|
||||||
# For proper SemVer releases, add major.minor and major tags
|
|
||||||
if [[ "${VERSION}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
|
||||||
# Extract major and minor versions
|
|
||||||
MAJOR=$(echo "${VERSION}" | cut -d. -f1)
|
|
||||||
MINOR=$(echo "${VERSION}" | cut -d. -f2)
|
|
||||||
|
|
||||||
TAGS="${TAGS}\nghcr.io/${IMAGE_NAME}:${MAJOR}.${MINOR}"
|
|
||||||
TAGS="${TAGS}\nghcr.io/${IMAGE_NAME}:${MAJOR}"
|
|
||||||
|
|
||||||
echo "Added SemVer tags: ${MAJOR}.${MINOR}, ${MAJOR}"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Add latest tag for stable releases
|
|
||||||
if [[ "${IS_PRERELEASE}" == "false" ]]; then
|
|
||||||
TAGS="${TAGS}\nghcr.io/${IMAGE_NAME}:latest"
|
|
||||||
echo "Added latest tag for stable release"
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "Generated GHCR tags:"
|
|
||||||
echo -e "${TAGS}"
|
|
||||||
|
|
||||||
# Debug: Show what will be passed to Docker build
|
|
||||||
echo "DEBUG: Tags for Docker build step:"
|
|
||||||
echo -e "${TAGS}"
|
|
||||||
|
|
||||||
{
|
|
||||||
echo "tags<<EOF"
|
|
||||||
echo -e "${TAGS}"
|
|
||||||
echo "EOF"
|
|
||||||
} >> "${GITHUB_OUTPUT}"
|
|
||||||
|
|
||||||
- name: Build GHCR metadata (experimental)
|
|
||||||
if: ${{ inputs.registry_type == 'ghcr' && inputs.experimental_mode == 'true' }}
|
|
||||||
id: ghcr-meta-experimental
|
|
||||||
uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # v5.7.0
|
|
||||||
with:
|
|
||||||
images: ghcr.io/${{ inputs.ghcr_image_name }}
|
|
||||||
tags: |
|
|
||||||
type=ref,event=branch
|
|
||||||
type=raw,value=${{ steps.version.outputs.version }}
|
|
||||||
|
|
||||||
- name: Debug Docker build tags
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
echo "=== DEBUG: Docker Build Configuration ==="
|
|
||||||
echo "Registry Type: ${{ inputs.registry_type }}"
|
|
||||||
echo "Experimental Mode: ${{ inputs.experimental_mode }}"
|
|
||||||
echo "Event Name: ${{ github.event_name }}"
|
|
||||||
echo "Is Prerelease: ${{ inputs.is_prerelease }}"
|
|
||||||
echo "Version: ${{ steps.version.outputs.version }}"
|
|
||||||
|
|
||||||
if [[ "${{ inputs.registry_type }}" == "ecr" ]]; then
|
|
||||||
echo "ECR Tags: ${{ steps.ecr-tags.outputs.tags }}"
|
|
||||||
elif [[ "${{ inputs.experimental_mode }}" == "true" ]]; then
|
|
||||||
echo "GHCR Experimental Tags: ${{ steps.ghcr-meta-experimental.outputs.tags }}"
|
|
||||||
else
|
|
||||||
echo "GHCR Extra Tags: ${{ steps.ghcr-extra-tags.outputs.tags }}"
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Build and push Docker image
|
|
||||||
id: build
|
|
||||||
uses: depot/build-push-action@636daae76684e38c301daa0c5eca1c095b24e780 # v1.14.0
|
|
||||||
with:
|
|
||||||
project: tw0fqmsx3c
|
|
||||||
token: ${{ env.DEPOT_PROJECT_TOKEN }}
|
|
||||||
context: ${{ inputs.context }}
|
|
||||||
file: ${{ inputs.dockerfile }}
|
|
||||||
platforms: linux/amd64,linux/arm64
|
|
||||||
push: ${{ github.event_name != 'pull_request' }}
|
|
||||||
tags: ${{ inputs.registry_type == 'ecr' && steps.ecr-tags.outputs.tags || (inputs.registry_type == 'ghcr' && inputs.experimental_mode == 'true' && steps.ghcr-meta-experimental.outputs.tags) || (inputs.registry_type == 'ghcr' && inputs.experimental_mode == 'false' && steps.ghcr-extra-tags.outputs.tags) || (inputs.registry_type == 'ghcr' && format('ghcr.io/{0}:{1}', inputs.ghcr_image_name, steps.version.outputs.version)) || (inputs.registry_type == 'ecr' && format('{0}/{1}:{2}', inputs.ecr_registry, inputs.ecr_repository, steps.version.outputs.version)) }}
|
|
||||||
labels: ${{ inputs.registry_type == 'ghcr' && inputs.experimental_mode == 'true' && steps.ghcr-meta-experimental.outputs.labels || '' }}
|
|
||||||
secrets: |
|
|
||||||
database_url=${{ env.DUMMY_DATABASE_URL }}
|
|
||||||
encryption_key=${{ env.DUMMY_ENCRYPTION_KEY }}
|
|
||||||
redis_url=${{ env.DUMMY_REDIS_URL }}
|
|
||||||
sentry_auth_token=${{ env.SENTRY_AUTH_TOKEN }}
|
|
||||||
env:
|
|
||||||
DEPOT_PROJECT_TOKEN: ${{ env.DEPOT_PROJECT_TOKEN }}
|
|
||||||
DUMMY_DATABASE_URL: ${{ env.DUMMY_DATABASE_URL }}
|
|
||||||
DUMMY_ENCRYPTION_KEY: ${{ env.DUMMY_ENCRYPTION_KEY }}
|
|
||||||
DUMMY_REDIS_URL: ${{ env.DUMMY_REDIS_URL }}
|
|
||||||
SENTRY_AUTH_TOKEN: ${{ env.SENTRY_AUTH_TOKEN }}
|
|
||||||
|
|
||||||
- name: Sign GHCR image (GHCR only)
|
|
||||||
if: ${{ inputs.registry_type == 'ghcr' && (github.event_name == 'workflow_call' || github.event_name == 'release' || github.event_name == 'workflow_dispatch') }}
|
|
||||||
shell: bash
|
|
||||||
env:
|
|
||||||
TAGS: ${{ inputs.experimental_mode == 'true' && steps.ghcr-meta-experimental.outputs.tags || steps.ghcr-extra-tags.outputs.tags }}
|
|
||||||
DIGEST: ${{ steps.build.outputs.digest }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
echo "${TAGS}" | xargs -I {} cosign sign --yes "{}@${DIGEST}"
|
|
||||||
|
|
||||||
- name: Output build summary
|
|
||||||
shell: bash
|
|
||||||
env:
|
|
||||||
REGISTRY_TYPE: ${{ inputs.registry_type }}
|
|
||||||
IMAGE_TAG: ${{ steps.version.outputs.version }}
|
|
||||||
VERSION_SOURCE: ${{ steps.version.outputs.source }}
|
|
||||||
run: |
|
|
||||||
echo "SUCCESS: Built and pushed Docker image to $REGISTRY_TYPE"
|
|
||||||
echo "Image Tag: $IMAGE_TAG (source: $VERSION_SOURCE)"
|
|
||||||
if [[ "$REGISTRY_TYPE" == "ecr" ]]; then
|
|
||||||
echo "ECR Registry: ${{ inputs.ecr_registry }}"
|
|
||||||
echo "ECR Repository: ${{ inputs.ecr_repository }}"
|
|
||||||
else
|
|
||||||
echo "GHCR Image: ghcr.io/${{ inputs.ghcr_image_name }}"
|
|
||||||
fi
|
|
||||||
4
.github/actions/cache-build-web/action.yml
vendored
4
.github/actions/cache-build-web/action.yml
vendored
@@ -62,12 +62,10 @@ 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=$E2E_TESTING_MODE" >> .env
|
echo "E2E_TESTING=${{ inputs.e2e_testing_mode }}" >> .env
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|
||||||
- run: |
|
- run: |
|
||||||
|
|||||||
106
.github/actions/docker-build-setup/action.yml
vendored
106
.github/actions/docker-build-setup/action.yml
vendored
@@ -1,106 +0,0 @@
|
|||||||
name: Docker Build Setup
|
|
||||||
description: |
|
|
||||||
Sets up common Docker build tools and authentication with security validation.
|
|
||||||
|
|
||||||
Security Features:
|
|
||||||
- Registry URL validation
|
|
||||||
- Input sanitization
|
|
||||||
- Conditional setup based on event type
|
|
||||||
- Post-setup verification
|
|
||||||
|
|
||||||
Supports Depot CLI, Cosign signing, and Docker registry authentication.
|
|
||||||
|
|
||||||
inputs:
|
|
||||||
registry:
|
|
||||||
description: "Docker registry hostname to login to (e.g., ghcr.io, registry.example.com:5000). No paths allowed."
|
|
||||||
required: false
|
|
||||||
default: "ghcr.io"
|
|
||||||
setup_cosign:
|
|
||||||
description: "Whether to install cosign for image signing"
|
|
||||||
required: false
|
|
||||||
default: "true"
|
|
||||||
skip_login_on_pr:
|
|
||||||
description: "Whether to skip registry login on pull requests"
|
|
||||||
required: false
|
|
||||||
default: "true"
|
|
||||||
|
|
||||||
runs:
|
|
||||||
using: "composite"
|
|
||||||
steps:
|
|
||||||
- name: Validate inputs
|
|
||||||
shell: bash
|
|
||||||
env:
|
|
||||||
REGISTRY: ${{ inputs.registry }}
|
|
||||||
SETUP_COSIGN: ${{ inputs.setup_cosign }}
|
|
||||||
SKIP_LOGIN_ON_PR: ${{ inputs.skip_login_on_pr }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
# Security: Validate registry input - must be hostname[:port] only, no paths
|
|
||||||
# Allow empty registry for cases where login is handled externally (e.g., ECR)
|
|
||||||
if [[ -n "$REGISTRY" ]]; then
|
|
||||||
if [[ "$REGISTRY" =~ / ]]; then
|
|
||||||
echo "ERROR: Invalid registry format: $REGISTRY"
|
|
||||||
echo "Registry must be host[:port] with no path (e.g., 'ghcr.io' or 'registry.example.com:5000')"
|
|
||||||
echo "Path components like 'ghcr.io/org' are not allowed as they break docker login"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Validate hostname with optional port format
|
|
||||||
if [[ ! "$REGISTRY" =~ ^[a-zA-Z0-9.-]+(\:[0-9]+)?$ ]]; then
|
|
||||||
echo "ERROR: Invalid registry hostname format: $REGISTRY"
|
|
||||||
echo "Registry must be a valid hostname optionally with port (e.g., 'ghcr.io' or 'registry.example.com:5000')"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Validate boolean inputs
|
|
||||||
if [[ "$SETUP_COSIGN" != "true" && "$SETUP_COSIGN" != "false" ]]; then
|
|
||||||
echo "ERROR: setup_cosign must be 'true' or 'false', got: $SETUP_COSIGN"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ "$SKIP_LOGIN_ON_PR" != "true" && "$SKIP_LOGIN_ON_PR" != "false" ]]; then
|
|
||||||
echo "ERROR: skip_login_on_pr must be 'true' or 'false', got: $SKIP_LOGIN_ON_PR"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "SUCCESS: Input validation passed"
|
|
||||||
|
|
||||||
- name: Set up Depot CLI
|
|
||||||
uses: depot/setup-action@b0b1ea4f69e92ebf5dea3f8713a1b0c37b2126a5 # v1.6.0
|
|
||||||
|
|
||||||
- name: Install cosign
|
|
||||||
# Install cosign when requested AND when we might actually sign images
|
|
||||||
# (i.e., non-PR contexts or when we login on PRs)
|
|
||||||
if: ${{ inputs.setup_cosign == 'true' && (inputs.skip_login_on_pr == 'false' || github.event_name != 'pull_request') }}
|
|
||||||
uses: sigstore/cosign-installer@3454372f43399081ed03b604cb2d021dabca52bb # v3.8.2
|
|
||||||
|
|
||||||
- name: Log into registry
|
|
||||||
if: ${{ inputs.registry != '' && (inputs.skip_login_on_pr == 'false' || github.event_name != 'pull_request') }}
|
|
||||||
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
|
|
||||||
with:
|
|
||||||
registry: ${{ inputs.registry }}
|
|
||||||
username: ${{ github.actor }}
|
|
||||||
password: ${{ github.token }}
|
|
||||||
|
|
||||||
- name: Verify setup completion
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
# Verify Depot CLI is available
|
|
||||||
if ! command -v depot >/dev/null 2>&1; then
|
|
||||||
echo "ERROR: Depot CLI not found in PATH"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Verify cosign if it should be installed (same conditions as install step)
|
|
||||||
if [[ "${{ inputs.setup_cosign }}" == "true" ]] && [[ "${{ inputs.skip_login_on_pr }}" == "false" || "${{ github.event_name }}" != "pull_request" ]]; then
|
|
||||||
if ! command -v cosign >/dev/null 2>&1; then
|
|
||||||
echo "ERROR: Cosign not found in PATH despite being requested"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "SUCCESS: Docker build setup completed successfully"
|
|
||||||
192
.github/actions/resolve-docker-version/action.yml
vendored
192
.github/actions/resolve-docker-version/action.yml
vendored
@@ -1,192 +0,0 @@
|
|||||||
name: Resolve Docker Version
|
|
||||||
description: |
|
|
||||||
Resolves and validates Docker-compatible SemVer versions for container builds with comprehensive security.
|
|
||||||
|
|
||||||
Security Features:
|
|
||||||
- Command injection protection
|
|
||||||
- Input sanitization and validation
|
|
||||||
- Docker tag character restrictions
|
|
||||||
- Length limits and boundary checks
|
|
||||||
- Safe branch name handling
|
|
||||||
|
|
||||||
Supports multiple modes: release, manual override, branch auto-detection, and experimental timestamped versions.
|
|
||||||
|
|
||||||
inputs:
|
|
||||||
version:
|
|
||||||
description: "Explicit version (SemVer only, e.g., 1.2.3-beta). If provided, this version is used directly. If empty, version is auto-generated from branch name."
|
|
||||||
required: false
|
|
||||||
current_branch:
|
|
||||||
description: "Current branch name for auto-detection"
|
|
||||||
required: true
|
|
||||||
experimental_mode:
|
|
||||||
description: "Enable experimental mode with timestamp-based versions"
|
|
||||||
required: false
|
|
||||||
default: "false"
|
|
||||||
|
|
||||||
outputs:
|
|
||||||
version:
|
|
||||||
description: "Resolved Docker-compatible SemVer version"
|
|
||||||
value: ${{ steps.resolve.outputs.version }}
|
|
||||||
source:
|
|
||||||
description: "Source of version (release|override|branch)"
|
|
||||||
value: ${{ steps.resolve.outputs.source }}
|
|
||||||
normalized:
|
|
||||||
description: "Whether the version was normalized (true/false)"
|
|
||||||
value: ${{ steps.resolve.outputs.normalized }}
|
|
||||||
|
|
||||||
runs:
|
|
||||||
using: "composite"
|
|
||||||
steps:
|
|
||||||
- name: Resolve and validate Docker version
|
|
||||||
id: resolve
|
|
||||||
shell: bash
|
|
||||||
env:
|
|
||||||
EXPLICIT_VERSION: ${{ inputs.version }}
|
|
||||||
CURRENT_BRANCH: ${{ inputs.current_branch }}
|
|
||||||
EXPERIMENTAL_MODE: ${{ inputs.experimental_mode }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
# Function to validate SemVer format (Docker-compatible, no '+' build metadata)
|
|
||||||
validate_semver() {
|
|
||||||
local version="$1"
|
|
||||||
local context="$2"
|
|
||||||
|
|
||||||
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.-]+)?$ ]]; then
|
|
||||||
echo "ERROR: Invalid $context format. Must be semver without build metadata (e.g., 1.2.3, 1.2.3-alpha)"
|
|
||||||
echo "Provided: $version"
|
|
||||||
echo "Note: Docker tags cannot contain '+' characters. Use prerelease identifiers instead."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
# Function to generate branch-based version
|
|
||||||
generate_branch_version() {
|
|
||||||
local branch="$1"
|
|
||||||
local use_timestamp="${2:-true}"
|
|
||||||
local timestamp
|
|
||||||
|
|
||||||
if [[ "$use_timestamp" == "true" ]]; then
|
|
||||||
timestamp=$(date +%s)
|
|
||||||
else
|
|
||||||
timestamp=""
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Sanitize branch name for Docker compatibility
|
|
||||||
local sanitized_branch=$(echo "$branch" | sed 's/[^a-zA-Z0-9.-]/-/g' | sed 's/--*/-/g' | sed 's/^-\|-$//g')
|
|
||||||
|
|
||||||
# Additional safety: truncate if too long (reserve space for prefix and timestamp)
|
|
||||||
if (( ${#sanitized_branch} > 80 )); then
|
|
||||||
sanitized_branch="${sanitized_branch:0:80}"
|
|
||||||
echo "INFO: Branch name truncated for Docker compatibility" >&2
|
|
||||||
fi
|
|
||||||
local version
|
|
||||||
|
|
||||||
# Generate version based on branch name (unified approach)
|
|
||||||
# All branches get alpha versions with sanitized branch name
|
|
||||||
if [[ -n "$timestamp" ]]; then
|
|
||||||
version="0.0.0-alpha-$sanitized_branch-$timestamp"
|
|
||||||
echo "INFO: Branch '$branch' detected - alpha version: $version" >&2
|
|
||||||
else
|
|
||||||
version="0.0.0-alpha-$sanitized_branch"
|
|
||||||
echo "INFO: Branch '$branch' detected - alpha version: $version" >&2
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "$version"
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
# Input validation and sanitization
|
|
||||||
if [[ -z "$CURRENT_BRANCH" ]]; then
|
|
||||||
echo "ERROR: current_branch input is required"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Security: Validate inputs to prevent command injection
|
|
||||||
# Use grep to check for dangerous characters (more reliable than bash regex)
|
|
||||||
validate_input() {
|
|
||||||
local input="$1"
|
|
||||||
local name="$2"
|
|
||||||
|
|
||||||
# Check for dangerous characters using grep
|
|
||||||
if echo "$input" | grep -q '[;|&`$(){}\\[:space:]]'; then
|
|
||||||
echo "ERROR: $name contains potentially dangerous characters: $input"
|
|
||||||
echo "Input should only contain letters, numbers, hyphens, underscores, dots, and forward slashes"
|
|
||||||
return 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
# Validate current branch
|
|
||||||
if ! validate_input "$CURRENT_BRANCH" "Branch name"; then
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Validate explicit version if provided
|
|
||||||
if [[ -n "$EXPLICIT_VERSION" ]] && ! validate_input "$EXPLICIT_VERSION" "Explicit version"; then
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Main resolution logic (ultra-simplified)
|
|
||||||
NORMALIZED="false"
|
|
||||||
|
|
||||||
if [[ -n "$EXPLICIT_VERSION" ]]; then
|
|
||||||
# Use provided explicit version (from either workflow_call or manual input)
|
|
||||||
validate_semver "$EXPLICIT_VERSION" "explicit version"
|
|
||||||
|
|
||||||
# Normalize to lowercase for Docker/ECR compatibility
|
|
||||||
RESOLVED_VERSION="${EXPLICIT_VERSION,,}"
|
|
||||||
if [[ "$EXPLICIT_VERSION" != "$RESOLVED_VERSION" ]]; then
|
|
||||||
NORMALIZED="true"
|
|
||||||
echo "INFO: Original version contained uppercase characters, normalized: $EXPLICIT_VERSION -> $RESOLVED_VERSION"
|
|
||||||
fi
|
|
||||||
|
|
||||||
SOURCE="explicit"
|
|
||||||
echo "INFO: Using explicit version: $RESOLVED_VERSION"
|
|
||||||
|
|
||||||
else
|
|
||||||
# Auto-generate version from branch name
|
|
||||||
if [[ "$EXPERIMENTAL_MODE" == "true" ]]; then
|
|
||||||
# Use timestamped version generation
|
|
||||||
echo "INFO: Experimental mode: generating timestamped version from branch: $CURRENT_BRANCH"
|
|
||||||
RESOLVED_VERSION=$(generate_branch_version "$CURRENT_BRANCH" "true")
|
|
||||||
SOURCE="experimental"
|
|
||||||
else
|
|
||||||
# Standard branch version (no timestamp)
|
|
||||||
echo "INFO: Auto-detecting version from branch: $CURRENT_BRANCH"
|
|
||||||
RESOLVED_VERSION=$(generate_branch_version "$CURRENT_BRANCH" "false")
|
|
||||||
SOURCE="branch"
|
|
||||||
fi
|
|
||||||
echo "Generated version: $RESOLVED_VERSION"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Final validation - ensure result is valid Docker tag
|
|
||||||
if [[ -z "$RESOLVED_VERSION" ]]; then
|
|
||||||
echo "ERROR: Failed to resolve version"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if (( ${#RESOLVED_VERSION} > 128 )); then
|
|
||||||
echo "ERROR: Version must be at most 128 characters (Docker limitation)"
|
|
||||||
echo "Generated version: $RESOLVED_VERSION (${#RESOLVED_VERSION} chars)"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ ! "$RESOLVED_VERSION" =~ ^[a-z0-9._-]+$ ]]; then
|
|
||||||
echo "ERROR: Version contains invalid characters for Docker tags"
|
|
||||||
echo "Version: $RESOLVED_VERSION"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ "$RESOLVED_VERSION" =~ ^[.-] || "$RESOLVED_VERSION" =~ [.-]$ ]]; then
|
|
||||||
echo "ERROR: Version must not start or end with '.' or '-'"
|
|
||||||
echo "Version: $RESOLVED_VERSION"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Output results
|
|
||||||
echo "SUCCESS: Resolved Docker version: $RESOLVED_VERSION (source: $SOURCE)"
|
|
||||||
echo "version=$RESOLVED_VERSION" >> $GITHUB_OUTPUT
|
|
||||||
echo "source=$SOURCE" >> $GITHUB_OUTPUT
|
|
||||||
echo "normalized=$NORMALIZED" >> $GITHUB_OUTPUT
|
|
||||||
160
.github/actions/update-package-version/action.yml
vendored
160
.github/actions/update-package-version/action.yml
vendored
@@ -1,160 +0,0 @@
|
|||||||
name: Update Package Version
|
|
||||||
description: |
|
|
||||||
Safely updates package.json version with comprehensive validation and atomic operations.
|
|
||||||
|
|
||||||
Security Features:
|
|
||||||
- Path traversal protection
|
|
||||||
- SemVer validation with length limits
|
|
||||||
- Atomic file operations with backup/recovery
|
|
||||||
- JSON validation before applying changes
|
|
||||||
|
|
||||||
This action is designed to be secure by default and prevent common attack vectors.
|
|
||||||
|
|
||||||
inputs:
|
|
||||||
version:
|
|
||||||
description: "Version to set in package.json (must be valid SemVer)"
|
|
||||||
required: true
|
|
||||||
package_path:
|
|
||||||
description: "Path to package.json file"
|
|
||||||
required: false
|
|
||||||
default: "./apps/web/package.json"
|
|
||||||
|
|
||||||
outputs:
|
|
||||||
updated_version:
|
|
||||||
description: "The version that was actually set in package.json"
|
|
||||||
value: ${{ steps.update.outputs.updated_version }}
|
|
||||||
|
|
||||||
runs:
|
|
||||||
using: "composite"
|
|
||||||
steps:
|
|
||||||
- name: Update and verify package.json version
|
|
||||||
id: update
|
|
||||||
shell: bash
|
|
||||||
env:
|
|
||||||
VERSION: ${{ inputs.version }}
|
|
||||||
PACKAGE_PATH: ${{ inputs.package_path }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
# Validate inputs
|
|
||||||
if [[ -z "$VERSION" ]]; then
|
|
||||||
echo "ERROR: version input is required"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Security: Validate package_path to prevent path traversal attacks
|
|
||||||
# Only allow paths within the workspace and must end with package.json
|
|
||||||
if [[ "$PACKAGE_PATH" =~ \.\./|^/|^~ ]]; then
|
|
||||||
echo "ERROR: Invalid package path - path traversal detected: $PACKAGE_PATH"
|
|
||||||
echo "Package path must be relative to workspace root and cannot contain '../', start with '/', or '~'"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ ! "$PACKAGE_PATH" =~ package\.json$ ]]; then
|
|
||||||
echo "ERROR: Package path must end with 'package.json': $PACKAGE_PATH"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Resolve to absolute path within workspace for additional security
|
|
||||||
WORKSPACE_ROOT="${GITHUB_WORKSPACE:-$(pwd)}"
|
|
||||||
|
|
||||||
# Use realpath to resolve both paths and handle symlinks properly
|
|
||||||
WORKSPACE_ROOT=$(realpath "$WORKSPACE_ROOT")
|
|
||||||
RESOLVED_PATH=$(realpath "${WORKSPACE_ROOT}/${PACKAGE_PATH}")
|
|
||||||
|
|
||||||
# Ensure WORKSPACE_ROOT has a trailing slash for proper prefix matching
|
|
||||||
WORKSPACE_ROOT="${WORKSPACE_ROOT}/"
|
|
||||||
|
|
||||||
# Use shell string matching to ensure RESOLVED_PATH is within workspace
|
|
||||||
# This is more secure than regex and handles edge cases properly
|
|
||||||
if [[ "$RESOLVED_PATH" != "$WORKSPACE_ROOT"* ]]; then
|
|
||||||
echo "ERROR: Resolved path is outside workspace: $RESOLVED_PATH"
|
|
||||||
echo "Workspace root: $WORKSPACE_ROOT"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ ! -f "$RESOLVED_PATH" ]]; then
|
|
||||||
echo "ERROR: package.json not found at: $RESOLVED_PATH"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Use resolved path for operations
|
|
||||||
PACKAGE_PATH="$RESOLVED_PATH"
|
|
||||||
|
|
||||||
# Validate SemVer format with additional security checks
|
|
||||||
if [[ ${#VERSION} -gt 128 ]]; then
|
|
||||||
echo "ERROR: Version string too long (${#VERSION} chars, max 128): $VERSION"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.-]+)?$ ]]; then
|
|
||||||
echo "ERROR: Invalid SemVer format: $VERSION"
|
|
||||||
echo "Expected format: MAJOR.MINOR.PATCH[-PRERELEASE]"
|
|
||||||
echo "Only alphanumeric characters, dots, and hyphens allowed in prerelease"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Additional validation: Check for reasonable version component sizes
|
|
||||||
# Extract base version (MAJOR.MINOR.PATCH) without prerelease/build metadata
|
|
||||||
if [[ "$VERSION" =~ ^([0-9]+\.[0-9]+\.[0-9]+) ]]; then
|
|
||||||
BASE_VERSION="${BASH_REMATCH[1]}"
|
|
||||||
else
|
|
||||||
echo "ERROR: Could not extract base version from: $VERSION"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Split version components safely
|
|
||||||
IFS='.' read -ra VERSION_PARTS <<< "$BASE_VERSION"
|
|
||||||
|
|
||||||
# Validate component sizes (should have exactly 3 parts due to regex above)
|
|
||||||
if (( ${VERSION_PARTS[0]} > 999 || ${VERSION_PARTS[1]} > 999 || ${VERSION_PARTS[2]} > 999 )); then
|
|
||||||
echo "ERROR: Version components too large (max 999 each): $VERSION"
|
|
||||||
echo "Components: ${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.${VERSION_PARTS[2]}"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "Updating package.json version to: $VERSION"
|
|
||||||
|
|
||||||
# Create backup for atomic operations
|
|
||||||
BACKUP_PATH="${PACKAGE_PATH}.backup.$$"
|
|
||||||
cp "$PACKAGE_PATH" "$BACKUP_PATH"
|
|
||||||
|
|
||||||
# Use jq to safely update the version field with error handling
|
|
||||||
if ! jq --arg version "$VERSION" '.version = $version' "$PACKAGE_PATH" > "${PACKAGE_PATH}.tmp"; then
|
|
||||||
echo "ERROR: jq failed to process package.json"
|
|
||||||
rm -f "${PACKAGE_PATH}.tmp" "$BACKUP_PATH"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Validate the generated JSON before applying changes
|
|
||||||
if ! jq empty "${PACKAGE_PATH}.tmp" 2>/dev/null; then
|
|
||||||
echo "ERROR: Generated invalid JSON"
|
|
||||||
rm -f "${PACKAGE_PATH}.tmp" "$BACKUP_PATH"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Atomic move operation
|
|
||||||
if ! mv "${PACKAGE_PATH}.tmp" "$PACKAGE_PATH"; then
|
|
||||||
echo "ERROR: Failed to update package.json"
|
|
||||||
# Restore backup
|
|
||||||
mv "$BACKUP_PATH" "$PACKAGE_PATH"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Verify the update was successful
|
|
||||||
UPDATED_VERSION=$(jq -r '.version' "$PACKAGE_PATH" 2>/dev/null)
|
|
||||||
|
|
||||||
if [[ "$UPDATED_VERSION" != "$VERSION" ]]; then
|
|
||||||
echo "ERROR: Version update failed!"
|
|
||||||
echo "Expected: $VERSION"
|
|
||||||
echo "Actual: $UPDATED_VERSION"
|
|
||||||
# Restore backup
|
|
||||||
mv "$BACKUP_PATH" "$PACKAGE_PATH"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Clean up backup on success
|
|
||||||
rm -f "$BACKUP_PATH"
|
|
||||||
|
|
||||||
echo "SUCCESS: Updated package.json version to: $UPDATED_VERSION"
|
|
||||||
echo "updated_version=$UPDATED_VERSION" >> $GITHUB_OUTPUT
|
|
||||||
82
.github/workflows/apply-issue-labels-to-pr.yml
vendored
Normal file
82
.github/workflows/apply-issue-labels-to-pr.yml
vendored
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
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),
|
||||||
|
});
|
||||||
|
}
|
||||||
88
.github/workflows/build-and-push-ecr.yml
vendored
88
.github/workflows/build-and-push-ecr.yml
vendored
@@ -1,88 +0,0 @@
|
|||||||
name: Build Cloud Deployment Images
|
|
||||||
|
|
||||||
# This workflow builds Formbricks Docker images for ECR deployment:
|
|
||||||
# - workflow_call: Used by releases with explicit SemVer versions
|
|
||||||
# - workflow_dispatch: Auto-detects version from current branch or uses override
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
inputs:
|
|
||||||
version_override:
|
|
||||||
description: "Override version (SemVer only, e.g., 1.2.3). Leave empty to auto-detect from branch."
|
|
||||||
required: false
|
|
||||||
type: string
|
|
||||||
deploy_production:
|
|
||||||
description: "Tag image for production deployment"
|
|
||||||
required: false
|
|
||||||
default: false
|
|
||||||
type: boolean
|
|
||||||
deploy_staging:
|
|
||||||
description: "Tag image for staging deployment"
|
|
||||||
required: false
|
|
||||||
default: false
|
|
||||||
type: boolean
|
|
||||||
workflow_call:
|
|
||||||
inputs:
|
|
||||||
image_tag:
|
|
||||||
description: "Image tag to push (required for workflow_call)"
|
|
||||||
required: true
|
|
||||||
type: string
|
|
||||||
IS_PRERELEASE:
|
|
||||||
description: "Whether this is a prerelease (auto-tags for staging/production)"
|
|
||||||
required: false
|
|
||||||
type: boolean
|
|
||||||
default: false
|
|
||||||
outputs:
|
|
||||||
IMAGE_TAG:
|
|
||||||
description: "Normalized image tag used for the build"
|
|
||||||
value: ${{ jobs.build-and-push.outputs.IMAGE_TAG }}
|
|
||||||
TAGS:
|
|
||||||
description: "Newline-separated list of ECR tags pushed"
|
|
||||||
value: ${{ jobs.build-and-push.outputs.TAGS }}
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
id-token: write
|
|
||||||
|
|
||||||
env:
|
|
||||||
ECR_REGION: ${{ vars.ECR_REGION }}
|
|
||||||
# ECR settings are sourced from repository/environment variables for portability across envs/forks
|
|
||||||
ECR_REGISTRY: ${{ vars.ECR_REGISTRY }}
|
|
||||||
ECR_REPOSITORY: ${{ vars.ECR_REPOSITORY }}
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build-and-push:
|
|
||||||
name: Build and Push
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
timeout-minutes: 45
|
|
||||||
outputs:
|
|
||||||
IMAGE_TAG: ${{ steps.build.outputs.image_tag }}
|
|
||||||
TAGS: ${{ steps.build.outputs.registry_tags }}
|
|
||||||
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
|
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
|
||||||
|
|
||||||
- name: Build and push cloud deployment image
|
|
||||||
id: build
|
|
||||||
uses: ./.github/actions/build-and-push-docker
|
|
||||||
with:
|
|
||||||
registry_type: "ecr"
|
|
||||||
ecr_registry: ${{ env.ECR_REGISTRY }}
|
|
||||||
ecr_repository: ${{ env.ECR_REPOSITORY }}
|
|
||||||
ecr_region: ${{ env.ECR_REGION }}
|
|
||||||
aws_role_arn: ${{ secrets.AWS_ECR_PUSH_ROLE_ARN }}
|
|
||||||
version: ${{ inputs.version_override || inputs.image_tag }}
|
|
||||||
deploy_production: ${{ inputs.deploy_production }}
|
|
||||||
deploy_staging: ${{ inputs.deploy_staging }}
|
|
||||||
is_prerelease: ${{ inputs.IS_PRERELEASE }}
|
|
||||||
env:
|
|
||||||
DEPOT_PROJECT_TOKEN: ${{ secrets.DEPOT_PROJECT_TOKEN }}
|
|
||||||
DUMMY_DATABASE_URL: ${{ secrets.DUMMY_DATABASE_URL }}
|
|
||||||
DUMMY_ENCRYPTION_KEY: ${{ secrets.DUMMY_ENCRYPTION_KEY }}
|
|
||||||
DUMMY_REDIS_URL: ${{ secrets.DUMMY_REDIS_URL }}
|
|
||||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
|
||||||
4
.github/workflows/chromatic.yml
vendored
4
.github/workflows/chromatic.yml
vendored
@@ -6,14 +6,12 @@ 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
Normal file
27
.github/workflows/dependency-review.yml
vendored
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
# 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
|
||||||
37
.github/workflows/deploy-formbricks-cloud.yml
vendored
37
.github/workflows/deploy-formbricks-cloud.yml
vendored
@@ -4,7 +4,7 @@ on:
|
|||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
VERSION:
|
VERSION:
|
||||||
description: "The version of the Docker image to release (clean SemVer, e.g., 1.2.3)"
|
description: "The version of the Docker image to release, full image tag if image tag is v0.0.0 enter v0.0.0."
|
||||||
required: true
|
required: true
|
||||||
type: string
|
type: string
|
||||||
REPOSITORY:
|
REPOSITORY:
|
||||||
@@ -17,8 +17,8 @@ on:
|
|||||||
required: true
|
required: true
|
||||||
type: choice
|
type: choice
|
||||||
options:
|
options:
|
||||||
- staging
|
- stage
|
||||||
- production
|
- prod
|
||||||
workflow_call:
|
workflow_call:
|
||||||
inputs:
|
inputs:
|
||||||
VERSION:
|
VERSION:
|
||||||
@@ -37,27 +37,21 @@ on:
|
|||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
id-token: write
|
id-token: write
|
||||||
contents: read
|
contents: write
|
||||||
|
|
||||||
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@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@v4.2.2
|
||||||
|
|
||||||
- name: Tailscale
|
- name: Tailscale
|
||||||
uses: tailscale/github-action@84a3f23bb4d843bcf4da6cf824ec1be473daf4de # v3.2.3
|
uses: tailscale/github-action@v3
|
||||||
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
|
||||||
@@ -71,9 +65,9 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
AWS_REGION: eu-central-1
|
AWS_REGION: eu-central-1
|
||||||
|
|
||||||
- uses: helmfile/helmfile-action@712000e3d4e28c72778ecc53857746082f555ef3 # v2.0.4
|
- uses: helmfile/helmfile-action@v2
|
||||||
name: Deploy Formbricks Cloud Production
|
name: Deploy Formbricks Cloud Prod
|
||||||
if: inputs.ENVIRONMENT == 'production'
|
if: inputs.ENVIRONMENT == 'prod'
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ inputs.VERSION }}
|
VERSION: ${{ inputs.VERSION }}
|
||||||
REPOSITORY: ${{ inputs.REPOSITORY }}
|
REPOSITORY: ${{ inputs.REPOSITORY }}
|
||||||
@@ -89,9 +83,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@712000e3d4e28c72778ecc53857746082f555ef3 # v2.0.4
|
- uses: helmfile/helmfile-action@v2
|
||||||
name: Deploy Formbricks Cloud Staging
|
name: Deploy Formbricks Cloud Stage
|
||||||
if: inputs.ENVIRONMENT == 'staging'
|
if: inputs.ENVIRONMENT == 'stage'
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ inputs.VERSION }}
|
VERSION: ${{ inputs.VERSION }}
|
||||||
REPOSITORY: ${{ inputs.REPOSITORY }}
|
REPOSITORY: ${{ inputs.REPOSITORY }}
|
||||||
@@ -107,20 +101,19 @@ jobs:
|
|||||||
helmfile-workdirectory: infra/formbricks-cloud-helm
|
helmfile-workdirectory: infra/formbricks-cloud-helm
|
||||||
|
|
||||||
- name: Purge Cloudflare Cache
|
- name: Purge Cloudflare Cache
|
||||||
if: ${{ inputs.ENVIRONMENT == 'production' || inputs.ENVIRONMENT == 'staging' }}
|
if: ${{ inputs.ENVIRONMENT == 'prod' || inputs.ENVIRONMENT == 'stage' }}
|
||||||
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 [[ "$ENVIRONMENT" == "production" ]]; then
|
if [[ "${{ inputs.ENVIRONMENT }}" == "prod" ]]; 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: $ENVIRONMENT, zone: $CF_ZONE_ID)"
|
echo "Purging Cloudflare cache for host: $PURGE_HOST (environment: ${{ inputs.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
|
||||||
|
|||||||
159
.github/workflows/docker-build-validation.yml
vendored
159
.github/workflows/docker-build-validation.yml
vendored
@@ -21,10 +21,10 @@ jobs:
|
|||||||
name: Validate Docker Build
|
name: Validate Docker Build
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
# Add PostgreSQL and Redis service containers
|
# Add PostgreSQL service container
|
||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
image: pgvector/pgvector@sha256:9ae02a756ba16a2d69dd78058e25915e36e189bb36ddf01ceae86390d7ed786a
|
image: pgvector/pgvector:pg17
|
||||||
env:
|
env:
|
||||||
POSTGRES_USER: test
|
POSTGRES_USER: test
|
||||||
POSTGRES_PASSWORD: test
|
POSTGRES_PASSWORD: test
|
||||||
@@ -38,98 +38,43 @@ jobs:
|
|||||||
--health-timeout 5s
|
--health-timeout 5s
|
||||||
--health-retries 5
|
--health-retries 5
|
||||||
|
|
||||||
redis:
|
|
||||||
image: valkey/valkey@sha256:12ba4f45a7c3e1d0f076acd616cb230834e75a77e8516dde382720af32832d6d
|
|
||||||
ports:
|
|
||||||
- 6379:6379
|
|
||||||
|
|
||||||
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@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@v4.2.2
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
- name: Build Docker Image
|
- name: Build Docker Image
|
||||||
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
uses: docker/build-push-action@v6
|
||||||
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:${{ env.GITHUB_SHA }}
|
tags: formbricks-test:${{ 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 }}
|
||||||
redis_url=redis://localhost:6379
|
|
||||||
|
|
||||||
- name: Verify and Initialize PostgreSQL
|
- name: Verify PostgreSQL Connection
|
||||||
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 with timeout and proper error handling
|
# Test connection using psql
|
||||||
echo "Testing PostgreSQL connection with 30 second timeout..."
|
PGPASSWORD=test psql -h localhost -U test -d formbricks -c "\dt" || echo "Failed to connect to PostgreSQL"
|
||||||
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: Verify Redis/Valkey Connection
|
|
||||||
run: |
|
|
||||||
echo "Verifying Redis/Valkey connection..."
|
|
||||||
# Install Redis client to test connection
|
|
||||||
sudo apt-get update && sudo apt-get install -y redis-tools
|
|
||||||
|
|
||||||
# Test connection using redis-cli with timeout and proper error handling
|
|
||||||
echo "Testing Redis connection with 30 second timeout..."
|
|
||||||
if timeout 30 bash -c 'until redis-cli -h localhost -p 6379 ping >/dev/null 2>&1; do
|
|
||||||
echo "Waiting for Redis to be ready..."
|
|
||||||
sleep 2
|
|
||||||
done'; then
|
|
||||||
echo "✅ Redis connection successful"
|
|
||||||
redis-cli -h localhost -p 6379 info server | head -5
|
|
||||||
else
|
|
||||||
echo "❌ Redis connection failed after 30 seconds"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Show network configuration for Redis
|
|
||||||
echo "Redis network configuration:"
|
|
||||||
netstat -tulpn | grep 6379 || echo "No process listening on port 6379"
|
|
||||||
|
|
||||||
- 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..."
|
||||||
|
|
||||||
@@ -141,13 +86,29 @@ 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="$DUMMY_ENCRYPTION_KEY" \
|
-e ENCRYPTION_KEY="${{ secrets.DUMMY_ENCRYPTION_KEY }}" \
|
||||||
-e REDIS_URL="redis://host.docker.internal:6379" \
|
-d formbricks-test:${{ github.sha }}
|
||||||
-d "formbricks-test:$GITHUB_SHA"
|
|
||||||
|
|
||||||
# Start health check polling immediately (every 5 seconds for up to 5 minutes)
|
# Give it more time to start up
|
||||||
echo "🏥 Polling /health endpoint every 5 seconds for up to 5 minutes..."
|
echo "Waiting 45 seconds for application to start..."
|
||||||
MAX_RETRIES=60 # 60 attempts × 5 seconds = 5 minutes
|
sleep 45
|
||||||
|
|
||||||
|
# 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
|
||||||
|
|
||||||
@@ -155,32 +116,38 @@ 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
|
|
||||||
if [ "$(docker inspect -f '{{.State.Running}}' formbricks-test 2>/dev/null)" != "true" ]; then
|
# Show container logs before each attempt to help debugging
|
||||||
echo "❌ Container stopped running after $((RETRY_COUNT * 5)) seconds!"
|
if [ $RETRY_COUNT -gt 1 ]; then
|
||||||
echo "📋 Container logs:"
|
echo "📋 Current container logs:"
|
||||||
docker logs formbricks-test
|
docker logs --tail 20 formbricks-test
|
||||||
exit 1
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Show progress and diagnostic info every 12 attempts (1 minute intervals)
|
# Get detailed curl output for debugging
|
||||||
if [ $((RETRY_COUNT % 12)) -eq 0 ] || [ $RETRY_COUNT -eq 1 ]; then
|
HTTP_OUTPUT=$(curl -v -s -m 30 http://localhost:3000/health 2>&1)
|
||||||
echo "Health check attempt $RETRY_COUNT of $MAX_RETRIES ($(($RETRY_COUNT * 5)) seconds elapsed)..."
|
CURL_EXIT_CODE=$?
|
||||||
echo "📋 Recent container logs:"
|
|
||||||
docker logs --tail 10 formbricks-test
|
echo "Curl exit code: $CURL_EXIT_CODE"
|
||||||
|
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
|
||||||
|
|
||||||
# Try health endpoint with shorter timeout for faster polling
|
echo "Waiting 15 seconds before next attempt..."
|
||||||
# Use -f flag to make curl fail on HTTP error status codes (4xx, 5xx)
|
sleep 15
|
||||||
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
|
||||||
@@ -193,7 +160,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 * 5)) seconds (5 minutes)"
|
echo "❌ Health check failed after $MAX_RETRIES attempts"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|||||||
70
.github/workflows/docker-security-scan.yml
vendored
70
.github/workflows/docker-security-scan.yml
vendored
@@ -1,70 +0,0 @@
|
|||||||
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
|
|
||||||
timeout-minutes: 30
|
|
||||||
steps:
|
|
||||||
- name: Harden the runner
|
|
||||||
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
|
||||||
with:
|
|
||||||
egress-policy: audit
|
|
||||||
|
|
||||||
- name: Checkout (for SARIF fingerprinting only)
|
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
|
||||||
with:
|
|
||||||
fetch-depth: 1
|
|
||||||
|
|
||||||
- name: Determine ref and commit for upload
|
|
||||||
id: gitref
|
|
||||||
shell: bash
|
|
||||||
env:
|
|
||||||
EVENT_NAME: ${{ github.event_name }}
|
|
||||||
HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
|
|
||||||
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
if [[ "${EVENT_NAME}" == "workflow_run" ]]; then
|
|
||||||
echo "ref=refs/heads/${HEAD_BRANCH}" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "sha=${HEAD_SHA}" >> "$GITHUB_OUTPUT"
|
|
||||||
else
|
|
||||||
echo "ref=${GITHUB_REF}" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "sha=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
|
|
||||||
fi
|
|
||||||
- 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() }}
|
|
||||||
with:
|
|
||||||
sarif_file: "trivy-results.sarif"
|
|
||||||
ref: ${{ steps.gitref.outputs.ref }}
|
|
||||||
sha: ${{ steps.gitref.outputs.sha }}
|
|
||||||
category: "trivy-container-scan"
|
|
||||||
103
.github/workflows/e2e.yml
vendored
103
.github/workflows/e2e.yml
vendored
@@ -33,7 +33,7 @@ jobs:
|
|||||||
timeout-minutes: 60
|
timeout-minutes: 60
|
||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
image: pgvector/pgvector@sha256:9ae02a756ba16a2d69dd78058e25915e36e189bb36ddf01ceae86390d7ed786a
|
image: pgvector/pgvector:pg17
|
||||||
env:
|
env:
|
||||||
POSTGRES_DB: postgres
|
POSTGRES_DB: postgres
|
||||||
POSTGRES_USER: postgres
|
POSTGRES_USER: postgres
|
||||||
@@ -41,23 +41,27 @@ jobs:
|
|||||||
ports:
|
ports:
|
||||||
- 5432:5432
|
- 5432:5432
|
||||||
options: >-
|
options: >-
|
||||||
--health-cmd="pg_isready -U postgres"
|
--health-cmd="pg_isready -U testuser"
|
||||||
--health-interval=10s
|
--health-interval=10s
|
||||||
--health-timeout=5s
|
--health-timeout=5s
|
||||||
--health-retries=5
|
--health-retries=5
|
||||||
valkey:
|
valkey:
|
||||||
image: valkey/valkey@sha256:12ba4f45a7c3e1d0f076acd616cb230834e75a77e8516dde382720af32832d6d
|
image: valkey/valkey:8.1.1
|
||||||
ports:
|
ports:
|
||||||
- 6379:6379
|
- 6379:6379
|
||||||
|
options: >-
|
||||||
|
--entrypoint "valkey-server"
|
||||||
|
--health-cmd="valkey-cli ping"
|
||||||
|
--health-interval=10s
|
||||||
|
--health-timeout=5s
|
||||||
|
--health-retries=5
|
||||||
steps:
|
steps:
|
||||||
- name: Harden the runner (Audit all outbound calls)
|
- name: Harden the runner (Audit all outbound calls)
|
||||||
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
||||||
with:
|
with:
|
||||||
egress-policy: audit
|
egress-policy: allow
|
||||||
allowed-endpoints: |
|
allowed-endpoints: |
|
||||||
ee.formbricks.com:443
|
ee.formbricks.com:443
|
||||||
registry-1.docker.io:443
|
|
||||||
docker.io:443
|
|
||||||
|
|
||||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
- uses: ./.github/actions/dangerous-git-checkout
|
- uses: ./.github/actions/dangerous-git-checkout
|
||||||
@@ -85,72 +89,10 @@ jobs:
|
|||||||
sed -i "s/CRON_SECRET=.*/CRON_SECRET=${RANDOM_KEY}/" .env
|
sed -i "s/CRON_SECRET=.*/CRON_SECRET=${RANDOM_KEY}/" .env
|
||||||
sed -i "s/NEXTAUTH_SECRET=.*/NEXTAUTH_SECRET=${RANDOM_KEY}/" .env
|
sed -i "s/NEXTAUTH_SECRET=.*/NEXTAUTH_SECRET=${RANDOM_KEY}/" .env
|
||||||
sed -i "s/ENTERPRISE_LICENSE_KEY=.*/ENTERPRISE_LICENSE_KEY=${{ secrets.ENTERPRISE_LICENSE_KEY }}/" .env
|
sed -i "s/ENTERPRISE_LICENSE_KEY=.*/ENTERPRISE_LICENSE_KEY=${{ secrets.ENTERPRISE_LICENSE_KEY }}/" .env
|
||||||
sed -i "s|REDIS_URL=.*|REDIS_URL=redis://localhost:6379|" .env
|
|
||||||
echo "" >> .env
|
echo "" >> .env
|
||||||
echo "E2E_TESTING=1" >> .env
|
echo "E2E_TESTING=1" >> .env
|
||||||
echo "S3_REGION=us-east-1" >> .env
|
|
||||||
echo "S3_BUCKET_NAME=formbricks-e2e" >> .env
|
|
||||||
echo "S3_ENDPOINT_URL=http://localhost:9000" >> .env
|
|
||||||
echo "S3_ACCESS_KEY=devminio" >> .env
|
|
||||||
echo "S3_SECRET_KEY=devminio123" >> .env
|
|
||||||
echo "S3_FORCE_PATH_STYLE=1" >> .env
|
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|
||||||
- name: Install MinIO client (mc)
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
MC_VERSION="RELEASE.2025-08-13T08-35-41Z"
|
|
||||||
MC_BASE="https://dl.min.io/client/mc/release/linux-amd64/archive"
|
|
||||||
MC_BIN="mc.${MC_VERSION}"
|
|
||||||
MC_SUM="${MC_BIN}.sha256sum"
|
|
||||||
|
|
||||||
curl -fsSL "${MC_BASE}/${MC_BIN}" -o "${MC_BIN}"
|
|
||||||
curl -fsSL "${MC_BASE}/${MC_SUM}" -o "${MC_SUM}"
|
|
||||||
|
|
||||||
sha256sum -c "${MC_SUM}"
|
|
||||||
|
|
||||||
chmod +x "${MC_BIN}"
|
|
||||||
sudo mv "${MC_BIN}" /usr/local/bin/mc
|
|
||||||
|
|
||||||
- name: Start MinIO Server
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
# Start MinIO server in background
|
|
||||||
docker run -d \
|
|
||||||
--name minio-server \
|
|
||||||
-p 9000:9000 \
|
|
||||||
-p 9001:9001 \
|
|
||||||
-e MINIO_ROOT_USER=devminio \
|
|
||||||
-e MINIO_ROOT_PASSWORD=devminio123 \
|
|
||||||
minio/minio:RELEASE.2025-09-07T16-13-09Z \
|
|
||||||
server /data --console-address :9001
|
|
||||||
|
|
||||||
echo "MinIO server started"
|
|
||||||
|
|
||||||
- name: Wait for MinIO and create S3 bucket
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
echo "Waiting for MinIO to be ready..."
|
|
||||||
ready=0
|
|
||||||
for i in {1..60}; do
|
|
||||||
if curl -fsS http://localhost:9000/minio/health/live >/dev/null; then
|
|
||||||
echo "MinIO is up after ${i} seconds"
|
|
||||||
ready=1
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
|
|
||||||
if [ "$ready" -ne 1 ]; then
|
|
||||||
echo "::error::MinIO did not become ready within 60 seconds"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
mc alias set local http://localhost:9000 devminio devminio123
|
|
||||||
mc mb --ignore-existing local/formbricks-e2e
|
|
||||||
|
|
||||||
- name: Build App
|
- name: Build App
|
||||||
run: |
|
run: |
|
||||||
pnpm build --filter=@formbricks/web...
|
pnpm build --filter=@formbricks/web...
|
||||||
@@ -160,18 +102,6 @@ jobs:
|
|||||||
# pnpm prisma migrate deploy
|
# pnpm prisma migrate deploy
|
||||||
pnpm db:migrate:dev
|
pnpm db:migrate:dev
|
||||||
|
|
||||||
- name: Run Rate Limiter Load Tests
|
|
||||||
run: |
|
|
||||||
echo "Running rate limiter load tests with Redis/Valkey..."
|
|
||||||
cd apps/web && pnpm vitest run modules/core/rate-limit/rate-limit-load.test.ts
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Run Cache Integration Tests
|
|
||||||
run: |
|
|
||||||
echo "Running cache integration tests with Redis/Valkey..."
|
|
||||||
cd packages/cache && pnpm vitest run src/cache-integration.test.ts
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Check for Enterprise License
|
- name: Check for Enterprise License
|
||||||
run: |
|
run: |
|
||||||
LICENSE_KEY=$(grep '^ENTERPRISE_LICENSE_KEY=' .env | cut -d'=' -f2-)
|
LICENSE_KEY=$(grep '^ENTERPRISE_LICENSE_KEY=' .env | cut -d'=' -f2-)
|
||||||
@@ -181,12 +111,6 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
echo "License key length: ${#LICENSE_KEY}"
|
echo "License key length: ${#LICENSE_KEY}"
|
||||||
|
|
||||||
- name: Disable rate limiting for E2E tests
|
|
||||||
run: |
|
|
||||||
echo "RATE_LIMITING_DISABLED=1" >> .env
|
|
||||||
echo "Rate limiting disabled for E2E tests"
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Run App
|
- name: Run App
|
||||||
run: |
|
run: |
|
||||||
echo "Starting app with enterprise license..."
|
echo "Starting app with enterprise license..."
|
||||||
@@ -228,14 +152,11 @@ jobs:
|
|||||||
if: env.AZURE_ENABLED == 'true'
|
if: env.AZURE_ENABLED == 'true'
|
||||||
env:
|
env:
|
||||||
PLAYWRIGHT_SERVICE_URL: ${{ secrets.PLAYWRIGHT_SERVICE_URL }}
|
PLAYWRIGHT_SERVICE_URL: ${{ secrets.PLAYWRIGHT_SERVICE_URL }}
|
||||||
CI: true
|
|
||||||
run: |
|
run: |
|
||||||
pnpm test-e2e:azure
|
pnpm test-e2e:azure
|
||||||
|
|
||||||
- name: Run E2E Tests (Local)
|
- name: Run E2E Tests (Local)
|
||||||
if: env.AZURE_ENABLED == 'false'
|
if: env.AZURE_ENABLED == 'false'
|
||||||
env:
|
|
||||||
CI: true
|
|
||||||
run: |
|
run: |
|
||||||
pnpm test:e2e
|
pnpm test:e2e
|
||||||
|
|
||||||
@@ -254,4 +175,4 @@ jobs:
|
|||||||
|
|
||||||
- name: Output App Logs
|
- name: Output App Logs
|
||||||
if: failure()
|
if: failure()
|
||||||
run: cat app.log
|
run: cat app.log
|
||||||
|
|||||||
81
.github/workflows/formbricks-release.yml
vendored
81
.github/workflows/formbricks-release.yml
vendored
@@ -1,81 +1,34 @@
|
|||||||
name: Build, release & deploy Formbricks images
|
name: Build, release & deploy Formbricks images
|
||||||
|
|
||||||
on:
|
on:
|
||||||
release:
|
workflow_dispatch:
|
||||||
types: [published]
|
push:
|
||||||
|
tags:
|
||||||
permissions:
|
- "v*"
|
||||||
contents: read
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
docker-build-community:
|
docker-build:
|
||||||
name: Build & release community docker image
|
name: Build & release stable docker image
|
||||||
permissions:
|
if: startsWith(github.ref, 'refs/tags/v')
|
||||||
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 }}
|
|
||||||
|
|
||||||
docker-build-cloud:
|
|
||||||
name: Build & push Formbricks Cloud to ECR
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
id-token: write
|
|
||||||
uses: ./.github/workflows/build-and-push-ecr.yml
|
|
||||||
secrets: inherit
|
|
||||||
with:
|
|
||||||
image_tag: ${{ needs.docker-build-community.outputs.VERSION }}
|
|
||||||
IS_PRERELEASE: ${{ github.event.release.prerelease }}
|
|
||||||
needs:
|
|
||||||
- docker-build-community
|
|
||||||
|
|
||||||
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:
|
||||||
- docker-build-community
|
- docker-build
|
||||||
with:
|
with:
|
||||||
VERSION: ${{ needs.docker-build-community.outputs.VERSION }}
|
VERSION: ${{ needs.docker-build.outputs.VERSION }}
|
||||||
|
|
||||||
verify-cloud-build:
|
deploy-formbricks-cloud:
|
||||||
name: Verify Cloud Build Outputs
|
name: Deploy Helm Chart to Formbricks Cloud
|
||||||
runs-on: ubuntu-latest
|
secrets: inherit
|
||||||
timeout-minutes: 5 # Simple verification should be quick
|
uses: ./.github/workflows/deploy-formbricks-cloud.yml
|
||||||
needs:
|
needs:
|
||||||
- docker-build-cloud
|
- docker-build
|
||||||
steps:
|
- helm-chart-release
|
||||||
- name: Harden the runner
|
|
||||||
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
|
||||||
with:
|
|
||||||
egress-policy: audit
|
|
||||||
|
|
||||||
- name: Display ECR build outputs
|
|
||||||
env:
|
|
||||||
IMAGE_TAG: ${{ needs.docker-build-cloud.outputs.IMAGE_TAG }}
|
|
||||||
TAGS: ${{ needs.docker-build-cloud.outputs.TAGS }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
echo "✅ ECR Build Completed Successfully"
|
|
||||||
echo "Image Tag: ${IMAGE_TAG}"
|
|
||||||
echo "ECR Tags:"
|
|
||||||
printf '%s\n' "${TAGS}"
|
|
||||||
|
|
||||||
move-stable-tag:
|
|
||||||
name: Move stable tag to release
|
|
||||||
permissions:
|
|
||||||
contents: write # Required for tag push operations in called workflow
|
|
||||||
uses: ./.github/workflows/move-stable-tag.yml
|
|
||||||
needs:
|
|
||||||
- docker-build-community # Ensure release is successful first
|
|
||||||
with:
|
with:
|
||||||
release_tag: ${{ github.event.release.tag_name }}
|
VERSION: v${{ needs.docker-build.outputs.VERSION }}
|
||||||
commit_sha: ${{ github.sha }}
|
ENVIRONMENT: "prod"
|
||||||
is_prerelease: ${{ github.event.release.prerelease }}
|
|
||||||
|
|||||||
96
.github/workflows/move-stable-tag.yml
vendored
96
.github/workflows/move-stable-tag.yml
vendored
@@ -1,96 +0,0 @@
|
|||||||
name: Move Stable Tag
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_call:
|
|
||||||
inputs:
|
|
||||||
release_tag:
|
|
||||||
description: "The release tag name (e.g., 1.2.3)"
|
|
||||||
required: true
|
|
||||||
type: string
|
|
||||||
commit_sha:
|
|
||||||
description: "The commit SHA to point the stable tag to"
|
|
||||||
required: true
|
|
||||||
type: string
|
|
||||||
is_prerelease:
|
|
||||||
description: "Whether this is a prerelease (stable tag won't be moved for prereleases)"
|
|
||||||
required: false
|
|
||||||
type: boolean
|
|
||||||
default: false
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
# Prevent concurrent stable tag operations to avoid race conditions
|
|
||||||
concurrency:
|
|
||||||
group: move-stable-tag-${{ github.repository }}
|
|
||||||
cancel-in-progress: true
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
move-stable-tag:
|
|
||||||
name: Move stable tag to release
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
timeout-minutes: 10 # Prevent hung git operations
|
|
||||||
permissions:
|
|
||||||
contents: write # Required to push tags
|
|
||||||
# Only move stable tag for non-prerelease versions
|
|
||||||
if: ${{ !inputs.is_prerelease }}
|
|
||||||
steps:
|
|
||||||
- name: Harden the runner
|
|
||||||
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
|
||||||
with:
|
|
||||||
egress-policy: audit
|
|
||||||
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
|
||||||
with:
|
|
||||||
fetch-depth: 0 # Full history needed for tag operations
|
|
||||||
|
|
||||||
- name: Validate inputs
|
|
||||||
env:
|
|
||||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
|
||||||
COMMIT_SHA: ${{ inputs.commit_sha }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
# Validate release tag format
|
|
||||||
if [[ ! "$RELEASE_TAG" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$ ]]; then
|
|
||||||
echo "❌ Error: Invalid release tag format. Expected format: 1.2.3, 1.2.3-alpha"
|
|
||||||
echo "Provided: $RELEASE_TAG"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Validate commit SHA format (40 character hex)
|
|
||||||
if [[ ! "$COMMIT_SHA" =~ ^[a-f0-9]{40}$ ]]; then
|
|
||||||
echo "❌ Error: Invalid commit SHA format. Expected 40 character hex string"
|
|
||||||
echo "Provided: $COMMIT_SHA"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "✅ Input validation passed"
|
|
||||||
echo "Release tag: $RELEASE_TAG"
|
|
||||||
echo "Commit SHA: $COMMIT_SHA"
|
|
||||||
|
|
||||||
- name: Move stable tag
|
|
||||||
env:
|
|
||||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
|
||||||
COMMIT_SHA: ${{ inputs.commit_sha }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
# Configure git
|
|
||||||
git config user.name "github-actions[bot]"
|
|
||||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
|
||||||
|
|
||||||
# Verify the commit exists
|
|
||||||
if ! git cat-file -e "$COMMIT_SHA"; then
|
|
||||||
echo "❌ Error: Commit $COMMIT_SHA does not exist in this repository"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Move stable tag to the release commit
|
|
||||||
echo "📌 Moving stable tag to commit: $COMMIT_SHA (release: $RELEASE_TAG)"
|
|
||||||
git tag -f stable "$COMMIT_SHA"
|
|
||||||
git push origin stable --force
|
|
||||||
|
|
||||||
echo "✅ Successfully moved stable tag to release $RELEASE_TAG"
|
|
||||||
echo "🔗 Stable tag now points to: https://github.com/${{ github.repository }}/commit/$COMMIT_SHA"
|
|
||||||
2
.github/workflows/pr.yml
vendored
2
.github/workflows/pr.yml
vendored
@@ -10,6 +10,8 @@ permissions:
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
pull_request:
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
merge_group:
|
merge_group:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
|
|||||||
@@ -1,50 +1,99 @@
|
|||||||
name: Build Community Testing Images
|
name: Docker Release to Github Experimental
|
||||||
|
|
||||||
# This workflow builds experimental/testing versions of Formbricks for self-hosting customers
|
# This workflow uses actions that are not certified by GitHub.
|
||||||
# to test fixes and features before official releases. Images are pushed to GHCR with
|
# They are provided by a third-party and are governed by
|
||||||
# timestamped experimental versions for easy identification and testing.
|
# separate terms of service, privacy policy, and support
|
||||||
|
# documentation.
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
|
||||||
version_override:
|
env:
|
||||||
description: "Override version (SemVer only, e.g., 1.2.3-beta). Leave empty for auto-generated experimental version."
|
# Use docker.io for Docker Hub if empty
|
||||||
required: false
|
REGISTRY: ghcr.io
|
||||||
type: string
|
# github.repository as <account>/<repo>
|
||||||
|
IMAGE_NAME: ${{ github.repository }}-experimental
|
||||||
|
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||||
|
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
packages: write
|
|
||||||
id-token: write
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build-community-testing:
|
build:
|
||||||
name: Build Community Testing Image
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 45
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
# This is used to complete the identity challenge
|
||||||
|
# with sigstore/fulcio when running outside of PRs.
|
||||||
|
id-token: write
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Harden the runner (Audit all outbound calls)
|
- name: Harden the runner (Audit all outbound calls)
|
||||||
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
||||||
with:
|
with:
|
||||||
egress-policy: audit
|
egress-policy: audit
|
||||||
|
|
||||||
- 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: Build and push community testing image
|
- name: Set up Depot CLI
|
||||||
uses: ./.github/actions/build-and-push-docker
|
uses: depot/setup-action@b0b1ea4f69e92ebf5dea3f8713a1b0c37b2126a5 # v1.6.0
|
||||||
|
|
||||||
|
# Install the cosign tool except on PR
|
||||||
|
# https://github.com/sigstore/cosign-installer
|
||||||
|
- name: Install cosign
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
uses: sigstore/cosign-installer@3454372f43399081ed03b604cb2d021dabca52bb # v3.8.2
|
||||||
|
|
||||||
|
# Login against a Docker registry except on PR
|
||||||
|
# https://github.com/docker/login-action
|
||||||
|
- name: Log into registry ${{ env.REGISTRY }}
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
|
||||||
with:
|
with:
|
||||||
registry_type: "ghcr"
|
registry: ${{ env.REGISTRY }}
|
||||||
ghcr_image_name: "${{ github.repository }}-experimental"
|
username: ${{ github.actor }}
|
||||||
experimental_mode: "true"
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
version: ${{ inputs.version_override }}
|
|
||||||
|
# Extract metadata (tags, labels) for Docker
|
||||||
|
# https://github.com/docker/metadata-action
|
||||||
|
- name: Extract Docker metadata
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # v5.7.0
|
||||||
|
with:
|
||||||
|
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||||
|
|
||||||
|
# Build and push Docker image with Buildx (don't push on PR)
|
||||||
|
# https://github.com/docker/build-push-action
|
||||||
|
- name: Build and push Docker image
|
||||||
|
id: build-and-push
|
||||||
|
uses: depot/build-push-action@636daae76684e38c301daa0c5eca1c095b24e780 # v1.14.0
|
||||||
|
with:
|
||||||
|
project: tw0fqmsx3c
|
||||||
|
token: ${{ secrets.DEPOT_PROJECT_TOKEN }}
|
||||||
|
context: .
|
||||||
|
file: ./apps/web/Dockerfile
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
push: ${{ github.event_name != 'pull_request' }}
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
secrets: |
|
||||||
|
database_url=${{ secrets.DUMMY_DATABASE_URL }}
|
||||||
|
encryption_key=${{ secrets.DUMMY_ENCRYPTION_KEY }}
|
||||||
|
|
||||||
|
# Sign the resulting Docker image digest except on PRs.
|
||||||
|
# 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
|
||||||
|
# transparency data even for private images, pass --force to cosign below.
|
||||||
|
# https://github.com/sigstore/cosign
|
||||||
|
- name: Sign the published Docker image
|
||||||
|
if: ${{ github.event_name != 'pull_request' }}
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
# https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions#using-an-intermediate-environment-variable
|
||||||
DEPOT_PROJECT_TOKEN: ${{ secrets.DEPOT_PROJECT_TOKEN }}
|
TAGS: ${{ steps.meta.outputs.tags }}
|
||||||
DUMMY_DATABASE_URL: ${{ secrets.DUMMY_DATABASE_URL }}
|
DIGEST: ${{ steps.build-and-push.outputs.digest }}
|
||||||
DUMMY_ENCRYPTION_KEY: ${{ secrets.DUMMY_ENCRYPTION_KEY }}
|
# This step uses the identity token to provision an ephemeral certificate
|
||||||
DUMMY_REDIS_URL: ${{ secrets.DUMMY_REDIS_URL }}
|
# against the sigstore community Fulcio instance.
|
||||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST}
|
||||||
|
|||||||
126
.github/workflows/release-docker-github.yml
vendored
126
.github/workflows/release-docker-github.yml
vendored
@@ -1,4 +1,4 @@
|
|||||||
name: Release Community Docker Images
|
name: Docker Release to Github
|
||||||
|
|
||||||
# This workflow uses actions that are not certified by GitHub.
|
# This workflow uses actions that are not certified by GitHub.
|
||||||
# They are provided by a third-party and are governed by
|
# They are provided by a third-party and are governed by
|
||||||
@@ -7,12 +7,6 @@ name: Release Community Docker Images
|
|||||||
|
|
||||||
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
|
||||||
@@ -23,14 +17,12 @@ env:
|
|||||||
REGISTRY: ghcr.io
|
REGISTRY: ghcr.io
|
||||||
# github.repository as <account>/<repo>
|
# github.repository as <account>/<repo>
|
||||||
IMAGE_NAME: ${{ github.repository }}
|
IMAGE_NAME: ${{ github.repository }}
|
||||||
|
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||||
permissions:
|
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
|
||||||
contents: read
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 45
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
packages: write
|
packages: write
|
||||||
@@ -43,60 +35,82 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Harden the runner (Audit all outbound calls)
|
- name: Harden the runner (Audit all outbound calls)
|
||||||
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
||||||
with:
|
with:
|
||||||
egress-policy: audit
|
egress-policy: audit
|
||||||
|
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
|
||||||
- name: Extract release version from tag
|
- name: Get Release Tag
|
||||||
id: extract_release_tag
|
id: extract_release_tag
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
TAG=${{ github.ref }}
|
||||||
|
TAG=${TAG#refs/tags/v}
|
||||||
# Extract tag name with fallback logic for different trigger contexts
|
echo "RELEASE_TAG=$TAG" >> $GITHUB_ENV
|
||||||
if [[ -n "${RELEASE_TAG:-}" ]]; then
|
|
||||||
TAG="$RELEASE_TAG"
|
|
||||||
echo "Using RELEASE_TAG override: $TAG"
|
|
||||||
elif [[ "$GITHUB_REF_NAME" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.-]+)?$ ]] || [[ "$GITHUB_REF_NAME" =~ ^v[0-9] ]]; then
|
|
||||||
TAG="$GITHUB_REF_NAME"
|
|
||||||
echo "Using GITHUB_REF_NAME (looks like tag): $TAG"
|
|
||||||
else
|
|
||||||
# Fallback: extract from GITHUB_REF for direct tag triggers
|
|
||||||
TAG="${GITHUB_REF#refs/tags/}"
|
|
||||||
if [[ -z "$TAG" || "$TAG" == "$GITHUB_REF" ]]; then
|
|
||||||
TAG="$GITHUB_REF_NAME"
|
|
||||||
echo "Using GITHUB_REF_NAME as final fallback: $TAG"
|
|
||||||
else
|
|
||||||
echo "Extracted from GITHUB_REF: $TAG"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Strip v-prefix if present (normalize to clean SemVer)
|
|
||||||
TAG=${TAG#[vV]}
|
|
||||||
|
|
||||||
# Validate SemVer format (supports prereleases like 4.0.0-rc.1)
|
|
||||||
if [[ ! "$TAG" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.-]+)?$ ]]; then
|
|
||||||
echo "ERROR: Invalid tag format '$TAG'. Expected SemVer (e.g., 1.2.3, 4.0.0-rc.1)"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "VERSION=$TAG" >> $GITHUB_OUTPUT
|
echo "VERSION=$TAG" >> $GITHUB_OUTPUT
|
||||||
echo "Using version: $TAG"
|
|
||||||
|
|
||||||
- name: Build and push community release image
|
- name: Update package.json version
|
||||||
id: build
|
run: |
|
||||||
uses: ./.github/actions/build-and-push-docker
|
sed -i "s/\"version\": \"0.0.0\"/\"version\": \"${{ env.RELEASE_TAG }}\"/" ./apps/web/package.json
|
||||||
|
cat ./apps/web/package.json | grep version
|
||||||
|
|
||||||
|
- name: Set up Depot CLI
|
||||||
|
uses: depot/setup-action@b0b1ea4f69e92ebf5dea3f8713a1b0c37b2126a5 # v1.6.0
|
||||||
|
|
||||||
|
# Install the cosign tool except on PR
|
||||||
|
# https://github.com/sigstore/cosign-installer
|
||||||
|
- name: Install cosign
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
uses: sigstore/cosign-installer@3454372f43399081ed03b604cb2d021dabca52bb # v3.8.2
|
||||||
|
|
||||||
|
# Login against a Docker registry except on PR
|
||||||
|
# https://github.com/docker/login-action
|
||||||
|
- name: Log into registry ${{ env.REGISTRY }}
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
|
||||||
with:
|
with:
|
||||||
registry_type: "ghcr"
|
registry: ${{ env.REGISTRY }}
|
||||||
ghcr_image_name: ${{ env.IMAGE_NAME }}
|
username: ${{ github.actor }}
|
||||||
version: ${{ steps.extract_release_tag.outputs.VERSION }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
is_prerelease: ${{ inputs.IS_PRERELEASE }}
|
|
||||||
|
# Extract metadata (tags, labels) for Docker
|
||||||
|
# https://github.com/docker/metadata-action
|
||||||
|
- name: Extract Docker metadata
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # v5.7.0
|
||||||
|
with:
|
||||||
|
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||||
|
|
||||||
|
# Build and push Docker image with Buildx (don't push on PR)
|
||||||
|
# https://github.com/docker/build-push-action
|
||||||
|
- name: Build and push Docker image
|
||||||
|
id: build-and-push
|
||||||
|
uses: depot/build-push-action@636daae76684e38c301daa0c5eca1c095b24e780 # v1.14.0
|
||||||
|
with:
|
||||||
|
project: tw0fqmsx3c
|
||||||
|
token: ${{ secrets.DEPOT_PROJECT_TOKEN }}
|
||||||
|
context: .
|
||||||
|
file: ./apps/web/Dockerfile
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
push: ${{ github.event_name != 'pull_request' }}
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
secrets: |
|
||||||
|
database_url=${{ secrets.DUMMY_DATABASE_URL }}
|
||||||
|
encryption_key=${{ secrets.DUMMY_ENCRYPTION_KEY }}
|
||||||
|
|
||||||
|
# Sign the resulting Docker image digest except on PRs.
|
||||||
|
# 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
|
||||||
|
# transparency data even for private images, pass --force to cosign below.
|
||||||
|
# https://github.com/sigstore/cosign
|
||||||
|
- name: Sign the published Docker image
|
||||||
|
if: ${{ github.event_name != 'pull_request' }}
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
# https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions#using-an-intermediate-environment-variable
|
||||||
DEPOT_PROJECT_TOKEN: ${{ secrets.DEPOT_PROJECT_TOKEN }}
|
TAGS: ${{ steps.meta.outputs.tags }}
|
||||||
DUMMY_DATABASE_URL: ${{ secrets.DUMMY_DATABASE_URL }}
|
DIGEST: ${{ steps.build-and-push.outputs.digest }}
|
||||||
DUMMY_ENCRYPTION_KEY: ${{ secrets.DUMMY_ENCRYPTION_KEY }}
|
# This step uses the identity token to provision an ephemeral certificate
|
||||||
DUMMY_REDIS_URL: ${{ secrets.DUMMY_REDIS_URL }}
|
# against the sigstore community Fulcio instance.
|
||||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST}
|
||||||
|
|||||||
53
.github/workflows/release-helm-chart.yml
vendored
53
.github/workflows/release-helm-chart.yml
vendored
@@ -19,30 +19,15 @@ jobs:
|
|||||||
contents: read
|
contents: read
|
||||||
steps:
|
steps:
|
||||||
- name: Harden the runner (Audit all outbound calls)
|
- name: Harden the runner (Audit all outbound calls)
|
||||||
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
|
||||||
with:
|
with:
|
||||||
egress-policy: audit
|
egress-policy: audit
|
||||||
|
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
|
||||||
- name: Validate input version
|
- name: Extract release version
|
||||||
env:
|
run: echo "VERSION=${{ github.event.release.tag_name }}" >> $GITHUB_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
|
||||||
@@ -50,44 +35,20 @@ jobs:
|
|||||||
version: latest
|
version: latest
|
||||||
|
|
||||||
- name: Log in to GitHub Container Registry
|
- name: Log in to GitHub Container Registry
|
||||||
env:
|
run: echo "${{ secrets.GITHUB_TOKEN }}" | helm registry login ghcr.io --username ${{ github.actor }} --password-stdin
|
||||||
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
|
||||||
env:
|
|
||||||
VERSION: ${{ env.VERSION }}
|
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
yq -i ".version = \"${{ inputs.VERSION }}\"" helm-chart/Chart.yaml
|
||||||
|
yq -i ".appVersion = \"v${{ inputs.VERSION }}\"" helm-chart/Chart.yaml
|
||||||
echo "Updating Chart.yaml with version: ${VERSION}"
|
|
||||||
yq -i ".version = \"${VERSION}\"" helm-chart/Chart.yaml
|
|
||||||
yq -i ".appVersion = \"${VERSION}\"" helm-chart/Chart.yaml
|
|
||||||
|
|
||||||
echo "✅ Successfully updated Chart.yaml"
|
|
||||||
|
|
||||||
- name: Package Helm chart
|
- name: Package Helm chart
|
||||||
env:
|
|
||||||
VERSION: ${{ env.VERSION }}
|
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
echo "Packaging Helm chart version: ${VERSION}"
|
|
||||||
helm package ./helm-chart
|
helm package ./helm-chart
|
||||||
|
|
||||||
echo "✅ Successfully packaged formbricks-${VERSION}.tgz"
|
|
||||||
|
|
||||||
- name: Push Helm chart to GitHub Container Registry
|
- name: Push Helm chart to GitHub Container Registry
|
||||||
env:
|
|
||||||
VERSION: ${{ env.VERSION }}
|
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
helm push formbricks-${{ inputs.VERSION }}.tgz oci://ghcr.io/formbricks/helm-charts
|
||||||
|
|
||||||
echo "Pushing Helm chart to registry: formbricks-${VERSION}.tgz"
|
|
||||||
helm push "formbricks-${VERSION}.tgz" oci://ghcr.io/formbricks/helm-charts
|
|
||||||
|
|
||||||
echo "✅ Successfully pushed Helm chart to registry"
|
|
||||||
|
|||||||
81
.github/workflows/scorecard.yml
vendored
Normal file
81
.github/workflows/scorecard.yml
vendored
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
# 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,3 +56,11 @@ 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! 🙏
|
||||||
|
|||||||
1
.github/workflows/sonarqube.yml
vendored
1
.github/workflows/sonarqube.yml
vendored
@@ -43,7 +43,6 @@ jobs:
|
|||||||
sed -i "s/ENCRYPTION_KEY=.*/ENCRYPTION_KEY=${RANDOM_KEY}/" .env
|
sed -i "s/ENCRYPTION_KEY=.*/ENCRYPTION_KEY=${RANDOM_KEY}/" .env
|
||||||
sed -i "s/CRON_SECRET=.*/CRON_SECRET=${RANDOM_KEY}/" .env
|
sed -i "s/CRON_SECRET=.*/CRON_SECRET=${RANDOM_KEY}/" .env
|
||||||
sed -i "s/NEXTAUTH_SECRET=.*/NEXTAUTH_SECRET=${RANDOM_KEY}/" .env
|
sed -i "s/NEXTAUTH_SECRET=.*/NEXTAUTH_SECRET=${RANDOM_KEY}/" .env
|
||||||
sed -i "s|REDIS_URL=.*|REDIS_URL=|" .env
|
|
||||||
|
|
||||||
- name: Run tests with coverage
|
- name: Run tests with coverage
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -14,14 +14,12 @@ 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 }}
|
||||||
@@ -35,7 +33,7 @@ jobs:
|
|||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
|
||||||
- name: Tailscale
|
- name: Tailscale
|
||||||
uses: tailscale/github-action@84a3f23bb4d843bcf4da6cf824ec1be473daf4de # v3.2.3
|
uses: tailscale/github-action@v3
|
||||||
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 }}
|
||||||
|
|||||||
1
.github/workflows/test.yml
vendored
1
.github/workflows/test.yml
vendored
@@ -41,7 +41,6 @@ jobs:
|
|||||||
sed -i "s/ENCRYPTION_KEY=.*/ENCRYPTION_KEY=${RANDOM_KEY}/" .env
|
sed -i "s/ENCRYPTION_KEY=.*/ENCRYPTION_KEY=${RANDOM_KEY}/" .env
|
||||||
sed -i "s/CRON_SECRET=.*/CRON_SECRET=${RANDOM_KEY}/" .env
|
sed -i "s/CRON_SECRET=.*/CRON_SECRET=${RANDOM_KEY}/" .env
|
||||||
sed -i "s/NEXTAUTH_SECRET=.*/NEXTAUTH_SECRET=${RANDOM_KEY}/" .env
|
sed -i "s/NEXTAUTH_SECRET=.*/NEXTAUTH_SECRET=${RANDOM_KEY}/" .env
|
||||||
sed -i "s|REDIS_URL=.*|REDIS_URL=|" .env
|
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
run: pnpm test
|
run: pnpm test
|
||||||
|
|||||||
10
.github/workflows/tolgee.yml
vendored
10
.github/workflows/tolgee.yml
vendored
@@ -27,18 +27,10 @@ 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: |
|
||||||
# Validate and sanitize branch name - only allow alphanumeric, dots, underscores, hyphens, and forward slashes
|
RAW_BRANCH="${{ github.head_ref }}"
|
||||||
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
|
||||||
|
|||||||
32
.github/workflows/welcome-new-contributors.yml
vendored
Normal file
32
.github/workflows/welcome-new-contributors.yml
vendored
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
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. 😊
|
||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -73,5 +73,3 @@ infra/terraform/.terraform/
|
|||||||
/.idea/
|
/.idea/
|
||||||
/*.iml
|
/*.iml
|
||||||
packages/ios/FormbricksSDK/FormbricksSDK.xcodeproj/project.xcworkspace/xcuserdata
|
packages/ios/FormbricksSDK/FormbricksSDK.xcodeproj/project.xcworkspace/xcuserdata
|
||||||
.cursorrules
|
|
||||||
i18n.cache
|
|
||||||
|
|||||||
@@ -31,18 +31,6 @@
|
|||||||
{
|
{
|
||||||
"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"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"language": "ja-JP",
|
|
||||||
"path": "./apps/web/locales/ja-JP.json"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"language": "zh-Hans-CN",
|
|
||||||
"path": "./apps/web/locales/zh-Hans-CN.json"
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"forceMode": "OVERRIDE"
|
"forceMode": "OVERRIDE"
|
||||||
|
|||||||
2
.vscode/settings.json
vendored
2
.vscode/settings.json
vendored
@@ -1,6 +1,4 @@
|
|||||||
{
|
{
|
||||||
"eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],
|
|
||||||
"eslint.workingDirectories": [{ "mode": "auto" }],
|
|
||||||
"javascript.updateImportsOnFileMove.enabled": "always",
|
"javascript.updateImportsOnFileMove.enabled": "always",
|
||||||
"sonarlint.connectedMode.project": {
|
"sonarlint.connectedMode.project": {
|
||||||
"connectionId": "formbricks",
|
"connectionId": "formbricks",
|
||||||
|
|||||||
@@ -14,7 +14,17 @@ Are you brimming with brilliant ideas? For new features that can elevate Formbri
|
|||||||
|
|
||||||
## 🛠 Crafting Pull Requests
|
## 🛠 Crafting Pull Requests
|
||||||
|
|
||||||
For the time being, we don't have the capacity to properly facilitate community contributions. It's a lot of engineering attention often spent on issues which don't follow our prioritization, so we've decided to only facilitate community code contributions in rare exceptions in the coming months.
|
Ready to dive into the code and make a real impact? Here's your path:
|
||||||
|
|
||||||
|
1. **Read our Best Practices**: [It takes 5 minutes](https://formbricks.com/docs/developer-docs/contributing/get-started) but will help you save hours 🤓
|
||||||
|
|
||||||
|
1. **Fork the Repository:** Fork our repository or use [Gitpod](https://gitpod.io) or use [Github Codespaces](https://github.com/features/codespaces) to get started instantly.
|
||||||
|
|
||||||
|
1. **Tweak and Transform:** Work your coding magic and apply your changes.
|
||||||
|
|
||||||
|
1. **Pull Request Act:** If you're ready to go, craft a new pull request closely following our PR template 🙏
|
||||||
|
|
||||||
|
Would you prefer a chat before you dive into a lot of work? [Github Discussions](https://github.com/formbricks/formbricks/discussions) is your harbor. Share your thoughts, and we'll meet you there with open arms. We're responsive and friendly, promise!
|
||||||
|
|
||||||
## 🚀 Aspiring Features
|
## 🚀 Aspiring Features
|
||||||
|
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ The Open Source Qualtrics Alternative
|
|||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://github.com/formbricks/formbricks/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-AGPL-purple" alt="License"></a> <a href="https://github.com/formbricks/formbricks/stargazers"><img src="https://img.shields.io/github/stars/formbricks/formbricks?logo=github" alt="Github Stars"></a>
|
<a href="https://github.com/formbricks/formbricks/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-AGPL-purple" alt="License"></a> <a href="https://github.com/formbricks/formbricks/stargazers"><img src="https://img.shields.io/github/stars/formbricks/formbricks?logo=github" alt="Github Stars"></a>
|
||||||
<a href="https://insights.linuxfoundation.org/project/formbricks"><img src="https://insights.linuxfoundation.org/api/badge/health-score?project=formbricks"></a>
|
|
||||||
<a href="https://news.ycombinator.com/item?id=32303986"><img src="https://img.shields.io/badge/Hacker%20News-122-%23FF6600" alt="Hacker News"></a>
|
<a href="https://news.ycombinator.com/item?id=32303986"><img src="https://img.shields.io/badge/Hacker%20News-122-%23FF6600" alt="Hacker News"></a>
|
||||||
<a href="[https://www.producthunt.com/products/formbricks](https://www.producthunt.com/posts/formbricks)"><img src="https://img.shields.io/badge/Product%20Hunt-455-orange?logo=producthunt&logoColor=%23fff" alt="Product Hunt"></a>
|
<a href="[https://www.producthunt.com/products/formbricks](https://www.producthunt.com/posts/formbricks)"><img src="https://img.shields.io/badge/Product%20Hunt-455-orange?logo=producthunt&logoColor=%23fff" alt="Product Hunt"></a>
|
||||||
<a href="https://github.blog/2023-04-12-github-accelerator-our-first-cohort-and-whats-next/"><img src="https://img.shields.io/badge/2023-blue?logo=github&label=Github%20Accelerator" alt="Github Accelerator"></a>
|
<a href="https://github.blog/2023-04-12-github-accelerator-our-first-cohort-and-whats-next/"><img src="https://img.shields.io/badge/2023-blue?logo=github&label=Github%20Accelerator" alt="Github Accelerator"></a>
|
||||||
@@ -193,7 +192,7 @@ Here are a few options:
|
|||||||
|
|
||||||
- Upvote issues with 👍 reaction so we know what the demand for a particular issue is to prioritize it within the roadmap.
|
- Upvote issues with 👍 reaction so we know what the demand for a particular issue is to prioritize it within the roadmap.
|
||||||
|
|
||||||
- Note: For the time being, we can only facilitate code contributions as an exception.
|
Please check out [our contribution guide](https://formbricks.com/docs/developer-docs/contributing/get-started) and our [list of open issues](https://github.com/formbricks/formbricks/issues) for more information.
|
||||||
|
|
||||||
## All Thanks To Our Contributors
|
## All Thanks To Our Contributors
|
||||||
|
|
||||||
|
|||||||
@@ -1,25 +1,23 @@
|
|||||||
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.
|
||||||
*/
|
*/
|
||||||
function getAbsolutePath(value: string): any {
|
const getAbsolutePath = (value: string) => {
|
||||||
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)"],
|
||||||
addons: [
|
addons: [
|
||||||
getAbsolutePath("@storybook/addon-onboarding"),
|
getAbsolutePath("@storybook/addon-onboarding"),
|
||||||
getAbsolutePath("@storybook/addon-links"),
|
getAbsolutePath("@storybook/addon-links"),
|
||||||
|
getAbsolutePath("@storybook/addon-essentials"),
|
||||||
getAbsolutePath("@chromatic-com/storybook"),
|
getAbsolutePath("@chromatic-com/storybook"),
|
||||||
|
getAbsolutePath("@storybook/addon-interactions"),
|
||||||
getAbsolutePath("@storybook/addon-a11y"),
|
getAbsolutePath("@storybook/addon-a11y"),
|
||||||
getAbsolutePath("@storybook/addon-docs"),
|
|
||||||
],
|
],
|
||||||
framework: {
|
framework: {
|
||||||
name: getAbsolutePath("@storybook/react-vite"),
|
name: getAbsolutePath("@storybook/react-vite"),
|
||||||
|
|||||||
@@ -1,32 +1,5 @@
|
|||||||
import type { Preview } from "@storybook/react-vite";
|
import type { Preview } from "@storybook/react";
|
||||||
import { TolgeeProvider } from "@tolgee/react";
|
|
||||||
import React from "react";
|
|
||||||
// Import translation data for Storybook
|
|
||||||
import enUSTranslations from "../../web/locales/en-US.json";
|
|
||||||
import "../../web/modules/ui/globals.css";
|
import "../../web/modules/ui/globals.css";
|
||||||
import { TolgeeBase } from "../../web/tolgee/shared";
|
|
||||||
|
|
||||||
// Create a Storybook-specific Tolgee decorator
|
|
||||||
const withTolgee = (Story: any) => {
|
|
||||||
const tolgee = TolgeeBase().init({
|
|
||||||
tagNewKeys: [], // No branch tagging in Storybook
|
|
||||||
});
|
|
||||||
|
|
||||||
return React.createElement(
|
|
||||||
TolgeeProvider,
|
|
||||||
{
|
|
||||||
tolgee,
|
|
||||||
fallback: "Loading",
|
|
||||||
ssr: {
|
|
||||||
language: "en-US",
|
|
||||||
staticData: {
|
|
||||||
"en-US": enUSTranslations,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
React.createElement(Story)
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const preview: Preview = {
|
const preview: Preview = {
|
||||||
parameters: {
|
parameters: {
|
||||||
@@ -37,7 +10,6 @@ const preview: Preview = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
decorators: [withTolgee],
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default preview;
|
export default preview;
|
||||||
|
|||||||
@@ -14,19 +14,23 @@
|
|||||||
"eslint-plugin-react-refresh": "0.4.20"
|
"eslint-plugin-react-refresh": "0.4.20"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@chromatic-com/storybook": "^4.0.1",
|
"@chromatic-com/storybook": "3.2.6",
|
||||||
"@storybook/addon-a11y": "9.0.15",
|
"@storybook/addon-a11y": "8.6.12",
|
||||||
"@storybook/addon-links": "9.0.15",
|
"@storybook/addon-essentials": "8.6.12",
|
||||||
"@storybook/addon-onboarding": "9.0.15",
|
"@storybook/addon-interactions": "8.6.12",
|
||||||
"@storybook/react-vite": "9.0.15",
|
"@storybook/addon-links": "8.6.12",
|
||||||
|
"@storybook/addon-onboarding": "8.6.12",
|
||||||
|
"@storybook/blocks": "8.6.12",
|
||||||
|
"@storybook/react": "8.6.12",
|
||||||
|
"@storybook/react-vite": "8.6.12",
|
||||||
|
"@storybook/test": "8.6.12",
|
||||||
"@typescript-eslint/eslint-plugin": "8.32.0",
|
"@typescript-eslint/eslint-plugin": "8.32.0",
|
||||||
"@typescript-eslint/parser": "8.32.0",
|
"@typescript-eslint/parser": "8.32.0",
|
||||||
"@vitejs/plugin-react": "4.4.1",
|
"@vitejs/plugin-react": "4.4.1",
|
||||||
"esbuild": "0.25.4",
|
"esbuild": "0.25.4",
|
||||||
"eslint-plugin-storybook": "9.0.15",
|
"eslint-plugin-storybook": "0.12.0",
|
||||||
"prop-types": "15.8.1",
|
"prop-types": "15.8.1",
|
||||||
"storybook": "9.0.15",
|
"storybook": "8.6.12",
|
||||||
"vite": "6.3.6",
|
"vite": "6.3.5"
|
||||||
"@storybook/addon-docs": "9.0.15"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Meta } from "@storybook/addon-docs/blocks";
|
import { Meta } from "@storybook/blocks";
|
||||||
|
|
||||||
import Accessibility from "./assets/accessibility.png";
|
import Accessibility from "./assets/accessibility.png";
|
||||||
import AddonLibrary from "./assets/addon-library.png";
|
import AddonLibrary from "./assets/addon-library.png";
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
FROM node:22-alpine3.22 AS base
|
FROM node:22-alpine3.21 AS base
|
||||||
|
|
||||||
#
|
#
|
||||||
## step 1: Prune monorepo
|
## step 1: Prune monorepo
|
||||||
@@ -25,18 +25,26 @@ RUN corepack prepare pnpm@9.15.9 --activate
|
|||||||
# Install necessary build tools and compilers
|
# Install necessary build tools and compilers
|
||||||
RUN apk update && apk add --no-cache cmake g++ gcc jq make openssl-dev python3
|
RUN apk update && apk add --no-cache cmake g++ gcc jq make openssl-dev python3
|
||||||
|
|
||||||
# Copy the secrets handling script
|
# BuildKit secret handling without hardcoded fallback values
|
||||||
COPY apps/web/scripts/docker/read-secrets.sh /tmp/read-secrets.sh
|
# This approach relies entirely on secrets passed from GitHub Actions
|
||||||
RUN chmod +x /tmp/read-secrets.sh
|
RUN echo '#!/bin/sh' > /tmp/read-secrets.sh && \
|
||||||
|
echo 'if [ -f "/run/secrets/database_url" ]; then' >> /tmp/read-secrets.sh && \
|
||||||
|
echo ' export DATABASE_URL=$(cat /run/secrets/database_url)' >> /tmp/read-secrets.sh && \
|
||||||
|
echo 'else' >> /tmp/read-secrets.sh && \
|
||||||
|
echo ' echo "DATABASE_URL secret not found. Build may fail if this is required."' >> /tmp/read-secrets.sh && \
|
||||||
|
echo 'fi' >> /tmp/read-secrets.sh && \
|
||||||
|
echo 'if [ -f "/run/secrets/encryption_key" ]; then' >> /tmp/read-secrets.sh && \
|
||||||
|
echo ' export ENCRYPTION_KEY=$(cat /run/secrets/encryption_key)' >> /tmp/read-secrets.sh && \
|
||||||
|
echo 'else' >> /tmp/read-secrets.sh && \
|
||||||
|
echo ' echo "ENCRYPTION_KEY secret not found. Build may fail if this is required."' >> /tmp/read-secrets.sh && \
|
||||||
|
echo 'fi' >> /tmp/read-secrets.sh && \
|
||||||
|
echo 'exec "$@"' >> /tmp/read-secrets.sh && \
|
||||||
|
chmod +x /tmp/read-secrets.sh
|
||||||
|
|
||||||
# Increase Node.js memory limit as a regular build argument
|
# Increase Node.js memory limit as a regular build argument
|
||||||
ARG NODE_OPTIONS="--max_old_space_size=8192"
|
ARG NODE_OPTIONS="--max_old_space_size=4096"
|
||||||
ENV NODE_OPTIONS=${NODE_OPTIONS}
|
ENV NODE_OPTIONS=${NODE_OPTIONS}
|
||||||
|
|
||||||
# Target architecture - automatically provided by Docker in multi-platform builds
|
|
||||||
# but needs explicit declaration for some build systems (like Depot)
|
|
||||||
ARG TARGETARCH
|
|
||||||
|
|
||||||
# Set the working directory
|
# Set the working directory
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@@ -54,15 +62,10 @@ RUN touch apps/web/.env
|
|||||||
# Install the dependencies
|
# Install the dependencies
|
||||||
RUN pnpm install --ignore-scripts
|
RUN pnpm install --ignore-scripts
|
||||||
|
|
||||||
# Build the database package first
|
|
||||||
RUN pnpm build --filter=@formbricks/database
|
|
||||||
|
|
||||||
# Build the project using our secret reader script
|
# Build the project using our secret reader script
|
||||||
# This mounts the secrets only during this build step without storing them in layers
|
# This mounts the secrets only during this build step without storing them in layers
|
||||||
RUN --mount=type=secret,id=database_url \
|
RUN --mount=type=secret,id=database_url \
|
||||||
--mount=type=secret,id=encryption_key \
|
--mount=type=secret,id=encryption_key \
|
||||||
--mount=type=secret,id=redis_url \
|
|
||||||
--mount=type=secret,id=sentry_auth_token \
|
|
||||||
/tmp/read-secrets.sh pnpm build --filter=@formbricks/web...
|
/tmp/read-secrets.sh pnpm build --filter=@formbricks/web...
|
||||||
|
|
||||||
# Extract Prisma version
|
# Extract Prisma version
|
||||||
@@ -103,8 +106,20 @@ RUN chown -R nextjs:nextjs ./apps/web/public && chmod -R 755 ./apps/web/public
|
|||||||
COPY --from=installer /app/packages/database/schema.prisma ./packages/database/schema.prisma
|
COPY --from=installer /app/packages/database/schema.prisma ./packages/database/schema.prisma
|
||||||
RUN chown nextjs:nextjs ./packages/database/schema.prisma && chmod 644 ./packages/database/schema.prisma
|
RUN chown nextjs:nextjs ./packages/database/schema.prisma && chmod 644 ./packages/database/schema.prisma
|
||||||
|
|
||||||
COPY --from=installer /app/packages/database/dist ./packages/database/dist
|
COPY --from=installer /app/packages/database/package.json ./packages/database/package.json
|
||||||
RUN chown -R nextjs:nextjs ./packages/database/dist && chmod -R 755 ./packages/database/dist
|
RUN chown nextjs:nextjs ./packages/database/package.json && chmod 644 ./packages/database/package.json
|
||||||
|
|
||||||
|
COPY --from=installer /app/packages/database/migration ./packages/database/migration
|
||||||
|
RUN chown -R nextjs:nextjs ./packages/database/migration && chmod -R 755 ./packages/database/migration
|
||||||
|
|
||||||
|
COPY --from=installer /app/packages/database/src ./packages/database/src
|
||||||
|
RUN chown -R nextjs:nextjs ./packages/database/src && chmod -R 755 ./packages/database/src
|
||||||
|
|
||||||
|
COPY --from=installer /app/packages/database/node_modules ./packages/database/node_modules
|
||||||
|
RUN chown -R nextjs:nextjs ./packages/database/node_modules && chmod -R 755 ./packages/database/node_modules
|
||||||
|
|
||||||
|
COPY --from=installer /app/packages/logger/dist ./packages/database/node_modules/@formbricks/logger/dist
|
||||||
|
RUN chown -R nextjs:nextjs ./packages/database/node_modules/@formbricks/logger/dist && chmod -R 755 ./packages/database/node_modules/@formbricks/logger/dist
|
||||||
|
|
||||||
COPY --from=installer /app/node_modules/@prisma/client ./node_modules/@prisma/client
|
COPY --from=installer /app/node_modules/@prisma/client ./node_modules/@prisma/client
|
||||||
RUN chown -R nextjs:nextjs ./node_modules/@prisma/client && chmod -R 755 ./node_modules/@prisma/client
|
RUN chown -R nextjs:nextjs ./node_modules/@prisma/client && chmod -R 755 ./node_modules/@prisma/client
|
||||||
@@ -115,6 +130,9 @@ RUN chown -R nextjs:nextjs ./node_modules/.prisma && chmod -R 755 ./node_modules
|
|||||||
COPY --from=installer /prisma_version.txt .
|
COPY --from=installer /prisma_version.txt .
|
||||||
RUN chown nextjs:nextjs ./prisma_version.txt && chmod 644 ./prisma_version.txt
|
RUN chown nextjs:nextjs ./prisma_version.txt && chmod 644 ./prisma_version.txt
|
||||||
|
|
||||||
|
COPY /docker/cronjobs /app/docker/cronjobs
|
||||||
|
RUN chmod -R 755 /app/docker/cronjobs
|
||||||
|
|
||||||
COPY --from=installer /app/node_modules/@paralleldrive/cuid2 ./node_modules/@paralleldrive/cuid2
|
COPY --from=installer /app/node_modules/@paralleldrive/cuid2 ./node_modules/@paralleldrive/cuid2
|
||||||
RUN chmod -R 755 ./node_modules/@paralleldrive/cuid2
|
RUN chmod -R 755 ./node_modules/@paralleldrive/cuid2
|
||||||
|
|
||||||
@@ -124,14 +142,12 @@ RUN chmod -R 755 ./node_modules/@noble/hashes
|
|||||||
COPY --from=installer /app/node_modules/zod ./node_modules/zod
|
COPY --from=installer /app/node_modules/zod ./node_modules/zod
|
||||||
RUN chmod -R 755 ./node_modules/zod
|
RUN chmod -R 755 ./node_modules/zod
|
||||||
|
|
||||||
|
RUN npm install --ignore-scripts -g tsx typescript pino-pretty
|
||||||
RUN npm install -g prisma
|
RUN npm install -g prisma
|
||||||
|
|
||||||
# Create a startup script to handle the conditional logic
|
|
||||||
COPY --from=installer /app/apps/web/scripts/docker/next-start.sh /home/nextjs/start.sh
|
|
||||||
RUN chown nextjs:nextjs /home/nextjs/start.sh && chmod +x /home/nextjs/start.sh
|
|
||||||
|
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
ENV HOSTNAME="0.0.0.0"
|
ENV HOSTNAME "0.0.0.0"
|
||||||
|
ENV NODE_ENV="production"
|
||||||
USER nextjs
|
USER nextjs
|
||||||
|
|
||||||
# Prepare volume for uploads
|
# Prepare volume for uploads
|
||||||
@@ -142,4 +158,12 @@ VOLUME /home/nextjs/apps/web/uploads/
|
|||||||
RUN mkdir -p /home/nextjs/apps/web/saml-connection
|
RUN mkdir -p /home/nextjs/apps/web/saml-connection
|
||||||
VOLUME /home/nextjs/apps/web/saml-connection
|
VOLUME /home/nextjs/apps/web/saml-connection
|
||||||
|
|
||||||
CMD ["/home/nextjs/start.sh"]
|
CMD if [ "${DOCKER_CRON_ENABLED:-1}" = "1" ]; then \
|
||||||
|
echo "Starting cron jobs..."; \
|
||||||
|
supercronic -quiet /app/docker/cronjobs & \
|
||||||
|
else \
|
||||||
|
echo "Docker cron jobs are disabled via DOCKER_CRON_ENABLED=0"; \
|
||||||
|
fi; \
|
||||||
|
(cd packages/database && npm run db:migrate:deploy) && \
|
||||||
|
(cd packages/database && npm run db:create-saml-database:deploy) && \
|
||||||
|
(cd apps/web && exec node server.js)
|
||||||
@@ -23,12 +23,12 @@ describe("ConnectWithFormbricks", () => {
|
|||||||
const webAppUrl = "http://app";
|
const webAppUrl = "http://app";
|
||||||
const channel = {} as any;
|
const channel = {} as any;
|
||||||
|
|
||||||
test("renders waiting state when appSetupCompleted is false", () => {
|
test("renders waiting state when widgetSetupCompleted is false", () => {
|
||||||
render(
|
render(
|
||||||
<ConnectWithFormbricks
|
<ConnectWithFormbricks
|
||||||
environment={environment}
|
environment={environment}
|
||||||
publicDomain={webAppUrl}
|
webAppUrl={webAppUrl}
|
||||||
appSetupCompleted={false}
|
widgetSetupCompleted={false}
|
||||||
channel={channel}
|
channel={channel}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
@@ -36,12 +36,12 @@ describe("ConnectWithFormbricks", () => {
|
|||||||
expect(screen.getByText("environments.connect.waiting_for_your_signal")).toBeInTheDocument();
|
expect(screen.getByText("environments.connect.waiting_for_your_signal")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("renders success state when appSetupCompleted is true", () => {
|
test("renders success state when widgetSetupCompleted is true", () => {
|
||||||
render(
|
render(
|
||||||
<ConnectWithFormbricks
|
<ConnectWithFormbricks
|
||||||
environment={environment}
|
environment={environment}
|
||||||
publicDomain={webAppUrl}
|
webAppUrl={webAppUrl}
|
||||||
appSetupCompleted={true}
|
widgetSetupCompleted={true}
|
||||||
channel={channel}
|
channel={channel}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
@@ -53,8 +53,8 @@ describe("ConnectWithFormbricks", () => {
|
|||||||
render(
|
render(
|
||||||
<ConnectWithFormbricks
|
<ConnectWithFormbricks
|
||||||
environment={environment}
|
environment={environment}
|
||||||
publicDomain={webAppUrl}
|
webAppUrl={webAppUrl}
|
||||||
appSetupCompleted={true}
|
widgetSetupCompleted={true}
|
||||||
channel={channel}
|
channel={channel}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
@@ -67,8 +67,8 @@ describe("ConnectWithFormbricks", () => {
|
|||||||
render(
|
render(
|
||||||
<ConnectWithFormbricks
|
<ConnectWithFormbricks
|
||||||
environment={environment}
|
environment={environment}
|
||||||
publicDomain={webAppUrl}
|
webAppUrl={webAppUrl}
|
||||||
appSetupCompleted={false}
|
widgetSetupCompleted={false}
|
||||||
channel={channel}
|
channel={channel}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -12,15 +12,15 @@ import { OnboardingSetupInstructions } from "./OnboardingSetupInstructions";
|
|||||||
|
|
||||||
interface ConnectWithFormbricksProps {
|
interface ConnectWithFormbricksProps {
|
||||||
environment: TEnvironment;
|
environment: TEnvironment;
|
||||||
publicDomain: string;
|
webAppUrl: string;
|
||||||
appSetupCompleted: boolean;
|
widgetSetupCompleted: boolean;
|
||||||
channel: TProjectConfigChannel;
|
channel: TProjectConfigChannel;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ConnectWithFormbricks = ({
|
export const ConnectWithFormbricks = ({
|
||||||
environment,
|
environment,
|
||||||
publicDomain,
|
webAppUrl,
|
||||||
appSetupCompleted,
|
widgetSetupCompleted,
|
||||||
channel,
|
channel,
|
||||||
}: ConnectWithFormbricksProps) => {
|
}: ConnectWithFormbricksProps) => {
|
||||||
const { t } = useTranslate();
|
const { t } = useTranslate();
|
||||||
@@ -49,17 +49,17 @@ export const ConnectWithFormbricks = ({
|
|||||||
<div className="flex w-1/2 flex-col space-y-4">
|
<div className="flex w-1/2 flex-col space-y-4">
|
||||||
<OnboardingSetupInstructions
|
<OnboardingSetupInstructions
|
||||||
environmentId={environment.id}
|
environmentId={environment.id}
|
||||||
publicDomain={publicDomain}
|
webAppUrl={webAppUrl}
|
||||||
channel={channel}
|
channel={channel}
|
||||||
appSetupCompleted={appSetupCompleted}
|
widgetSetupCompleted={widgetSetupCompleted}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex h-[30rem] w-1/2 flex-col items-center justify-center rounded-lg border text-center",
|
"flex h-[30rem] w-1/2 flex-col items-center justify-center rounded-lg border text-center",
|
||||||
appSetupCompleted ? "border-green-500 bg-green-100" : "border-slate-300 bg-slate-200"
|
widgetSetupCompleted ? "border-green-500 bg-green-100" : "border-slate-300 bg-slate-200"
|
||||||
)}>
|
)}>
|
||||||
{appSetupCompleted ? (
|
{widgetSetupCompleted ? (
|
||||||
<div>
|
<div>
|
||||||
<p className="text-3xl">{t("environments.connect.congrats")}</p>
|
<p className="text-3xl">{t("environments.connect.congrats")}</p>
|
||||||
<p className="pt-4 text-sm font-medium text-slate-600">
|
<p className="pt-4 text-sm font-medium text-slate-600">
|
||||||
@@ -81,9 +81,9 @@ export const ConnectWithFormbricks = ({
|
|||||||
</div>
|
</div>
|
||||||
<Button
|
<Button
|
||||||
id="finishOnboarding"
|
id="finishOnboarding"
|
||||||
variant={appSetupCompleted ? "default" : "ghost"}
|
variant={widgetSetupCompleted ? "default" : "ghost"}
|
||||||
onClick={handleFinishOnboarding}>
|
onClick={handleFinishOnboarding}>
|
||||||
{appSetupCompleted
|
{widgetSetupCompleted
|
||||||
? t("environments.connect.finish_onboarding")
|
? t("environments.connect.finish_onboarding")
|
||||||
: t("environments.connect.do_it_later")}
|
: t("environments.connect.do_it_later")}
|
||||||
<ArrowRight />
|
<ArrowRight />
|
||||||
|
|||||||
@@ -33,9 +33,9 @@ describe("OnboardingSetupInstructions", () => {
|
|||||||
// Provide some default props for testing
|
// Provide some default props for testing
|
||||||
const defaultProps = {
|
const defaultProps = {
|
||||||
environmentId: "env-123",
|
environmentId: "env-123",
|
||||||
publicDomain: "https://example.com",
|
webAppUrl: "https://example.com",
|
||||||
channel: "app" as const, // Assuming channel is either "app" or "website"
|
channel: "app" as const, // Assuming channel is either "app" or "website"
|
||||||
appSetupCompleted: false,
|
widgetSetupCompleted: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
test("renders HTML tab content by default", () => {
|
test("renders HTML tab content by default", () => {
|
||||||
|
|||||||
@@ -18,23 +18,23 @@ const tabs = [
|
|||||||
|
|
||||||
interface OnboardingSetupInstructionsProps {
|
interface OnboardingSetupInstructionsProps {
|
||||||
environmentId: string;
|
environmentId: string;
|
||||||
publicDomain: string;
|
webAppUrl: string;
|
||||||
channel: TProjectConfigChannel;
|
channel: TProjectConfigChannel;
|
||||||
appSetupCompleted: boolean;
|
widgetSetupCompleted: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const OnboardingSetupInstructions = ({
|
export const OnboardingSetupInstructions = ({
|
||||||
environmentId,
|
environmentId,
|
||||||
publicDomain,
|
webAppUrl,
|
||||||
channel,
|
channel,
|
||||||
appSetupCompleted,
|
widgetSetupCompleted,
|
||||||
}: OnboardingSetupInstructionsProps) => {
|
}: OnboardingSetupInstructionsProps) => {
|
||||||
const { t } = useTranslate();
|
const { t } = useTranslate();
|
||||||
const [activeTab, setActiveTab] = useState(tabs[0].id);
|
const [activeTab, setActiveTab] = useState(tabs[0].id);
|
||||||
const htmlSnippetForAppSurveys = `<!-- START Formbricks Surveys -->
|
const htmlSnippetForAppSurveys = `<!-- START Formbricks Surveys -->
|
||||||
<script type="text/javascript">
|
<script type="text/javascript">
|
||||||
!function(){
|
!function(){
|
||||||
var appUrl = "${publicDomain}";
|
var appUrl = "${webAppUrl}";
|
||||||
var environmentId = "${environmentId}";
|
var environmentId = "${environmentId}";
|
||||||
var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.src=appUrl+"/js/formbricks.umd.cjs",t.onload=function(){window.formbricks?window.formbricks.setup({environmentId:environmentId,appUrl:appUrl}):console.error("Formbricks library failed to load properly. The formbricks object is not available.");};var e=document.getElementsByTagName("script")[0];e.parentNode.insertBefore(t,e)}();
|
var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.src=appUrl+"/js/formbricks.umd.cjs",t.onload=function(){window.formbricks?window.formbricks.setup({environmentId:environmentId,appUrl:appUrl}):console.error("Formbricks library failed to load properly. The formbricks object is not available.");};var e=document.getElementsByTagName("script")[0];e.parentNode.insertBefore(t,e)}();
|
||||||
</script>
|
</script>
|
||||||
@@ -44,7 +44,7 @@ export const OnboardingSetupInstructions = ({
|
|||||||
const htmlSnippetForWebsiteSurveys = `<!-- START Formbricks Surveys -->
|
const htmlSnippetForWebsiteSurveys = `<!-- START Formbricks Surveys -->
|
||||||
<script type="text/javascript">
|
<script type="text/javascript">
|
||||||
!function(){
|
!function(){
|
||||||
var appUrl = "${publicDomain}";
|
var appUrl = "${webAppUrl}";
|
||||||
var environmentId = "${environmentId}";
|
var environmentId = "${environmentId}";
|
||||||
var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.src=appUrl+"/js/formbricks.umd.cjs",t.onload=function(){window.formbricks?window.formbricks.setup({environmentId:environmentId,appUrl:appUrl}):console.error("Formbricks library failed to load properly. The formbricks object is not available.");};var e=document.getElementsByTagName("script")[0];e.parentNode.insertBefore(t,e)}();
|
var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.src=appUrl+"/js/formbricks.umd.cjs",t.onload=function(){window.formbricks?window.formbricks.setup({environmentId:environmentId,appUrl:appUrl}):console.error("Formbricks library failed to load properly. The formbricks object is not available.");};var e=document.getElementsByTagName("script")[0];e.parentNode.insertBefore(t,e)}();
|
||||||
</script>
|
</script>
|
||||||
@@ -57,7 +57,7 @@ export const OnboardingSetupInstructions = ({
|
|||||||
if (typeof window !== "undefined") {
|
if (typeof window !== "undefined") {
|
||||||
formbricks.setup({
|
formbricks.setup({
|
||||||
environmentId: "${environmentId}",
|
environmentId: "${environmentId}",
|
||||||
appUrl: "${publicDomain}",
|
appUrl: "${webAppUrl}",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,7 +75,7 @@ export const OnboardingSetupInstructions = ({
|
|||||||
if (typeof window !== "undefined") {
|
if (typeof window !== "undefined") {
|
||||||
formbricks.setup({
|
formbricks.setup({
|
||||||
environmentId: "${environmentId}",
|
environmentId: "${environmentId}",
|
||||||
appUrl: "${publicDomain}",
|
appUrl: "${webAppUrl}",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,7 +137,7 @@ export const OnboardingSetupInstructions = ({
|
|||||||
<div className="mt-4 flex justify-between space-x-2">
|
<div className="mt-4 flex justify-between space-x-2">
|
||||||
<Button
|
<Button
|
||||||
id="onboarding-inapp-connect-copy-code"
|
id="onboarding-inapp-connect-copy-code"
|
||||||
variant={appSetupCompleted ? "secondary" : "default"}
|
variant={widgetSetupCompleted ? "secondary" : "default"}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
navigator.clipboard.writeText(
|
navigator.clipboard.writeText(
|
||||||
channel === "app" ? htmlSnippetForAppSurveys : htmlSnippetForWebsiteSurveys
|
channel === "app" ? htmlSnippetForAppSurveys : htmlSnippetForWebsiteSurveys
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { ConnectWithFormbricks } from "@/app/(app)/(onboarding)/environments/[environmentId]/connect/components/ConnectWithFormbricks";
|
import { ConnectWithFormbricks } from "@/app/(app)/(onboarding)/environments/[environmentId]/connect/components/ConnectWithFormbricks";
|
||||||
|
import { WEBAPP_URL } from "@/lib/constants";
|
||||||
import { getEnvironment } from "@/lib/environment/service";
|
import { getEnvironment } from "@/lib/environment/service";
|
||||||
import { getPublicDomain } from "@/lib/getPublicUrl";
|
|
||||||
import { getProjectByEnvironmentId } from "@/lib/project/service";
|
import { getProjectByEnvironmentId } from "@/lib/project/service";
|
||||||
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";
|
||||||
@@ -30,8 +30,6 @@ const Page = async (props: ConnectPageProps) => {
|
|||||||
|
|
||||||
const channel = project.config.channel || null;
|
const channel = project.config.channel || null;
|
||||||
|
|
||||||
const publicDomain = getPublicDomain();
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-full flex-col items-center justify-center py-10">
|
<div className="flex min-h-full flex-col items-center justify-center py-10">
|
||||||
<Header title={t("environments.connect.headline")} subtitle={t("environments.connect.subtitle")} />
|
<Header title={t("environments.connect.headline")} subtitle={t("environments.connect.subtitle")} />
|
||||||
@@ -41,8 +39,8 @@ const Page = async (props: ConnectPageProps) => {
|
|||||||
</div>
|
</div>
|
||||||
<ConnectWithFormbricks
|
<ConnectWithFormbricks
|
||||||
environment={environment}
|
environment={environment}
|
||||||
publicDomain={publicDomain}
|
webAppUrl={WEBAPP_URL}
|
||||||
appSetupCompleted={environment.appSetupCompleted}
|
widgetSetupCompleted={environment.appSetupCompleted}
|
||||||
channel={channel}
|
channel={channel}
|
||||||
/>
|
/>
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ vi.mock("@/lib/constants", () => ({
|
|||||||
IS_DEVELOPMENT: true,
|
IS_DEVELOPMENT: true,
|
||||||
E2E_TESTING: false,
|
E2E_TESTING: false,
|
||||||
WEBAPP_URL: "http://localhost:3000",
|
WEBAPP_URL: "http://localhost:3000",
|
||||||
PUBLIC_URL: "http://localhost:3000/survey",
|
SURVEY_URL: "http://localhost:3000/survey",
|
||||||
ENCRYPTION_KEY: "mock-encryption-key",
|
ENCRYPTION_KEY: "mock-encryption-key",
|
||||||
CRON_SECRET: "mock-cron-secret",
|
CRON_SECRET: "mock-cron-secret",
|
||||||
DEFAULT_BRAND_COLOR: "#64748b",
|
DEFAULT_BRAND_COLOR: "#64748b",
|
||||||
@@ -86,7 +86,7 @@ vi.mock("@/lib/constants", () => ({
|
|||||||
OIDC_ISSUER: "https://mock-oidc-issuer.com",
|
OIDC_ISSUER: "https://mock-oidc-issuer.com",
|
||||||
OIDC_SIGNING_ALGORITHM: "RS256",
|
OIDC_SIGNING_ALGORITHM: "RS256",
|
||||||
SESSION_MAX_AGE: 1000,
|
SESSION_MAX_AGE: 1000,
|
||||||
REDIS_URL: undefined,
|
REDIS_URL: "test-redis-url",
|
||||||
AUDIT_LOG_ENABLED: true,
|
AUDIT_LOG_ENABLED: true,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
|||||||
@@ -45,11 +45,22 @@ afterEach(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("LandingSidebar component", () => {
|
describe("LandingSidebar component", () => {
|
||||||
const user = { id: "u1", name: "Alice", email: "alice@example.com" } as any;
|
const user = { id: "u1", name: "Alice", email: "alice@example.com", imageUrl: "" } as any;
|
||||||
const organization = { id: "o1", name: "orgOne" } as any;
|
const organization = { id: "o1", name: "orgOne" } as any;
|
||||||
|
const organizations = [
|
||||||
|
{ id: "o2", name: "betaOrg" },
|
||||||
|
{ id: "o1", name: "alphaOrg" },
|
||||||
|
] as any;
|
||||||
|
|
||||||
test("renders logo, avatar, and initial modal closed", () => {
|
test("renders logo, avatar, and initial modal closed", () => {
|
||||||
render(<LandingSidebar user={user} organization={organization} />);
|
render(
|
||||||
|
<LandingSidebar
|
||||||
|
isMultiOrgEnabled={false}
|
||||||
|
user={user}
|
||||||
|
organization={organization}
|
||||||
|
organizations={organizations}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
// Formbricks logo
|
// Formbricks logo
|
||||||
expect(screen.getByAltText("environments.formbricks_logo")).toBeInTheDocument();
|
expect(screen.getByAltText("environments.formbricks_logo")).toBeInTheDocument();
|
||||||
@@ -60,7 +71,14 @@ describe("LandingSidebar component", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("clicking logout triggers signOut", async () => {
|
test("clicking logout triggers signOut", async () => {
|
||||||
render(<LandingSidebar user={user} organization={organization} />);
|
render(
|
||||||
|
<LandingSidebar
|
||||||
|
isMultiOrgEnabled={false}
|
||||||
|
user={user}
|
||||||
|
organization={organization}
|
||||||
|
organizations={organizations}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
// Open user dropdown by clicking on avatar trigger
|
// Open user dropdown by clicking on avatar trigger
|
||||||
const trigger = screen.getByTestId("avatar").parentElement;
|
const trigger = screen.getByTestId("avatar").parentElement;
|
||||||
@@ -76,7 +94,6 @@ describe("LandingSidebar component", () => {
|
|||||||
organizationId: "o1",
|
organizationId: "o1",
|
||||||
redirect: true,
|
redirect: true,
|
||||||
callbackUrl: "/auth/login",
|
callbackUrl: "/auth/login",
|
||||||
clearEnvironmentId: true,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -10,27 +10,48 @@ import {
|
|||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
|
DropdownMenuPortal,
|
||||||
|
DropdownMenuRadioGroup,
|
||||||
|
DropdownMenuRadioItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuSub,
|
||||||
|
DropdownMenuSubContent,
|
||||||
|
DropdownMenuSubTrigger,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "@/modules/ui/components/dropdown-menu";
|
} from "@/modules/ui/components/dropdown-menu";
|
||||||
import { useTranslate } from "@tolgee/react";
|
import { useTranslate } from "@tolgee/react";
|
||||||
import { ArrowUpRightIcon, ChevronRightIcon, LogOutIcon } from "lucide-react";
|
import { ArrowUpRightIcon, ChevronRightIcon, LogOutIcon, PlusIcon } from "lucide-react";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useState } from "react";
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
import { TOrganization } from "@formbricks/types/organizations";
|
import { TOrganization } from "@formbricks/types/organizations";
|
||||||
import { TUser } from "@formbricks/types/user";
|
import { TUser } from "@formbricks/types/user";
|
||||||
|
|
||||||
interface LandingSidebarProps {
|
interface LandingSidebarProps {
|
||||||
|
isMultiOrgEnabled: boolean;
|
||||||
user: TUser;
|
user: TUser;
|
||||||
organization: TOrganization;
|
organization: TOrganization;
|
||||||
|
organizations: TOrganization[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export const LandingSidebar = ({ user, organization }: LandingSidebarProps) => {
|
export const LandingSidebar = ({
|
||||||
|
isMultiOrgEnabled,
|
||||||
|
user,
|
||||||
|
organization,
|
||||||
|
organizations,
|
||||||
|
}: LandingSidebarProps) => {
|
||||||
const [openCreateOrganizationModal, setOpenCreateOrganizationModal] = useState<boolean>(false);
|
const [openCreateOrganizationModal, setOpenCreateOrganizationModal] = useState<boolean>(false);
|
||||||
|
|
||||||
const { t } = useTranslate();
|
const { t } = useTranslate();
|
||||||
const { signOut: signOutWithAudit } = useSignOut({ id: user.id, email: user.email });
|
const { signOut: signOutWithAudit } = useSignOut({ id: user.id, email: user.email });
|
||||||
|
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const handleEnvironmentChangeByOrganization = (organizationId: string) => {
|
||||||
|
router.push(`/organizations/${organizationId}/`);
|
||||||
|
};
|
||||||
|
|
||||||
const dropdownNavigation = [
|
const dropdownNavigation = [
|
||||||
{
|
{
|
||||||
label: t("common.documentation"),
|
label: t("common.documentation"),
|
||||||
@@ -40,6 +61,13 @@ export const LandingSidebar = ({ user, organization }: LandingSidebarProps) => {
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const currentOrganizationId = organization?.id;
|
||||||
|
const currentOrganizationName = capitalizeFirstLetter(organization?.name);
|
||||||
|
|
||||||
|
const sortedOrganizations = useMemo(() => {
|
||||||
|
return [...organizations].sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
}, [organizations]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<aside
|
<aside
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -52,28 +80,27 @@ export const LandingSidebar = ({ user, organization }: LandingSidebarProps) => {
|
|||||||
<DropdownMenuTrigger
|
<DropdownMenuTrigger
|
||||||
asChild
|
asChild
|
||||||
id="userDropdownTrigger"
|
id="userDropdownTrigger"
|
||||||
className="w-full rounded-br-xl border-t p-4 transition-colors duration-200 hover:bg-slate-50 focus:outline-none">
|
className="w-full rounded-br-xl border-t py-4 pl-4 transition-colors duration-200 hover:bg-slate-50 focus:outline-none">
|
||||||
<button
|
<div tabIndex={0} className={cn("flex cursor-pointer flex-row items-center space-x-3")}>
|
||||||
type="button"
|
<ProfileAvatar userId={user.id} imageUrl={user.imageUrl} />
|
||||||
className={cn("flex w-full cursor-pointer flex-row items-center gap-3 text-left")}
|
<>
|
||||||
aria-haspopup="menu">
|
<div>
|
||||||
<ProfileAvatar userId={user.id} />
|
<p
|
||||||
<div className="grow overflow-hidden">
|
title={user?.email}
|
||||||
<p
|
className={cn(
|
||||||
title={user?.email}
|
"ph-no-capture ph-no-capture -mb-0.5 max-w-28 truncate text-sm font-bold text-slate-700"
|
||||||
className={cn(
|
)}>
|
||||||
"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>}
|
||||||
)}>
|
</p>
|
||||||
{user?.name ? <span>{user?.name}</span> : <span>{user?.email}</span>}
|
<p
|
||||||
</p>
|
title={capitalizeFirstLetter(organization?.name)}
|
||||||
<p
|
className="max-w-28 truncate text-sm text-slate-500">
|
||||||
title={capitalizeFirstLetter(organization?.name)}
|
{capitalizeFirstLetter(organization?.name)}
|
||||||
className="truncate text-sm text-slate-500">
|
</p>
|
||||||
{capitalizeFirstLetter(organization?.name)}
|
</div>
|
||||||
</p>
|
<ChevronRightIcon className={cn("h-5 w-5 text-slate-700 hover:text-slate-500")} />
|
||||||
</div>
|
</>
|
||||||
<ChevronRightIcon className={cn("h-5 w-5 shrink-0 text-slate-700 hover:text-slate-500")} />
|
</div>
|
||||||
</button>
|
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
|
|
||||||
<DropdownMenuContent
|
<DropdownMenuContent
|
||||||
@@ -85,13 +112,7 @@ export const LandingSidebar = ({ user, organization }: LandingSidebarProps) => {
|
|||||||
{/* Dropdown Items */}
|
{/* Dropdown Items */}
|
||||||
|
|
||||||
{dropdownNavigation.map((link) => (
|
{dropdownNavigation.map((link) => (
|
||||||
<Link
|
<Link id={link.href} href={link.href} target={link.target} className="flex w-full items-center">
|
||||||
key={link.href}
|
|
||||||
id={link.href}
|
|
||||||
href={link.href}
|
|
||||||
target={link.target}
|
|
||||||
rel={link.target === "_blank" ? "noopener noreferrer" : undefined}
|
|
||||||
className="flex w-full items-center">
|
|
||||||
<DropdownMenuItem>
|
<DropdownMenuItem>
|
||||||
<link.icon className="mr-2 h-4 w-4" strokeWidth={1.5} />
|
<link.icon className="mr-2 h-4 w-4" strokeWidth={1.5} />
|
||||||
{link.label}
|
{link.label}
|
||||||
@@ -100,6 +121,7 @@ export const LandingSidebar = ({ user, organization }: LandingSidebarProps) => {
|
|||||||
))}
|
))}
|
||||||
|
|
||||||
{/* Logout */}
|
{/* Logout */}
|
||||||
|
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
await signOutWithAudit({
|
await signOutWithAudit({
|
||||||
@@ -108,12 +130,50 @@ export const LandingSidebar = ({ user, organization }: LandingSidebarProps) => {
|
|||||||
organizationId: organization.id,
|
organizationId: organization.id,
|
||||||
redirect: true,
|
redirect: true,
|
||||||
callbackUrl: "/auth/login",
|
callbackUrl: "/auth/login",
|
||||||
clearEnvironmentId: true,
|
|
||||||
});
|
});
|
||||||
}}
|
}}
|
||||||
icon={<LogOutIcon className="mr-2 h-4 w-4" strokeWidth={1.5} />}>
|
icon={<LogOutIcon className="mr-2 h-4 w-4" strokeWidth={1.5} />}>
|
||||||
{t("common.logout")}
|
{t("common.logout")}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|
||||||
|
{/* Organization Switch */}
|
||||||
|
|
||||||
|
{(isMultiOrgEnabled || organizations.length > 1) && (
|
||||||
|
<DropdownMenuSub>
|
||||||
|
<DropdownMenuSubTrigger className="rounded-lg">
|
||||||
|
<div>
|
||||||
|
<p>{currentOrganizationName}</p>
|
||||||
|
<p className="block text-xs text-slate-500">{t("common.switch_organization")}</p>
|
||||||
|
</div>
|
||||||
|
</DropdownMenuSubTrigger>
|
||||||
|
<DropdownMenuPortal>
|
||||||
|
<DropdownMenuSubContent sideOffset={10} alignOffset={5}>
|
||||||
|
<DropdownMenuRadioGroup
|
||||||
|
value={currentOrganizationId}
|
||||||
|
onValueChange={(organizationId) =>
|
||||||
|
handleEnvironmentChangeByOrganization(organizationId)
|
||||||
|
}>
|
||||||
|
{sortedOrganizations.map((organization) => (
|
||||||
|
<DropdownMenuRadioItem
|
||||||
|
value={organization.id}
|
||||||
|
className="cursor-pointer rounded-lg"
|
||||||
|
key={organization.id}>
|
||||||
|
{organization.name}
|
||||||
|
</DropdownMenuRadioItem>
|
||||||
|
))}
|
||||||
|
</DropdownMenuRadioGroup>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
{isMultiOrgEnabled && (
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() => setOpenCreateOrganizationModal(true)}
|
||||||
|
icon={<PlusIcon className="mr-2 h-4 w-4" />}>
|
||||||
|
<span>{t("common.create_new_organization")}</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
|
</DropdownMenuSubContent>
|
||||||
|
</DropdownMenuPortal>
|
||||||
|
</DropdownMenuSub>
|
||||||
|
)}
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ vi.mock("@/lib/constants", () => ({
|
|||||||
IS_DEVELOPMENT: true,
|
IS_DEVELOPMENT: true,
|
||||||
E2E_TESTING: false,
|
E2E_TESTING: false,
|
||||||
WEBAPP_URL: "http://localhost:3000",
|
WEBAPP_URL: "http://localhost:3000",
|
||||||
PUBLIC_URL: "http://localhost:3000/survey",
|
SURVEY_URL: "http://localhost:3000/survey",
|
||||||
ENCRYPTION_KEY: "mock-encryption-key",
|
ENCRYPTION_KEY: "mock-encryption-key",
|
||||||
CRON_SECRET: "mock-cron-secret",
|
CRON_SECRET: "mock-cron-secret",
|
||||||
DEFAULT_BRAND_COLOR: "#64748b",
|
DEFAULT_BRAND_COLOR: "#64748b",
|
||||||
@@ -89,7 +89,7 @@ vi.mock("@/lib/constants", () => ({
|
|||||||
OIDC_ISSUER: "https://mock-oidc-issuer.com",
|
OIDC_ISSUER: "https://mock-oidc-issuer.com",
|
||||||
OIDC_SIGNING_ALGORITHM: "RS256",
|
OIDC_SIGNING_ALGORITHM: "RS256",
|
||||||
SESSION_MAX_AGE: 1000,
|
SESSION_MAX_AGE: 1000,
|
||||||
REDIS_URL: undefined,
|
REDIS_URL: "test-redis-url",
|
||||||
AUDIT_LOG_ENABLED: true,
|
AUDIT_LOG_ENABLED: true,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { getMembershipByUserIdOrganizationId } from "@/lib/membership/service";
|
|
||||||
import { getOrganizationsByUserId } from "@/lib/organization/service";
|
import { getOrganizationsByUserId } from "@/lib/organization/service";
|
||||||
import { getUser } from "@/lib/user/service";
|
import { getUser } from "@/lib/user/service";
|
||||||
import { getOrganizationAuth } from "@/modules/organization/lib/utils";
|
import { getOrganizationAuth } from "@/modules/organization/lib/utils";
|
||||||
@@ -16,7 +15,6 @@ vi.mock("@/modules/ee/license-check/lib/license", () => ({
|
|||||||
isPendingDowngrade: false,
|
isPendingDowngrade: false,
|
||||||
fallbackLevel: "live",
|
fallbackLevel: "live",
|
||||||
}),
|
}),
|
||||||
getLicenseFeatures: vi.fn().mockResolvedValue({ isMultiOrgEnabled: true }),
|
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("@/lib/constants", () => ({
|
vi.mock("@/lib/constants", () => ({
|
||||||
@@ -25,6 +23,7 @@ vi.mock("@/lib/constants", () => ({
|
|||||||
IS_DEVELOPMENT: true,
|
IS_DEVELOPMENT: true,
|
||||||
E2E_TESTING: false,
|
E2E_TESTING: false,
|
||||||
WEBAPP_URL: "http://localhost:3000",
|
WEBAPP_URL: "http://localhost:3000",
|
||||||
|
SURVEY_URL: "http://localhost:3000/survey",
|
||||||
ENCRYPTION_KEY: "mock-encryption-key",
|
ENCRYPTION_KEY: "mock-encryption-key",
|
||||||
CRON_SECRET: "mock-cron-secret",
|
CRON_SECRET: "mock-cron-secret",
|
||||||
DEFAULT_BRAND_COLOR: "#64748b",
|
DEFAULT_BRAND_COLOR: "#64748b",
|
||||||
@@ -99,36 +98,20 @@ vi.mock("@/lib/constants", () => ({
|
|||||||
OIDC_ISSUER: "https://mock-oidc-issuer.com",
|
OIDC_ISSUER: "https://mock-oidc-issuer.com",
|
||||||
OIDC_SIGNING_ALGORITHM: "RS256",
|
OIDC_SIGNING_ALGORITHM: "RS256",
|
||||||
SESSION_MAX_AGE: 1000,
|
SESSION_MAX_AGE: 1000,
|
||||||
REDIS_URL: undefined,
|
REDIS_URL: "test-redis-url",
|
||||||
AUDIT_LOG_ENABLED: true,
|
AUDIT_LOG_ENABLED: true,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("@/lib/getPublicUrl", () => ({
|
|
||||||
getPublicDomain: vi.fn().mockReturnValue("http://localhost:3000"),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock("@/app/(app)/(onboarding)/organizations/[organizationId]/landing/components/landing-sidebar", () => ({
|
vi.mock("@/app/(app)/(onboarding)/organizations/[organizationId]/landing/components/landing-sidebar", () => ({
|
||||||
LandingSidebar: () => <div data-testid="landing-sidebar" />,
|
LandingSidebar: () => <div data-testid="landing-sidebar" />,
|
||||||
}));
|
}));
|
||||||
vi.mock("@/app/(app)/environments/[environmentId]/components/project-and-org-switch", () => ({
|
|
||||||
ProjectAndOrgSwitch: () => <div data-testid="project-and-org-switch" />,
|
|
||||||
}));
|
|
||||||
vi.mock("@/modules/organization/lib/utils");
|
vi.mock("@/modules/organization/lib/utils");
|
||||||
vi.mock("@/lib/user/service");
|
vi.mock("@/lib/user/service");
|
||||||
vi.mock("@/lib/organization/service");
|
vi.mock("@/lib/organization/service");
|
||||||
vi.mock("@/lib/membership/service");
|
|
||||||
vi.mock("@/tolgee/server");
|
vi.mock("@/tolgee/server");
|
||||||
vi.mock("next/navigation", () => ({
|
vi.mock("next/navigation", () => ({
|
||||||
redirect: vi.fn(() => "REDIRECT_STUB"),
|
redirect: vi.fn(() => "REDIRECT_STUB"),
|
||||||
notFound: vi.fn(() => "NOT_FOUND_STUB"),
|
notFound: vi.fn(() => "NOT_FOUND_STUB"),
|
||||||
usePathname: vi.fn(() => "/organizations/org1"),
|
|
||||||
useRouter: vi.fn(() => ({
|
|
||||||
push: vi.fn(),
|
|
||||||
replace: vi.fn(),
|
|
||||||
back: vi.fn(),
|
|
||||||
forward: vi.fn(),
|
|
||||||
refresh: vi.fn(),
|
|
||||||
})),
|
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// Mock the React cache function
|
// Mock the React cache function
|
||||||
@@ -160,7 +143,6 @@ describe("Page component", () => {
|
|||||||
isPendingDowngrade: false,
|
isPendingDowngrade: false,
|
||||||
fallbackLevel: "live",
|
fallbackLevel: "live",
|
||||||
}),
|
}),
|
||||||
getLicenseFeatures: vi.fn().mockResolvedValue({ isMultiOrgEnabled: true }),
|
|
||||||
}));
|
}));
|
||||||
const { default: Page } = await import("./page");
|
const { default: Page } = await import("./page");
|
||||||
const result = await Page({ params: { organizationId: "org1" } });
|
const result = await Page({ params: { organizationId: "org1" } });
|
||||||
@@ -182,7 +164,6 @@ describe("Page component", () => {
|
|||||||
isPendingDowngrade: false,
|
isPendingDowngrade: false,
|
||||||
fallbackLevel: "live",
|
fallbackLevel: "live",
|
||||||
}),
|
}),
|
||||||
getLicenseFeatures: vi.fn().mockResolvedValue({ isMultiOrgEnabled: true }),
|
|
||||||
}));
|
}));
|
||||||
const { default: Page } = await import("./page");
|
const { default: Page } = await import("./page");
|
||||||
const result = await Page({ params: { organizationId: "org1" } });
|
const result = await Page({ params: { organizationId: "org1" } });
|
||||||
@@ -193,16 +174,10 @@ describe("Page component", () => {
|
|||||||
test("renders header and sidebar for authenticated user", async () => {
|
test("renders header and sidebar for authenticated user", async () => {
|
||||||
vi.mocked(getOrganizationAuth).mockResolvedValue({
|
vi.mocked(getOrganizationAuth).mockResolvedValue({
|
||||||
session: { user: { id: "user1" } },
|
session: { user: { id: "user1" } },
|
||||||
organization: { id: "org1", billing: { plan: "free" } },
|
organization: { id: "org1" },
|
||||||
} as any);
|
} as any);
|
||||||
vi.mocked(getUser).mockResolvedValue({ id: "user1", name: "Test User" } as any);
|
vi.mocked(getUser).mockResolvedValue({ id: "user1", name: "Test User" } as any);
|
||||||
vi.mocked(getOrganizationsByUserId).mockResolvedValue([{ id: "org1", name: "Org One" } as any]);
|
vi.mocked(getOrganizationsByUserId).mockResolvedValue([{ id: "org1", name: "Org One" } as any]);
|
||||||
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue({
|
|
||||||
organizationId: "org1",
|
|
||||||
userId: "user1",
|
|
||||||
accepted: true,
|
|
||||||
role: "member",
|
|
||||||
} as any);
|
|
||||||
vi.mocked(getTranslate).mockResolvedValue((props: any) =>
|
vi.mocked(getTranslate).mockResolvedValue((props: any) =>
|
||||||
typeof props === "string" ? props : props.key || ""
|
typeof props === "string" ? props : props.key || ""
|
||||||
);
|
);
|
||||||
@@ -214,13 +189,11 @@ describe("Page component", () => {
|
|||||||
isPendingDowngrade: false,
|
isPendingDowngrade: false,
|
||||||
fallbackLevel: "live",
|
fallbackLevel: "live",
|
||||||
}),
|
}),
|
||||||
getLicenseFeatures: vi.fn().mockResolvedValue({ isMultiOrgEnabled: true }),
|
|
||||||
}));
|
}));
|
||||||
const { default: Page } = await import("./page");
|
const { default: Page } = await import("./page");
|
||||||
const element = await Page({ params: { organizationId: "org1" } });
|
const element = await Page({ params: { organizationId: "org1" } });
|
||||||
render(element as React.ReactElement);
|
render(element as React.ReactElement);
|
||||||
expect(screen.getByTestId("landing-sidebar")).toBeInTheDocument();
|
expect(screen.getByTestId("landing-sidebar")).toBeInTheDocument();
|
||||||
expect(screen.getByTestId("project-and-org-switch")).toBeInTheDocument();
|
|
||||||
expect(screen.getByText("organizations.landing.no_projects_warning_title")).toBeInTheDocument();
|
expect(screen.getByText("organizations.landing.no_projects_warning_title")).toBeInTheDocument();
|
||||||
expect(screen.getByText("organizations.landing.no_projects_warning_subtitle")).toBeInTheDocument();
|
expect(screen.getByText("organizations.landing.no_projects_warning_subtitle")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,7 @@
|
|||||||
import { LandingSidebar } from "@/app/(app)/(onboarding)/organizations/[organizationId]/landing/components/landing-sidebar";
|
import { LandingSidebar } from "@/app/(app)/(onboarding)/organizations/[organizationId]/landing/components/landing-sidebar";
|
||||||
import { ProjectAndOrgSwitch } from "@/app/(app)/environments/[environmentId]/components/project-and-org-switch";
|
|
||||||
import { IS_FORMBRICKS_CLOUD } from "@/lib/constants";
|
|
||||||
import { getMembershipByUserIdOrganizationId } from "@/lib/membership/service";
|
|
||||||
import { getAccessFlags } from "@/lib/membership/utils";
|
|
||||||
import { getOrganizationsByUserId } from "@/lib/organization/service";
|
import { getOrganizationsByUserId } from "@/lib/organization/service";
|
||||||
import { getUser } from "@/lib/user/service";
|
import { getUser } from "@/lib/user/service";
|
||||||
import { getIsMultiOrgEnabled } from "@/modules/ee/license-check/lib/utils";
|
import { getEnterpriseLicense } from "@/modules/ee/license-check/lib/license";
|
||||||
import { getOrganizationAuth } from "@/modules/organization/lib/utils";
|
import { getOrganizationAuth } from "@/modules/organization/lib/utils";
|
||||||
import { Header } from "@/modules/ui/components/header";
|
import { Header } from "@/modules/ui/components/header";
|
||||||
import { getTranslate } from "@/tolgee/server";
|
import { getTranslate } from "@/tolgee/server";
|
||||||
@@ -26,38 +22,24 @@ const Page = async (props) => {
|
|||||||
|
|
||||||
const organizations = await getOrganizationsByUserId(session.user.id);
|
const organizations = await getOrganizationsByUserId(session.user.id);
|
||||||
|
|
||||||
const isMultiOrgEnabled = await getIsMultiOrgEnabled();
|
const { features } = await getEnterpriseLicense();
|
||||||
|
|
||||||
const membership = await getMembershipByUserIdOrganizationId(session.user.id, organization.id);
|
const isMultiOrgEnabled = features?.isMultiOrgEnabled ?? false;
|
||||||
const { isMember } = getAccessFlags(membership?.role);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-full min-w-full flex-row">
|
<div className="flex min-h-full min-w-full flex-row">
|
||||||
<LandingSidebar user={user} organization={organization} />
|
<LandingSidebar
|
||||||
|
user={user}
|
||||||
|
organization={organization}
|
||||||
|
isMultiOrgEnabled={isMultiOrgEnabled}
|
||||||
|
organizations={organizations}
|
||||||
|
/>
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
<div className="flex h-full flex-col">
|
<div className="flex h-full flex-col items-center justify-center space-y-12">
|
||||||
<div className="p-6">
|
<Header
|
||||||
{/* we only need to render organization breadcrumb on this page, so we pass some default value without actually calculating them to ProjectAndOrgSwitch component */}
|
title={t("organizations.landing.no_projects_warning_title")}
|
||||||
<ProjectAndOrgSwitch
|
subtitle={t("organizations.landing.no_projects_warning_subtitle")}
|
||||||
currentOrganizationId={organization.id}
|
/>
|
||||||
organizations={organizations}
|
|
||||||
projects={[]}
|
|
||||||
isMultiOrgEnabled={isMultiOrgEnabled}
|
|
||||||
organizationProjectsLimit={0}
|
|
||||||
isFormbricksCloud={IS_FORMBRICKS_CLOUD}
|
|
||||||
isLicenseActive={false}
|
|
||||||
isOwnerOrManager={false}
|
|
||||||
isAccessControlAllowed={false}
|
|
||||||
isMember={isMember}
|
|
||||||
environments={[]}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="flex h-full flex-col items-center justify-center space-y-12">
|
|
||||||
<Header
|
|
||||||
title={t("organizations.landing.no_projects_warning_title")}
|
|
||||||
subtitle={t("organizations.landing.no_projects_warning_subtitle")}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ vi.mock("@/lib/constants", () => ({
|
|||||||
WEBAPP_URL: "test-webapp-url",
|
WEBAPP_URL: "test-webapp-url",
|
||||||
IS_PRODUCTION: false,
|
IS_PRODUCTION: false,
|
||||||
SESSION_MAX_AGE: 1000,
|
SESSION_MAX_AGE: 1000,
|
||||||
REDIS_URL: undefined,
|
REDIS_URL: "test-redis-url",
|
||||||
AUDIT_LOG_ENABLED: true,
|
AUDIT_LOG_ENABLED: true,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ vi.mock("@/lib/constants", () => ({
|
|||||||
WEBAPP_URL: "test-webapp-url",
|
WEBAPP_URL: "test-webapp-url",
|
||||||
IS_PRODUCTION: false,
|
IS_PRODUCTION: false,
|
||||||
SESSION_MAX_AGE: 1000,
|
SESSION_MAX_AGE: 1000,
|
||||||
REDIS_URL: undefined,
|
REDIS_URL: "test-redis-url",
|
||||||
AUDIT_LOG_ENABLED: true,
|
AUDIT_LOG_ENABLED: true,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ describe("ProjectSettings component", () => {
|
|||||||
industry: "ind",
|
industry: "ind",
|
||||||
defaultBrandColor: "#fff",
|
defaultBrandColor: "#fff",
|
||||||
organizationTeams: [],
|
organizationTeams: [],
|
||||||
isAccessControlAllowed: false,
|
canDoRoleManagement: 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[];
|
||||||
isAccessControlAllowed: boolean;
|
canDoRoleManagement: boolean;
|
||||||
userProjectsCount: number;
|
userProjectsCount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,7 +53,7 @@ export const ProjectSettings = ({
|
|||||||
industry,
|
industry,
|
||||||
defaultBrandColor,
|
defaultBrandColor,
|
||||||
organizationTeams,
|
organizationTeams,
|
||||||
isAccessControlAllowed = false,
|
canDoRoleManagement = false,
|
||||||
userProjectsCount,
|
userProjectsCount,
|
||||||
}: ProjectSettingsProps) => {
|
}: ProjectSettingsProps) => {
|
||||||
const [createTeamModalOpen, setCreateTeamModalOpen] = useState(false);
|
const [createTeamModalOpen, setCreateTeamModalOpen] = useState(false);
|
||||||
@@ -174,7 +174,7 @@ export const ProjectSettings = ({
|
|||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{isAccessControlAllowed && userProjectsCount > 0 && (
|
{canDoRoleManagement && 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 { getAccessControlPermission } from "@/modules/ee/license-check/lib/utils";
|
import { getRoleManagementPermission } 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", () => ({ getAccessControlPermission: vi.fn() }));
|
vi.mock("@/modules/ee/license-check/lib/utils", () => ({ getRoleManagementPermission: 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(getAccessControlPermission).mockResolvedValueOnce(false as any);
|
vi.mocked(getRoleManagementPermission).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(getAccessControlPermission).mockResolvedValueOnce(true as any);
|
vi.mocked(getRoleManagementPermission).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(getAccessControlPermission).mockResolvedValueOnce(true as any);
|
vi.mocked(getRoleManagementPermission).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 { getAccessControlPermission } from "@/modules/ee/license-check/lib/utils";
|
import { getRoleManagementPermission } 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 isAccessControlAllowed = await getAccessControlPermission(organization.billing.plan);
|
const canDoRoleManagement = await getRoleManagementPermission(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}
|
||||||
isAccessControlAllowed={isAccessControlAllowed}
|
canDoRoleManagement={canDoRoleManagement}
|
||||||
userProjectsCount={projects.length}
|
userProjectsCount={projects.length}
|
||||||
/>
|
/>
|
||||||
{projects.length >= 1 && (
|
{projects.length >= 1 && (
|
||||||
|
|||||||
@@ -18,6 +18,11 @@ vi.mock("@/modules/ui/components/environmentId-base-layout", () => ({
|
|||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
}));
|
}));
|
||||||
|
vi.mock("@/modules/ui/components/dev-environment-banner", () => ({
|
||||||
|
DevEnvironmentBanner: ({ environment }: any) => (
|
||||||
|
<div data-testid="DevEnvironmentBanner">{environment.id}</div>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
// Mocks for dependencies
|
// Mocks for dependencies
|
||||||
vi.mock("@/modules/environments/lib/utils", () => ({
|
vi.mock("@/modules/environments/lib/utils", () => ({
|
||||||
@@ -53,6 +58,7 @@ describe("SurveyEditorEnvironmentLayout", () => {
|
|||||||
render(result);
|
render(result);
|
||||||
|
|
||||||
expect(screen.getByTestId("EnvironmentIdBaseLayout")).toHaveTextContent("env1");
|
expect(screen.getByTestId("EnvironmentIdBaseLayout")).toHaveTextContent("env1");
|
||||||
|
expect(screen.getByTestId("DevEnvironmentBanner")).toHaveTextContent("env1");
|
||||||
expect(screen.getByTestId("child")).toHaveTextContent("Survey Editor Content");
|
expect(screen.getByTestId("child")).toHaveTextContent("Survey Editor Content");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { getEnvironment } from "@/lib/environment/service";
|
import { getEnvironment } from "@/lib/environment/service";
|
||||||
import { environmentIdLayoutChecks } from "@/modules/environments/lib/utils";
|
import { environmentIdLayoutChecks } from "@/modules/environments/lib/utils";
|
||||||
|
import { DevEnvironmentBanner } from "@/modules/ui/components/dev-environment-banner";
|
||||||
import { EnvironmentIdBaseLayout } from "@/modules/ui/components/environmentId-base-layout";
|
import { EnvironmentIdBaseLayout } from "@/modules/ui/components/environmentId-base-layout";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
@@ -31,6 +32,7 @@ const SurveyEditorEnvironmentLayout = async (props) => {
|
|||||||
user={user}
|
user={user}
|
||||||
organization={organization}>
|
organization={organization}>
|
||||||
<div className="flex h-screen flex-col">
|
<div className="flex h-screen flex-col">
|
||||||
|
<DevEnvironmentBanner environment={environment} />
|
||||||
<div className="h-full overflow-y-auto bg-slate-50">{children}</div>
|
<div className="h-full overflow-y-auto bg-slate-50">{children}</div>
|
||||||
</div>
|
</div>
|
||||||
</EnvironmentIdBaseLayout>
|
</EnvironmentIdBaseLayout>
|
||||||
|
|||||||
@@ -27,13 +27,7 @@ vi.mock("@/lib/constants", () => ({
|
|||||||
IS_POSTHOG_CONFIGURED: true,
|
IS_POSTHOG_CONFIGURED: true,
|
||||||
SESSION_MAX_AGE: 1000,
|
SESSION_MAX_AGE: 1000,
|
||||||
AUDIT_LOG_ENABLED: 1,
|
AUDIT_LOG_ENABLED: 1,
|
||||||
REDIS_URL: undefined,
|
REDIS_URL: "redis://localhost:6379",
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock("@/lib/env", () => ({
|
|
||||||
env: {
|
|
||||||
PUBLIC_URL: "https://public-domain.com",
|
|
||||||
},
|
|
||||||
}));
|
}));
|
||||||
|
|
||||||
describe("Contact Page Re-export", () => {
|
describe("Contact Page Re-export", () => {
|
||||||
|
|||||||
@@ -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 isAccessControlAllowed = await getAccessControlPermission(organization.billing.plan);
|
const canDoRoleManagement = await getRoleManagementPermission(organization.billing.plan);
|
||||||
|
|
||||||
if (!isAccessControlAllowed) {
|
if (!canDoRoleManagement) {
|
||||||
throw new OperationNotAllowedError("You do not have permission to manage roles");
|
throw new OperationNotAllowedError("You do not have permission to manage roles");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -71,6 +71,10 @@ 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, {
|
||||||
|
|||||||
@@ -136,8 +136,8 @@ const getLatestStableFbRelease = async (): Promise<string | null> => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
} catch (error) {
|
} catch (err) {
|
||||||
throw new Error("Failed to get latest stable Formbricks release", { cause: error });
|
return null;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { getActiveInactiveSurveysAction } from "@/modules/projects/settings/(setup)/app-connection/actions";
|
|
||||||
import { createActionClassAction } from "@/modules/survey/editor/actions";
|
import { createActionClassAction } from "@/modules/survey/editor/actions";
|
||||||
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";
|
||||||
@@ -6,43 +5,18 @@ import toast from "react-hot-toast";
|
|||||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||||
import { TActionClass } from "@formbricks/types/action-classes";
|
import { TActionClass } from "@formbricks/types/action-classes";
|
||||||
import { TEnvironment } from "@formbricks/types/environment";
|
import { TEnvironment } from "@formbricks/types/environment";
|
||||||
|
import { getActiveInactiveSurveysAction } from "../actions";
|
||||||
import { ActionActivityTab } from "./ActionActivityTab";
|
import { ActionActivityTab } from "./ActionActivityTab";
|
||||||
|
|
||||||
// Mock dependencies
|
// Mock dependencies
|
||||||
vi.mock("@/modules/projects/settings/(setup)/app-connection/utils", () => ({
|
vi.mock("@/app/(app)/environments/[environmentId]/actions/utils", () => ({
|
||||||
ACTION_TYPE_ICON_LOOKUP: {
|
ACTION_TYPE_ICON_LOOKUP: {
|
||||||
noCode: <div>NoCodeIcon</div>,
|
noCode: <div>NoCodeIcon</div>,
|
||||||
|
automatic: <div>AutomaticIcon</div>,
|
||||||
code: <div>CodeIcon</div>,
|
code: <div>CodeIcon</div>,
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("@/lib/constants", () => ({
|
|
||||||
IS_FORMBRICKS_CLOUD: false,
|
|
||||||
POSTHOG_API_KEY: "mock-posthog-api-key",
|
|
||||||
POSTHOG_HOST: "mock-posthog-host",
|
|
||||||
IS_POSTHOG_CONFIGURED: true,
|
|
||||||
ENCRYPTION_KEY: "mock-encryption-key",
|
|
||||||
ENTERPRISE_LICENSE_KEY: "mock-enterprise-license-key",
|
|
||||||
GITHUB_ID: "mock-github-id",
|
|
||||||
GITHUB_SECRET: "test-githubID",
|
|
||||||
GOOGLE_CLIENT_ID: "test-google-client-id",
|
|
||||||
GOOGLE_CLIENT_SECRET: "test-google-client-secret",
|
|
||||||
AZUREAD_CLIENT_ID: "test-azuread-client-id",
|
|
||||||
AZUREAD_CLIENT_SECRET: "test-azure",
|
|
||||||
AZUREAD_TENANT_ID: "test-azuread-tenant-id",
|
|
||||||
OIDC_DISPLAY_NAME: "test-oidc-display-name",
|
|
||||||
OIDC_CLIENT_ID: "test-oidc-client-id",
|
|
||||||
OIDC_ISSUER: "test-oidc-issuer",
|
|
||||||
OIDC_CLIENT_SECRET: "test-oidc-client-secret",
|
|
||||||
OIDC_SIGNING_ALGORITHM: "test-oidc-signing-algorithm",
|
|
||||||
WEBAPP_URL: "test-webapp-url",
|
|
||||||
IS_PRODUCTION: false,
|
|
||||||
SENTRY_DSN: "mock-sentry-dsn",
|
|
||||||
SENTRY_RELEASE: "mock-sentry-release",
|
|
||||||
SENTRY_ENVIRONMENT: "mock-sentry-environment",
|
|
||||||
SESSION_MAX_AGE: 1000,
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock("@/lib/time", () => ({
|
vi.mock("@/lib/time", () => ({
|
||||||
convertDateTimeStringShort: (dateString: string) => `formatted-${dateString}`,
|
convertDateTimeStringShort: (dateString: string) => `formatted-${dateString}`,
|
||||||
}));
|
}));
|
||||||
@@ -79,14 +53,10 @@ vi.mock("@/modules/ui/components/loading-spinner", () => ({
|
|||||||
LoadingSpinner: () => <div>LoadingSpinner</div>,
|
LoadingSpinner: () => <div>LoadingSpinner</div>,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("@/modules/projects/settings/(setup)/app-connection/actions", () => ({
|
vi.mock("../actions", () => ({
|
||||||
getActiveInactiveSurveysAction: vi.fn(),
|
getActiveInactiveSurveysAction: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("react-hot-toast", () => ({
|
|
||||||
default: { success: vi.fn(), error: vi.fn() },
|
|
||||||
}));
|
|
||||||
|
|
||||||
const mockActionClass = {
|
const mockActionClass = {
|
||||||
id: "action1",
|
id: "action1",
|
||||||
createdAt: new Date("2023-01-01T10:00:00Z"),
|
createdAt: new Date("2023-01-01T10:00:00Z"),
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { ACTION_TYPE_ICON_LOOKUP } from "@/app/(app)/environments/[environmentId]/actions/utils";
|
||||||
import { convertDateTimeStringShort } from "@/lib/time";
|
import { convertDateTimeStringShort } from "@/lib/time";
|
||||||
import { getFormattedErrorMessage } from "@/lib/utils/helper";
|
import { getFormattedErrorMessage } from "@/lib/utils/helper";
|
||||||
import { capitalizeFirstLetter } from "@/lib/utils/strings";
|
import { capitalizeFirstLetter } from "@/lib/utils/strings";
|
||||||
import { getActiveInactiveSurveysAction } from "@/modules/projects/settings/(setup)/app-connection/actions";
|
|
||||||
import { ACTION_TYPE_ICON_LOOKUP } from "@/modules/projects/settings/(setup)/app-connection/utils";
|
|
||||||
import { createActionClassAction } from "@/modules/survey/editor/actions";
|
import { createActionClassAction } from "@/modules/survey/editor/actions";
|
||||||
import { Button } from "@/modules/ui/components/button";
|
import { Button } from "@/modules/ui/components/button";
|
||||||
import { ErrorComponent } from "@/modules/ui/components/error-component";
|
import { ErrorComponent } from "@/modules/ui/components/error-component";
|
||||||
@@ -15,6 +14,7 @@ import { useEffect, useMemo, useState } from "react";
|
|||||||
import toast from "react-hot-toast";
|
import toast from "react-hot-toast";
|
||||||
import { TActionClass, TActionClassInput, TActionClassInputCode } from "@formbricks/types/action-classes";
|
import { TActionClass, TActionClassInput, TActionClassInputCode } from "@formbricks/types/action-classes";
|
||||||
import { TEnvironment } from "@formbricks/types/environment";
|
import { TEnvironment } from "@formbricks/types/environment";
|
||||||
|
import { getActiveInactiveSurveysAction } from "../actions";
|
||||||
|
|
||||||
interface ActivityTabProps {
|
interface ActivityTabProps {
|
||||||
actionClass: TActionClass;
|
actionClass: TActionClass;
|
||||||
@@ -24,17 +24,14 @@ export const ActionClassesTable = ({
|
|||||||
otherEnvActionClasses,
|
otherEnvActionClasses,
|
||||||
otherEnvironment,
|
otherEnvironment,
|
||||||
}: ActionClassesTableProps) => {
|
}: ActionClassesTableProps) => {
|
||||||
const [isActionDetailModalOpen, setIsActionDetailModalOpen] = useState(false);
|
const [isActionDetailModalOpen, setActionDetailModalOpen] = useState(false);
|
||||||
|
|
||||||
const [activeActionClass, setActiveActionClass] = useState<TActionClass>();
|
const [activeActionClass, setActiveActionClass] = useState<TActionClass>();
|
||||||
|
|
||||||
const handleOpenActionDetailModalClick = (
|
const handleOpenActionDetailModalClick = (e, actionClass: TActionClass) => {
|
||||||
e: React.MouseEvent<HTMLButtonElement>,
|
|
||||||
actionClass: TActionClass
|
|
||||||
) => {
|
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setActiveActionClass(actionClass);
|
setActiveActionClass(actionClass);
|
||||||
setIsActionDetailModalOpen(true);
|
setActionDetailModalOpen(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -45,7 +42,7 @@ export const ActionClassesTable = ({
|
|||||||
{actionClasses.length > 0 ? (
|
{actionClasses.length > 0 ? (
|
||||||
actionClasses.map((actionClass, index) => (
|
actionClasses.map((actionClass, index) => (
|
||||||
<button
|
<button
|
||||||
onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
|
onClick={(e) => {
|
||||||
handleOpenActionDetailModalClick(e, actionClass);
|
handleOpenActionDetailModalClick(e, actionClass);
|
||||||
}}
|
}}
|
||||||
className="w-full"
|
className="w-full"
|
||||||
@@ -66,7 +63,7 @@ export const ActionClassesTable = ({
|
|||||||
environmentId={environmentId}
|
environmentId={environmentId}
|
||||||
environment={environment}
|
environment={environment}
|
||||||
open={isActionDetailModalOpen}
|
open={isActionDetailModalOpen}
|
||||||
setOpen={setIsActionDetailModalOpen}
|
setOpen={setActionDetailModalOpen}
|
||||||
actionClasses={actionClasses}
|
actionClasses={actionClasses}
|
||||||
actionClass={activeActionClass}
|
actionClass={activeActionClass}
|
||||||
isReadOnly={isReadOnly}
|
isReadOnly={isReadOnly}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
import { ModalWithTabs } from "@/modules/ui/components/modal-with-tabs";
|
||||||
|
import { cleanup, render } from "@testing-library/react";
|
||||||
|
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||||
|
import { TActionClass } from "@formbricks/types/action-classes";
|
||||||
|
import { TEnvironment } from "@formbricks/types/environment";
|
||||||
|
import { ActionActivityTab } from "./ActionActivityTab";
|
||||||
|
import { ActionDetailModal } from "./ActionDetailModal";
|
||||||
|
// Import mocked components
|
||||||
|
import { ActionSettingsTab } from "./ActionSettingsTab";
|
||||||
|
|
||||||
|
// Mock child components
|
||||||
|
vi.mock("@/modules/ui/components/modal-with-tabs", () => ({
|
||||||
|
ModalWithTabs: vi.fn(({ tabs, icon, label, description, open, setOpen }) => (
|
||||||
|
<div data-testid="modal-with-tabs">
|
||||||
|
<span data-testid="modal-label">{label}</span>
|
||||||
|
<span data-testid="modal-description">{description}</span>
|
||||||
|
<span data-testid="modal-open">{open.toString()}</span>
|
||||||
|
<button onClick={() => setOpen(false)}>Close</button>
|
||||||
|
{icon}
|
||||||
|
{tabs.map((tab) => (
|
||||||
|
<div key={tab.title}>
|
||||||
|
<h2>{tab.title}</h2>
|
||||||
|
{tab.children}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("./ActionActivityTab", () => ({
|
||||||
|
ActionActivityTab: vi.fn(() => <div data-testid="action-activity-tab">ActionActivityTab</div>),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("./ActionSettingsTab", () => ({
|
||||||
|
ActionSettingsTab: vi.fn(() => <div data-testid="action-settings-tab">ActionSettingsTab</div>),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mock the utils file to control ACTION_TYPE_ICON_LOOKUP
|
||||||
|
vi.mock("@/app/(app)/environments/[environmentId]/actions/utils", () => ({
|
||||||
|
ACTION_TYPE_ICON_LOOKUP: {
|
||||||
|
code: <div data-testid="code-icon">Code Icon Mock</div>,
|
||||||
|
noCode: <div data-testid="nocode-icon">No Code Icon Mock</div>,
|
||||||
|
// Add other types if needed by other tests or default props
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockEnvironmentId = "test-env-id";
|
||||||
|
const mockSetOpen = vi.fn();
|
||||||
|
|
||||||
|
const mockEnvironment = {
|
||||||
|
id: mockEnvironmentId,
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
type: "production", // Use string literal as TEnvironmentType is not exported
|
||||||
|
appSetupCompleted: false,
|
||||||
|
} as unknown as TEnvironment;
|
||||||
|
|
||||||
|
const mockActionClass: TActionClass = {
|
||||||
|
id: "action-class-1",
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
name: "Test Action",
|
||||||
|
description: "This is a test action",
|
||||||
|
type: "code", // Ensure this matches a key in the mocked ACTION_TYPE_ICON_LOOKUP
|
||||||
|
environmentId: mockEnvironmentId,
|
||||||
|
noCodeConfig: null,
|
||||||
|
key: "test-action-key",
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockActionClasses: TActionClass[] = [mockActionClass];
|
||||||
|
const mockOtherEnvActionClasses: TActionClass[] = [];
|
||||||
|
const mockOtherEnvironment = { ...mockEnvironment, id: "other-env-id", name: "Other Environment" };
|
||||||
|
|
||||||
|
const defaultProps = {
|
||||||
|
environmentId: mockEnvironmentId,
|
||||||
|
environment: mockEnvironment,
|
||||||
|
open: true,
|
||||||
|
setOpen: mockSetOpen,
|
||||||
|
actionClass: mockActionClass,
|
||||||
|
actionClasses: mockActionClasses,
|
||||||
|
isReadOnly: false,
|
||||||
|
otherEnvironment: mockOtherEnvironment,
|
||||||
|
otherEnvActionClasses: mockOtherEnvActionClasses,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("ActionDetailModal", () => {
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
vi.clearAllMocks(); // Clear mocks after each test
|
||||||
|
});
|
||||||
|
|
||||||
|
test("renders ModalWithTabs with correct props", () => {
|
||||||
|
render(<ActionDetailModal {...defaultProps} />);
|
||||||
|
|
||||||
|
const mockedModalWithTabs = vi.mocked(ModalWithTabs);
|
||||||
|
|
||||||
|
expect(mockedModalWithTabs).toHaveBeenCalled();
|
||||||
|
const props = mockedModalWithTabs.mock.calls[0][0];
|
||||||
|
|
||||||
|
// Check basic props
|
||||||
|
expect(props.open).toBe(true);
|
||||||
|
expect(props.setOpen).toBe(mockSetOpen);
|
||||||
|
expect(props.label).toBe(mockActionClass.name);
|
||||||
|
expect(props.description).toBe(mockActionClass.description);
|
||||||
|
|
||||||
|
// Check icon data-testid based on the mock for the default 'code' type
|
||||||
|
expect(props.icon).toBeDefined();
|
||||||
|
if (!props.icon) {
|
||||||
|
throw new Error("Icon prop is not defined");
|
||||||
|
}
|
||||||
|
expect((props.icon as any).props["data-testid"]).toBe("code-icon");
|
||||||
|
|
||||||
|
// Check tabs structure
|
||||||
|
expect(props.tabs).toHaveLength(2);
|
||||||
|
expect(props.tabs[0].title).toBe("common.activity");
|
||||||
|
expect(props.tabs[1].title).toBe("common.settings");
|
||||||
|
|
||||||
|
// Check if the correct mocked components are used as children
|
||||||
|
// Access the mocked functions directly
|
||||||
|
const mockedActionActivityTab = vi.mocked(ActionActivityTab);
|
||||||
|
const mockedActionSettingsTab = vi.mocked(ActionSettingsTab);
|
||||||
|
|
||||||
|
if (!props.tabs[0].children || !props.tabs[1].children) {
|
||||||
|
throw new Error("Tabs children are not defined");
|
||||||
|
}
|
||||||
|
|
||||||
|
expect((props.tabs[0].children as any).type).toBe(mockedActionActivityTab);
|
||||||
|
expect((props.tabs[1].children as any).type).toBe(mockedActionSettingsTab);
|
||||||
|
|
||||||
|
// Check props passed to child components
|
||||||
|
const activityTabProps = (props.tabs[0].children as any).props;
|
||||||
|
expect(activityTabProps.otherEnvActionClasses).toBe(mockOtherEnvActionClasses);
|
||||||
|
expect(activityTabProps.otherEnvironment).toBe(mockOtherEnvironment);
|
||||||
|
expect(activityTabProps.isReadOnly).toBe(false);
|
||||||
|
expect(activityTabProps.environment).toBe(mockEnvironment);
|
||||||
|
expect(activityTabProps.actionClass).toBe(mockActionClass);
|
||||||
|
expect(activityTabProps.environmentId).toBe(mockEnvironmentId);
|
||||||
|
|
||||||
|
const settingsTabProps = (props.tabs[1].children as any).props;
|
||||||
|
expect(settingsTabProps.actionClass).toBe(mockActionClass);
|
||||||
|
expect(settingsTabProps.actionClasses).toBe(mockActionClasses);
|
||||||
|
expect(settingsTabProps.setOpen).toBe(mockSetOpen);
|
||||||
|
expect(settingsTabProps.isReadOnly).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("renders correct icon based on action type", () => {
|
||||||
|
// Test with 'noCode' type
|
||||||
|
const noCodeAction: TActionClass = { ...mockActionClass, type: "noCode" } as TActionClass;
|
||||||
|
render(<ActionDetailModal {...defaultProps} actionClass={noCodeAction} />);
|
||||||
|
|
||||||
|
const mockedModalWithTabs = vi.mocked(ModalWithTabs);
|
||||||
|
const props = mockedModalWithTabs.mock.calls[0][0];
|
||||||
|
|
||||||
|
// Expect the 'nocode-icon' based on the updated mock and action type
|
||||||
|
expect(props.icon).toBeDefined();
|
||||||
|
|
||||||
|
if (!props.icon) {
|
||||||
|
throw new Error("Icon prop is not defined");
|
||||||
|
}
|
||||||
|
|
||||||
|
expect((props.icon as any).props["data-testid"]).toBe("nocode-icon");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("passes isReadOnly prop correctly", () => {
|
||||||
|
render(<ActionDetailModal {...defaultProps} isReadOnly={true} />);
|
||||||
|
// Access the mocked component directly
|
||||||
|
const mockedModalWithTabs = vi.mocked(ModalWithTabs);
|
||||||
|
const props = mockedModalWithTabs.mock.calls[0][0];
|
||||||
|
|
||||||
|
if (!props.tabs[0].children || !props.tabs[1].children) {
|
||||||
|
throw new Error("Tabs children are not defined");
|
||||||
|
}
|
||||||
|
|
||||||
|
const activityTabProps = (props.tabs[0].children as any).props;
|
||||||
|
expect(activityTabProps.isReadOnly).toBe(true);
|
||||||
|
|
||||||
|
const settingsTabProps = (props.tabs[1].children as any).props;
|
||||||
|
expect(settingsTabProps.isReadOnly).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { ACTION_TYPE_ICON_LOOKUP } from "@/modules/projects/settings/(setup)/app-connection/utils";
|
import { ACTION_TYPE_ICON_LOOKUP } from "@/app/(app)/environments/[environmentId]/actions/utils";
|
||||||
import { ModalWithTabs } from "@/modules/ui/components/modal-with-tabs";
|
import { ModalWithTabs } from "@/modules/ui/components/modal-with-tabs";
|
||||||
import { useTranslate } from "@tolgee/react";
|
import { useTranslate } from "@tolgee/react";
|
||||||
import { TActionClass } from "@formbricks/types/action-classes";
|
import { TActionClass } from "@formbricks/types/action-classes";
|
||||||
@@ -59,24 +59,16 @@ export const ActionDetailModal = ({
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const typeDescription = () => {
|
|
||||||
if (actionClass.description) return actionClass.description;
|
|
||||||
else
|
|
||||||
return (
|
|
||||||
(actionClass.type && actionClass.type === "noCode" ? t("common.no_code") : t("common.code")) +
|
|
||||||
" " +
|
|
||||||
t("common.action").toLowerCase()
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ModalWithTabs
|
<>
|
||||||
open={open}
|
<ModalWithTabs
|
||||||
setOpen={setOpen}
|
open={open}
|
||||||
tabs={tabs}
|
setOpen={setOpen}
|
||||||
icon={ACTION_TYPE_ICON_LOOKUP[actionClass.type]}
|
tabs={tabs}
|
||||||
label={actionClass.name}
|
icon={ACTION_TYPE_ICON_LOOKUP[actionClass.type]}
|
||||||
description={typeDescription()}
|
label={actionClass.name}
|
||||||
/>
|
description={actionClass.description || ""}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { ACTION_TYPE_ICON_LOOKUP } from "@/app/(app)/environments/[environmentId]/actions/utils";
|
||||||
|
import { timeSince } from "@/lib/time";
|
||||||
|
import { TActionClass } from "@formbricks/types/action-classes";
|
||||||
|
import { TUserLocale } from "@formbricks/types/user";
|
||||||
|
|
||||||
|
export const ActionClassDataRow = ({
|
||||||
|
actionClass,
|
||||||
|
locale,
|
||||||
|
}: {
|
||||||
|
actionClass: TActionClass;
|
||||||
|
locale: TUserLocale;
|
||||||
|
}) => {
|
||||||
|
return (
|
||||||
|
<div className="m-2 grid h-16 grid-cols-6 content-center rounded-lg transition-colors ease-in-out hover:bg-slate-100">
|
||||||
|
<div className="col-span-4 flex items-center pl-6 text-sm">
|
||||||
|
<div className="flex items-center">
|
||||||
|
<div className="h-5 w-5 flex-shrink-0 text-slate-500">
|
||||||
|
{ACTION_TYPE_ICON_LOOKUP[actionClass.type]}
|
||||||
|
</div>
|
||||||
|
<div className="ml-4 text-left">
|
||||||
|
<div className="font-medium text-slate-900">{actionClass.name}</div>
|
||||||
|
<div className="text-xs text-slate-400">{actionClass.description}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2 my-auto whitespace-nowrap text-center text-sm text-slate-500">
|
||||||
|
{timeSince(actionClass.createdAt.toString(), locale)}
|
||||||
|
</div>
|
||||||
|
<div className="text-center"></div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -6,28 +6,13 @@ import { TActionClass, TActionClassNoCodeConfig, TActionClassType } from "@formb
|
|||||||
import { ActionSettingsTab } from "./ActionSettingsTab";
|
import { ActionSettingsTab } from "./ActionSettingsTab";
|
||||||
|
|
||||||
// Mock actions
|
// Mock actions
|
||||||
vi.mock("@/modules/projects/settings/(setup)/app-connection/actions", () => ({
|
vi.mock("@/app/(app)/environments/[environmentId]/actions/actions", () => ({
|
||||||
deleteActionClassAction: vi.fn(),
|
deleteActionClassAction: vi.fn(),
|
||||||
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) => ({
|
|
||||||
...data,
|
|
||||||
environmentId,
|
|
||||||
})),
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Mock utils
|
// Mock utils
|
||||||
vi.mock("@/modules/projects/settings/(setup)/app-connection/utils", () => ({
|
vi.mock("@/app/lib/actionClass/actionClass", () => ({
|
||||||
isValidCssSelector: vi.fn((selector) => selector !== "invalid-selector"),
|
isValidCssSelector: vi.fn((selector) => selector !== "invalid-selector"),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -39,7 +24,6 @@ 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}>
|
||||||
@@ -47,7 +31,6 @@ 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 ? (
|
||||||
@@ -60,26 +43,6 @@ 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}>
|
||||||
@@ -93,28 +56,6 @@ vi.mock("lucide-react", () => ({
|
|||||||
TrashIcon: () => <div data-testid="trash-icon">Trash</div>,
|
TrashIcon: () => <div data-testid="trash-icon">Trash</div>,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// Mock react-hot-toast
|
|
||||||
vi.mock("react-hot-toast", () => ({
|
|
||||||
toast: { success: vi.fn(), error: vi.fn() },
|
|
||||||
}));
|
|
||||||
|
|
||||||
// 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[] = [
|
||||||
{
|
{
|
||||||
@@ -147,7 +88,6 @@ const createMockActionClass = (id: string, type: TActionClassType, name: string)
|
|||||||
describe("ActionSettingsTab", () => {
|
describe("ActionSettingsTab", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
mockHandleSubmit.mockImplementation((fn) => fn);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -165,9 +105,13 @@ describe("ActionSettingsTab", () => {
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(screen.getByTestId("action-name-description-fields")).toBeInTheDocument();
|
// Use getByPlaceholderText or getByLabelText now that Input isn't mocked
|
||||||
expect(screen.getByTestId("name-input-actionNameSettingsInput")).toBeInTheDocument();
|
expect(screen.getByPlaceholderText("environments.actions.eg_clicked_download")).toHaveValue(
|
||||||
expect(screen.getByTestId("description-input-actionDescriptionSettingsInput")).toBeInTheDocument();
|
actionClass.name
|
||||||
|
);
|
||||||
|
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")
|
||||||
@@ -187,108 +131,22 @@ describe("ActionSettingsTab", () => {
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(screen.getByTestId("action-name-description-fields")).toBeInTheDocument();
|
// Use getByPlaceholderText or getByLabelText now that Input isn't mocked
|
||||||
|
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(
|
|
||||||
"@/modules/projects/settings/(setup)/app-connection/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(
|
||||||
"@/modules/projects/settings/(setup)/app-connection/actions"
|
"@/app/(app)/environments/[environmentId]/actions/actions"
|
||||||
);
|
);
|
||||||
vi.mocked(deleteActionClassAction).mockResolvedValue({ data: actionClass } as any);
|
vi.mocked(deleteActionClassAction).mockResolvedValue({ data: actionClass } as any);
|
||||||
|
|
||||||
@@ -319,7 +177,7 @@ describe("ActionSettingsTab", () => {
|
|||||||
test("handles deletion failure", async () => {
|
test("handles deletion failure", 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(
|
||||||
"@/modules/projects/settings/(setup)/app-connection/actions"
|
"@/app/(app)/environments/[environmentId]/actions/actions"
|
||||||
);
|
);
|
||||||
vi.mocked(deleteActionClassAction).mockRejectedValue(new Error("Deletion failed"));
|
vi.mocked(deleteActionClassAction).mockRejectedValue(new Error("Deletion failed"));
|
||||||
|
|
||||||
@@ -351,24 +209,26 @@ describe("ActionSettingsTab", () => {
|
|||||||
actionClass={actionClass}
|
actionClass={actionClass}
|
||||||
actionClasses={mockActionClasses}
|
actionClasses={mockActionClasses}
|
||||||
setOpen={mockSetOpen}
|
setOpen={mockSetOpen}
|
||||||
isReadOnly={true}
|
isReadOnly={true} // Set to read-only
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(screen.getByTestId("name-input-actionNameSettingsInput")).toBeDisabled();
|
// Use getByPlaceholderText or getByLabelText now that Input isn't mocked
|
||||||
expect(screen.getByTestId("description-input-actionDescriptionSettingsInput")).toBeDisabled();
|
expect(screen.getByPlaceholderText("environments.actions.eg_clicked_download")).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();
|
expect(screen.getByRole("link", { name: "common.read_docs" })).toBeInTheDocument(); // Docs link still visible
|
||||||
});
|
});
|
||||||
|
|
||||||
test("prevents delete when read-only", async () => {
|
test("prevents delete when read-only", 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(
|
||||||
"@/modules/projects/settings/(setup)/app-connection/actions"
|
"@/app/(app)/environments/[environmentId]/actions/actions"
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Render with isReadOnly=true, but simulate a delete attempt
|
||||||
render(
|
render(
|
||||||
<ActionSettingsTab
|
<ActionSettingsTab
|
||||||
actionClass={actionClass}
|
actionClass={actionClass}
|
||||||
@@ -378,6 +238,12 @@ 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();
|
||||||
});
|
});
|
||||||
@@ -396,19 +262,4 @@ 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();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
deleteActionClassAction,
|
||||||
|
updateActionClassAction,
|
||||||
|
} from "@/app/(app)/environments/[environmentId]/actions/actions";
|
||||||
|
import { isValidCssSelector } from "@/app/lib/actionClass/actionClass";
|
||||||
|
import { Button } from "@/modules/ui/components/button";
|
||||||
|
import { CodeActionForm } from "@/modules/ui/components/code-action-form";
|
||||||
|
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 { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { useTranslate } from "@tolgee/react";
|
||||||
|
import { TrashIcon } from "lucide-react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import { FormProvider, useForm } from "react-hook-form";
|
||||||
|
import { toast } from "react-hot-toast";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { TActionClass, TActionClassInput, ZActionClassInput } from "@formbricks/types/action-classes";
|
||||||
|
|
||||||
|
interface ActionSettingsTabProps {
|
||||||
|
actionClass: TActionClass;
|
||||||
|
actionClasses: TActionClass[];
|
||||||
|
setOpen: (v: boolean) => void;
|
||||||
|
isReadOnly: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ActionSettingsTab = ({
|
||||||
|
actionClass,
|
||||||
|
actionClasses,
|
||||||
|
setOpen,
|
||||||
|
isReadOnly,
|
||||||
|
}: ActionSettingsTabProps) => {
|
||||||
|
const { createdAt, updatedAt, id, ...restActionClass } = actionClass;
|
||||||
|
const router = useRouter();
|
||||||
|
const [openDeleteDialog, setOpenDeleteDialog] = useState(false);
|
||||||
|
const { t } = useTranslate();
|
||||||
|
const [isUpdatingAction, setIsUpdatingAction] = useState(false);
|
||||||
|
const [isDeletingAction, setIsDeletingAction] = useState(false);
|
||||||
|
|
||||||
|
const actionClassNames = useMemo(
|
||||||
|
() =>
|
||||||
|
actionClasses.filter((action) => action.id !== actionClass.id).map((actionClass) => actionClass.name),
|
||||||
|
[actionClass.id, actionClasses]
|
||||||
|
);
|
||||||
|
|
||||||
|
const form = useForm<TActionClassInput>({
|
||||||
|
defaultValues: {
|
||||||
|
...restActionClass,
|
||||||
|
},
|
||||||
|
resolver: zodResolver(
|
||||||
|
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",
|
||||||
|
});
|
||||||
|
|
||||||
|
const { handleSubmit, control } = form;
|
||||||
|
|
||||||
|
const onSubmit = async (data: TActionClassInput) => {
|
||||||
|
try {
|
||||||
|
if (isReadOnly) {
|
||||||
|
throw new Error(t("common.you_are_not_authorised_to_perform_this_action"));
|
||||||
|
}
|
||||||
|
setIsUpdatingAction(true);
|
||||||
|
|
||||||
|
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({
|
||||||
|
actionClassId: actionClass.id,
|
||||||
|
updatedAction: updatedData,
|
||||||
|
});
|
||||||
|
setOpen(false);
|
||||||
|
router.refresh();
|
||||||
|
toast.success(t("environments.actions.action_updated_successfully"));
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(error.message);
|
||||||
|
} finally {
|
||||||
|
setIsUpdatingAction(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeleteAction = async () => {
|
||||||
|
try {
|
||||||
|
setIsDeletingAction(true);
|
||||||
|
await deleteActionClassAction({ actionClassId: actionClass.id });
|
||||||
|
router.refresh();
|
||||||
|
toast.success(t("environments.actions.action_deleted_successfully"));
|
||||||
|
setOpen(false);
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(t("common.something_went_wrong_please_try_again"));
|
||||||
|
} finally {
|
||||||
|
setIsDeletingAction(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<FormProvider {...form}>
|
||||||
|
<form onSubmit={handleSubmit(onSubmit)}>
|
||||||
|
<div className="max-h-[400px] w-full space-y-4 overflow-y-auto">
|
||||||
|
<div className="grid w-full grid-cols-2 gap-x-4">
|
||||||
|
<div className="col-span-1">
|
||||||
|
<FormField
|
||||||
|
control={control}
|
||||||
|
name="name"
|
||||||
|
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>
|
||||||
|
<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 className="flex justify-between border-t border-slate-200 py-6">
|
||||||
|
<div>
|
||||||
|
{!isReadOnly ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="destructive"
|
||||||
|
onClick={() => setOpenDeleteDialog(true)}
|
||||||
|
className="mr-3"
|
||||||
|
id="deleteActionModalTrigger">
|
||||||
|
<TrashIcon />
|
||||||
|
{t("common.delete")}
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<Button variant="secondary" asChild>
|
||||||
|
<Link href="https://formbricks.com/docs/actions/no-code" target="_blank">
|
||||||
|
{t("common.read_docs")}
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!isReadOnly ? (
|
||||||
|
<div className="flex space-x-2">
|
||||||
|
<Button type="submit" loading={isUpdatingAction}>
|
||||||
|
{t("common.save_changes")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</FormProvider>
|
||||||
|
|
||||||
|
<DeleteDialog
|
||||||
|
open={openDeleteDialog}
|
||||||
|
setOpen={setOpenDeleteDialog}
|
||||||
|
isDeleting={isDeletingAction}
|
||||||
|
deleteWhat={t("common.action")}
|
||||||
|
text={t("environments.actions.delete_action_text")}
|
||||||
|
onDelete={handleDeleteAction}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { getTranslate } from "@/tolgee/server";
|
||||||
|
|
||||||
|
export const ActionTableHeading = async () => {
|
||||||
|
const t = await getTranslate();
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="grid h-12 grid-cols-6 content-center border-b border-slate-200 text-left text-sm font-semibold text-slate-900">
|
||||||
|
<span className="sr-only">{t("common.edit")}</span>
|
||||||
|
<div className="col-span-4 pl-6">{t("environments.actions.user_actions")}</div>
|
||||||
|
<div className="col-span-2 text-center">{t("common.created")}</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
import { cleanup, render, screen } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||||
|
import { TActionClass, TActionClassNoCodeConfig } from "@formbricks/types/action-classes";
|
||||||
|
import { AddActionModal } from "./AddActionModal";
|
||||||
|
|
||||||
|
// Mock child components and hooks
|
||||||
|
vi.mock("@/modules/survey/editor/components/create-new-action-tab", () => ({
|
||||||
|
CreateNewActionTab: vi.fn(({ setOpen }) => (
|
||||||
|
<div data-testid="create-new-action-tab">
|
||||||
|
<span>CreateNewActionTab Content</span>
|
||||||
|
<button onClick={() => setOpen(false)}>Close from Tab</button>
|
||||||
|
</div>
|
||||||
|
)),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/modules/ui/components/button", () => ({
|
||||||
|
Button: ({ children, onClick, ...props }: any) => (
|
||||||
|
<button onClick={onClick} {...props}>
|
||||||
|
{children}
|
||||||
|
</button>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/modules/ui/components/modal", () => ({
|
||||||
|
Modal: ({ children, open, setOpen, ...props }: any) =>
|
||||||
|
open ? (
|
||||||
|
<div data-testid="modal" {...props}>
|
||||||
|
{children}
|
||||||
|
<button onClick={() => setOpen(false)}>Close Modal</button>
|
||||||
|
</div>
|
||||||
|
) : null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@tolgee/react", () => ({
|
||||||
|
useTranslate: () => ({
|
||||||
|
t: (key: string) => key,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("lucide-react", () => ({
|
||||||
|
MousePointerClickIcon: () => <div data-testid="mouse-pointer-icon" />,
|
||||||
|
PlusIcon: () => <div data-testid="plus-icon" />,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockActionClasses: TActionClass[] = [
|
||||||
|
{
|
||||||
|
id: "action1",
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
name: "Action 1",
|
||||||
|
description: "Description 1",
|
||||||
|
type: "noCode",
|
||||||
|
environmentId: "env1",
|
||||||
|
noCodeConfig: { type: "click" } as unknown as TActionClassNoCodeConfig,
|
||||||
|
} as unknown as TActionClass,
|
||||||
|
];
|
||||||
|
|
||||||
|
const environmentId = "env1";
|
||||||
|
|
||||||
|
describe("AddActionModal", () => {
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("renders the 'Add Action' button initially", () => {
|
||||||
|
render(
|
||||||
|
<AddActionModal environmentId={environmentId} actionClasses={mockActionClasses} isReadOnly={false} />
|
||||||
|
);
|
||||||
|
expect(screen.getByRole("button", { name: "common.add_action" })).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId("plus-icon")).toBeInTheDocument();
|
||||||
|
expect(screen.queryByTestId("modal")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("opens the modal when the 'Add Action' button is clicked", async () => {
|
||||||
|
render(
|
||||||
|
<AddActionModal environmentId={environmentId} actionClasses={mockActionClasses} isReadOnly={false} />
|
||||||
|
);
|
||||||
|
const addButton = screen.getByRole("button", { name: "common.add_action" });
|
||||||
|
await userEvent.click(addButton);
|
||||||
|
|
||||||
|
expect(screen.getByTestId("modal")).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId("mouse-pointer-icon")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("environments.actions.track_new_user_action")).toBeInTheDocument();
|
||||||
|
expect(
|
||||||
|
screen.getByText("environments.actions.track_user_action_to_display_surveys_or_create_user_segment")
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId("create-new-action-tab")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("passes correct props to CreateNewActionTab", async () => {
|
||||||
|
const { CreateNewActionTab } = await import("@/modules/survey/editor/components/create-new-action-tab");
|
||||||
|
const mockedCreateNewActionTab = vi.mocked(CreateNewActionTab);
|
||||||
|
|
||||||
|
render(
|
||||||
|
<AddActionModal environmentId={environmentId} actionClasses={mockActionClasses} isReadOnly={false} />
|
||||||
|
);
|
||||||
|
const addButton = screen.getByRole("button", { name: "common.add_action" });
|
||||||
|
await userEvent.click(addButton);
|
||||||
|
|
||||||
|
expect(mockedCreateNewActionTab).toHaveBeenCalled();
|
||||||
|
const props = mockedCreateNewActionTab.mock.calls[0][0];
|
||||||
|
expect(props.environmentId).toBe(environmentId);
|
||||||
|
expect(props.actionClasses).toEqual(mockActionClasses); // Initial state check
|
||||||
|
expect(props.isReadOnly).toBe(false);
|
||||||
|
expect(props.setOpen).toBeInstanceOf(Function);
|
||||||
|
expect(props.setActionClasses).toBeInstanceOf(Function);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("closes the modal when the close button (simulated) is clicked", async () => {
|
||||||
|
render(
|
||||||
|
<AddActionModal environmentId={environmentId} actionClasses={mockActionClasses} isReadOnly={false} />
|
||||||
|
);
|
||||||
|
const addButton = screen.getByRole("button", { name: "common.add_action" });
|
||||||
|
await userEvent.click(addButton);
|
||||||
|
|
||||||
|
expect(screen.getByTestId("modal")).toBeInTheDocument();
|
||||||
|
|
||||||
|
// Simulate closing via the mocked Modal's close button
|
||||||
|
const closeModalButton = screen.getByText("Close Modal");
|
||||||
|
await userEvent.click(closeModalButton);
|
||||||
|
|
||||||
|
expect(screen.queryByTestId("modal")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("closes the modal when setOpen is called from CreateNewActionTab", async () => {
|
||||||
|
render(
|
||||||
|
<AddActionModal environmentId={environmentId} actionClasses={mockActionClasses} isReadOnly={false} />
|
||||||
|
);
|
||||||
|
const addButton = screen.getByRole("button", { name: "common.add_action" });
|
||||||
|
await userEvent.click(addButton);
|
||||||
|
|
||||||
|
expect(screen.getByTestId("modal")).toBeInTheDocument();
|
||||||
|
|
||||||
|
// Simulate closing via the mocked CreateNewActionTab's button
|
||||||
|
const closeFromTabButton = screen.getByText("Close from Tab");
|
||||||
|
await userEvent.click(closeFromTabButton);
|
||||||
|
|
||||||
|
expect(screen.queryByTestId("modal")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { CreateNewActionTab } from "@/modules/survey/editor/components/create-new-action-tab";
|
||||||
|
import { Button } from "@/modules/ui/components/button";
|
||||||
|
import { Modal } from "@/modules/ui/components/modal";
|
||||||
|
import { useTranslate } from "@tolgee/react";
|
||||||
|
import { MousePointerClickIcon, PlusIcon } from "lucide-react";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { TActionClass } from "@formbricks/types/action-classes";
|
||||||
|
|
||||||
|
interface AddActionModalProps {
|
||||||
|
environmentId: string;
|
||||||
|
actionClasses: TActionClass[];
|
||||||
|
isReadOnly: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AddActionModal = ({ environmentId, actionClasses, isReadOnly }: AddActionModalProps) => {
|
||||||
|
const { t } = useTranslate();
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
|
const [newActionClasses, setNewActionClasses] = useState<TActionClass[]>(actionClasses);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Button size="sm" onClick={() => setOpen(true)}>
|
||||||
|
{t("common.add_action")}
|
||||||
|
<PlusIcon />
|
||||||
|
</Button>
|
||||||
|
<Modal open={open} setOpen={setOpen} noPadding closeOnOutsideClick={false} restrictOverflow>
|
||||||
|
<div className="flex h-full flex-col rounded-lg">
|
||||||
|
<div className="rounded-t-lg bg-slate-100">
|
||||||
|
<div className="flex w-full items-center justify-between p-6">
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<div className="mr-1.5 h-6 w-6 text-slate-500">
|
||||||
|
<MousePointerClickIcon className="h-5 w-5" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-xl font-medium text-slate-700">
|
||||||
|
{t("environments.actions.track_new_user_action")}
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-slate-500">
|
||||||
|
{t("environments.actions.track_user_action_to_display_surveys_or_create_user_segment")}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="px-6 py-4">
|
||||||
|
<CreateNewActionTab
|
||||||
|
actionClasses={newActionClasses}
|
||||||
|
environmentId={environmentId}
|
||||||
|
isReadOnly={isReadOnly}
|
||||||
|
setActionClasses={setNewActionClasses}
|
||||||
|
setOpen={setOpen}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { cleanup, render, screen } from "@testing-library/react";
|
||||||
|
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||||
|
import Loading from "./loading";
|
||||||
|
|
||||||
|
// Mock child components
|
||||||
|
vi.mock("@/modules/ui/components/page-content-wrapper", () => ({
|
||||||
|
PageContentWrapper: ({ children }: { children: React.ReactNode }) => (
|
||||||
|
<div data-testid="page-content-wrapper">{children}</div>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/modules/ui/components/page-header", () => ({
|
||||||
|
PageHeader: ({ pageTitle }: { pageTitle: string }) => <div data-testid="page-header">{pageTitle}</div>,
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe("Loading", () => {
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("renders loading state correctly", () => {
|
||||||
|
render(<Loading />);
|
||||||
|
|
||||||
|
// Check if mocked components are rendered
|
||||||
|
expect(screen.getByTestId("page-content-wrapper")).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId("page-header")).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId("page-header")).toHaveTextContent("common.actions");
|
||||||
|
|
||||||
|
// Check for translated table headers
|
||||||
|
expect(screen.getByText("environments.actions.user_actions")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("common.created")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("common.edit")).toBeInTheDocument(); // Screen reader text
|
||||||
|
|
||||||
|
// Check for skeleton elements (presence of animate-pulse class)
|
||||||
|
const skeletonElements = document.querySelectorAll(".animate-pulse");
|
||||||
|
expect(skeletonElements.length).toBeGreaterThan(0); // Ensure some skeleton elements are rendered
|
||||||
|
|
||||||
|
// Check for the presence of multiple skeleton rows (3 rows * 4 pulse elements per row = 12)
|
||||||
|
const pulseDivs = screen.getAllByText((_, element) => {
|
||||||
|
return element?.tagName.toLowerCase() === "div" && element.classList.contains("animate-pulse");
|
||||||
|
});
|
||||||
|
expect(pulseDivs.length).toBe(3 * 4); // 3 rows, 4 pulsing divs per row (icon, name, desc, created)
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
|
||||||
|
import { PageHeader } from "@/modules/ui/components/page-header";
|
||||||
|
import { useTranslate } from "@tolgee/react";
|
||||||
|
|
||||||
|
const Loading = () => {
|
||||||
|
const { t } = useTranslate();
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageContentWrapper>
|
||||||
|
<PageHeader pageTitle={t("common.actions")} />
|
||||||
|
<div className="rounded-xl border border-slate-200 bg-white shadow-sm">
|
||||||
|
<div className="grid h-12 grid-cols-6 content-center border-b border-slate-200 text-left text-sm font-semibold text-slate-900">
|
||||||
|
<span className="sr-only">{t("common.edit")}</span>
|
||||||
|
<div className="col-span-4 pl-6">{t("environments.actions.user_actions")}</div>
|
||||||
|
<div className="col-span-2 text-center">{t("common.created")}</div>
|
||||||
|
</div>
|
||||||
|
{[...Array(3)].map((_, index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="m-2 grid h-16 grid-cols-6 content-center rounded-lg transition-colors ease-in-out hover:bg-slate-100">
|
||||||
|
<div className="col-span-4 flex items-center pl-6 text-sm">
|
||||||
|
<div className="flex items-center">
|
||||||
|
<div className="h-6 w-6 flex-shrink-0 animate-pulse rounded-full bg-slate-200 text-slate-500" />
|
||||||
|
<div className="ml-4 text-left">
|
||||||
|
<div className="font-medium text-slate-900">
|
||||||
|
<div className="mt-0 h-4 w-48 animate-pulse rounded-full bg-slate-200"></div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 text-xs text-slate-400">
|
||||||
|
<div className="h-2 w-24 animate-pulse rounded-full bg-slate-200"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2 my-auto flex justify-center whitespace-nowrap text-center text-sm text-slate-500">
|
||||||
|
<div className="h-4 w-28 animate-pulse rounded-full bg-slate-200"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</PageContentWrapper>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
export default Loading;
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
import { getActionClasses } from "@/lib/actionClass/service";
|
||||||
|
import { getEnvironments } from "@/lib/environment/service";
|
||||||
|
import { findMatchingLocale } from "@/lib/utils/locale";
|
||||||
|
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
|
||||||
|
import { TEnvironmentAuth } from "@/modules/environments/types/environment-auth";
|
||||||
|
import { cleanup, render, screen } from "@testing-library/react";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||||
|
import { TActionClass } from "@formbricks/types/action-classes";
|
||||||
|
import { TEnvironment } from "@formbricks/types/environment";
|
||||||
|
import { TProject } from "@formbricks/types/project";
|
||||||
|
// Import the component after mocks
|
||||||
|
import Page from "./page";
|
||||||
|
|
||||||
|
// Mock dependencies
|
||||||
|
vi.mock("@/lib/actionClass/service", () => ({
|
||||||
|
getActionClasses: vi.fn(),
|
||||||
|
}));
|
||||||
|
vi.mock("@/lib/environment/service", () => ({
|
||||||
|
getEnvironments: vi.fn(),
|
||||||
|
}));
|
||||||
|
vi.mock("@/lib/utils/locale", () => ({
|
||||||
|
findMatchingLocale: vi.fn(),
|
||||||
|
}));
|
||||||
|
vi.mock("@/modules/environments/lib/utils", () => ({
|
||||||
|
getEnvironmentAuth: vi.fn(),
|
||||||
|
}));
|
||||||
|
vi.mock("@/tolgee/server", () => ({
|
||||||
|
getTranslate: async () => (key: string) => key,
|
||||||
|
}));
|
||||||
|
vi.mock("next/navigation", () => ({
|
||||||
|
redirect: vi.fn(),
|
||||||
|
}));
|
||||||
|
vi.mock("@/app/(app)/environments/[environmentId]/actions/components/ActionClassesTable", () => ({
|
||||||
|
ActionClassesTable: ({ children }) => <div>ActionClassesTable Mock{children}</div>,
|
||||||
|
}));
|
||||||
|
vi.mock("@/app/(app)/environments/[environmentId]/actions/components/ActionRowData", () => ({
|
||||||
|
ActionClassDataRow: ({ actionClass }) => <div>ActionClassDataRow Mock: {actionClass.name}</div>,
|
||||||
|
}));
|
||||||
|
vi.mock("@/app/(app)/environments/[environmentId]/actions/components/ActionTableHeading", () => ({
|
||||||
|
ActionTableHeading: () => <div>ActionTableHeading Mock</div>,
|
||||||
|
}));
|
||||||
|
vi.mock("@/app/(app)/environments/[environmentId]/actions/components/AddActionModal", () => ({
|
||||||
|
AddActionModal: () => <div>AddActionModal Mock</div>,
|
||||||
|
}));
|
||||||
|
vi.mock("@/modules/ui/components/page-content-wrapper", () => ({
|
||||||
|
PageContentWrapper: ({ children }) => <div>PageContentWrapper Mock{children}</div>,
|
||||||
|
}));
|
||||||
|
vi.mock("@/modules/ui/components/page-header", () => ({
|
||||||
|
PageHeader: ({ pageTitle, cta }) => (
|
||||||
|
<div>
|
||||||
|
PageHeader Mock: {pageTitle} {cta && <div>CTA Mock</div>}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mock data
|
||||||
|
const mockEnvironmentId = "test-env-id";
|
||||||
|
const mockProjectId = "test-project-id";
|
||||||
|
const mockEnvironment = {
|
||||||
|
id: mockEnvironmentId,
|
||||||
|
name: "Test Environment",
|
||||||
|
type: "development",
|
||||||
|
} as unknown as TEnvironment;
|
||||||
|
const mockOtherEnvironment = {
|
||||||
|
id: "other-env-id",
|
||||||
|
name: "Other Environment",
|
||||||
|
type: "production",
|
||||||
|
} as unknown as TEnvironment;
|
||||||
|
const mockProject = { id: mockProjectId, name: "Test Project" } as unknown as TProject;
|
||||||
|
const mockActionClasses = [
|
||||||
|
{ id: "action1", name: "Action 1", type: "code", environmentId: mockEnvironmentId } as TActionClass,
|
||||||
|
{ id: "action2", name: "Action 2", type: "noCode", environmentId: mockEnvironmentId } as TActionClass,
|
||||||
|
];
|
||||||
|
const mockOtherEnvActionClasses = [
|
||||||
|
{ id: "action3", name: "Action 3", type: "code", environmentId: mockOtherEnvironment.id } as TActionClass,
|
||||||
|
];
|
||||||
|
const mockLocale = "en-US";
|
||||||
|
|
||||||
|
const mockParams = { environmentId: mockEnvironmentId };
|
||||||
|
const mockProps = { params: mockParams };
|
||||||
|
|
||||||
|
describe("Actions Page", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.mocked(getActionClasses)
|
||||||
|
.mockResolvedValueOnce(mockActionClasses) // First call for current env
|
||||||
|
.mockResolvedValueOnce(mockOtherEnvActionClasses); // Second call for other env
|
||||||
|
vi.mocked(getEnvironments).mockResolvedValue([mockEnvironment, mockOtherEnvironment]);
|
||||||
|
vi.mocked(findMatchingLocale).mockResolvedValue(mockLocale);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
vi.resetAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("renders the page correctly with actions", async () => {
|
||||||
|
vi.mocked(getEnvironmentAuth).mockResolvedValue({
|
||||||
|
isReadOnly: false,
|
||||||
|
project: mockProject,
|
||||||
|
isBilling: false,
|
||||||
|
environment: mockEnvironment,
|
||||||
|
} as TEnvironmentAuth);
|
||||||
|
|
||||||
|
const PageComponent = await Page(mockProps);
|
||||||
|
render(PageComponent);
|
||||||
|
|
||||||
|
expect(screen.getByText("PageHeader Mock: common.actions")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("CTA Mock")).toBeInTheDocument(); // AddActionModal rendered via CTA
|
||||||
|
expect(screen.getByText("ActionClassesTable Mock")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("ActionTableHeading Mock")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("ActionClassDataRow Mock: Action 1")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("ActionClassDataRow Mock: Action 2")).toBeInTheDocument();
|
||||||
|
expect(vi.mocked(redirect)).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("redirects if isBilling is true", async () => {
|
||||||
|
vi.mocked(getEnvironmentAuth).mockResolvedValue({
|
||||||
|
isReadOnly: false,
|
||||||
|
project: mockProject,
|
||||||
|
isBilling: true,
|
||||||
|
environment: mockEnvironment,
|
||||||
|
} as TEnvironmentAuth);
|
||||||
|
|
||||||
|
await Page(mockProps);
|
||||||
|
|
||||||
|
expect(vi.mocked(redirect)).toHaveBeenCalledWith(`/environments/${mockEnvironmentId}/settings/billing`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not render AddActionModal CTA if isReadOnly is true", async () => {
|
||||||
|
vi.mocked(getEnvironmentAuth).mockResolvedValue({
|
||||||
|
isReadOnly: true,
|
||||||
|
project: mockProject,
|
||||||
|
isBilling: false,
|
||||||
|
environment: mockEnvironment,
|
||||||
|
} as TEnvironmentAuth);
|
||||||
|
|
||||||
|
const PageComponent = await Page(mockProps);
|
||||||
|
render(PageComponent);
|
||||||
|
|
||||||
|
expect(screen.getByText("PageHeader Mock: common.actions")).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText("CTA Mock")).not.toBeInTheDocument(); // CTA should not be present
|
||||||
|
expect(screen.getByText("ActionClassesTable Mock")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("renders AddActionModal CTA if isReadOnly is false", async () => {
|
||||||
|
vi.mocked(getEnvironmentAuth).mockResolvedValue({
|
||||||
|
isReadOnly: false,
|
||||||
|
project: mockProject,
|
||||||
|
isBilling: false,
|
||||||
|
environment: mockEnvironment,
|
||||||
|
} as TEnvironmentAuth);
|
||||||
|
|
||||||
|
const PageComponent = await Page(mockProps);
|
||||||
|
render(PageComponent);
|
||||||
|
|
||||||
|
expect(screen.getByText("PageHeader Mock: common.actions")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("CTA Mock")).toBeInTheDocument(); // CTA should be present
|
||||||
|
expect(screen.getByText("ActionClassesTable Mock")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import { ActionClassesTable } from "@/app/(app)/environments/[environmentId]/actions/components/ActionClassesTable";
|
||||||
|
import { ActionClassDataRow } from "@/app/(app)/environments/[environmentId]/actions/components/ActionRowData";
|
||||||
|
import { ActionTableHeading } from "@/app/(app)/environments/[environmentId]/actions/components/ActionTableHeading";
|
||||||
|
import { AddActionModal } from "@/app/(app)/environments/[environmentId]/actions/components/AddActionModal";
|
||||||
|
import { getActionClasses } from "@/lib/actionClass/service";
|
||||||
|
import { getEnvironments } from "@/lib/environment/service";
|
||||||
|
import { findMatchingLocale } from "@/lib/utils/locale";
|
||||||
|
import { getEnvironmentAuth } from "@/modules/environments/lib/utils";
|
||||||
|
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
|
||||||
|
import { PageHeader } from "@/modules/ui/components/page-header";
|
||||||
|
import { getTranslate } from "@/tolgee/server";
|
||||||
|
import { Metadata } from "next";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: "Actions",
|
||||||
|
};
|
||||||
|
|
||||||
|
const Page = async (props) => {
|
||||||
|
const params = await props.params;
|
||||||
|
|
||||||
|
const { isReadOnly, project, isBilling, environment } = await getEnvironmentAuth(params.environmentId);
|
||||||
|
|
||||||
|
const t = await getTranslate();
|
||||||
|
|
||||||
|
const [actionClasses] = await Promise.all([getActionClasses(params.environmentId)]);
|
||||||
|
|
||||||
|
const locale = await findMatchingLocale();
|
||||||
|
const environments = await getEnvironments(project.id);
|
||||||
|
|
||||||
|
const otherEnvironment = environments.filter((env) => env.id !== params.environmentId)[0];
|
||||||
|
|
||||||
|
const otherEnvActionClasses = await getActionClasses(otherEnvironment.id);
|
||||||
|
|
||||||
|
if (isBilling) {
|
||||||
|
return redirect(`/environments/${params.environmentId}/settings/billing`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const renderAddActionButton = () => (
|
||||||
|
<AddActionModal
|
||||||
|
environmentId={params.environmentId}
|
||||||
|
actionClasses={actionClasses}
|
||||||
|
isReadOnly={isReadOnly}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<PageContentWrapper>
|
||||||
|
<PageHeader pageTitle={t("common.actions")} cta={!isReadOnly ? renderAddActionButton() : undefined} />
|
||||||
|
<ActionClassesTable
|
||||||
|
environment={environment}
|
||||||
|
otherEnvironment={otherEnvironment}
|
||||||
|
otherEnvActionClasses={otherEnvActionClasses}
|
||||||
|
environmentId={params.environmentId}
|
||||||
|
actionClasses={actionClasses}
|
||||||
|
isReadOnly={isReadOnly}>
|
||||||
|
<ActionTableHeading />
|
||||||
|
{actionClasses.map((actionClass) => (
|
||||||
|
<ActionClassDataRow key={actionClass.id} actionClass={actionClass} locale={locale} />
|
||||||
|
))}
|
||||||
|
</ActionClassesTable>
|
||||||
|
</PageContentWrapper>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Page;
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { Code2Icon, MousePointerClickIcon } from "lucide-react";
|
||||||
|
|
||||||
|
export const ACTION_TYPE_ICON_LOOKUP = {
|
||||||
|
code: <Code2Icon className="h-4 w-4" />,
|
||||||
|
noCode: <MousePointerClickIcon className="h-4 w-4" />,
|
||||||
|
};
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
import { getOrganizationsByUserId } from "@/app/(app)/environments/[environmentId]/lib/organization";
|
|
||||||
import { getProjectsByUserId } from "@/app/(app)/environments/[environmentId]/lib/project";
|
|
||||||
import { getEnvironment, getEnvironments } from "@/lib/environment/service";
|
import { getEnvironment, getEnvironments } from "@/lib/environment/service";
|
||||||
import { getMembershipByUserIdOrganizationId } from "@/lib/membership/service";
|
import { getMembershipByUserIdOrganizationId } from "@/lib/membership/service";
|
||||||
import { getAccessFlags } from "@/lib/membership/utils";
|
import { getAccessFlags } from "@/lib/membership/utils";
|
||||||
@@ -7,20 +5,22 @@ import {
|
|||||||
getMonthlyActiveOrganizationPeopleCount,
|
getMonthlyActiveOrganizationPeopleCount,
|
||||||
getMonthlyOrganizationResponseCount,
|
getMonthlyOrganizationResponseCount,
|
||||||
getOrganizationByEnvironmentId,
|
getOrganizationByEnvironmentId,
|
||||||
|
getOrganizationsByUserId,
|
||||||
} from "@/lib/organization/service";
|
} from "@/lib/organization/service";
|
||||||
|
import { getUserProjects } from "@/lib/project/service";
|
||||||
import { getUser } from "@/lib/user/service";
|
import { getUser } from "@/lib/user/service";
|
||||||
import {
|
import { getOrganizationProjectsLimit } from "@/modules/ee/license-check/lib/utils";
|
||||||
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";
|
||||||
import { TEnvironment } from "@formbricks/types/environment";
|
import { TEnvironment } from "@formbricks/types/environment";
|
||||||
import { TMembership } from "@formbricks/types/memberships";
|
import { TMembership } from "@formbricks/types/memberships";
|
||||||
import { TOrganization } from "@formbricks/types/organizations";
|
import {
|
||||||
|
TOrganization,
|
||||||
|
TOrganizationBilling,
|
||||||
|
TOrganizationBillingPlanLimits,
|
||||||
|
} from "@formbricks/types/organizations";
|
||||||
import { TProject } from "@formbricks/types/project";
|
import { TProject } from "@formbricks/types/project";
|
||||||
import { TUser } from "@formbricks/types/user";
|
import { TUser } from "@formbricks/types/user";
|
||||||
|
|
||||||
@@ -31,12 +31,16 @@ vi.mock("@/lib/environment/service", () => ({
|
|||||||
}));
|
}));
|
||||||
vi.mock("@/lib/organization/service", () => ({
|
vi.mock("@/lib/organization/service", () => ({
|
||||||
getOrganizationByEnvironmentId: vi.fn(),
|
getOrganizationByEnvironmentId: vi.fn(),
|
||||||
|
getOrganizationsByUserId: vi.fn(),
|
||||||
getMonthlyActiveOrganizationPeopleCount: vi.fn(),
|
getMonthlyActiveOrganizationPeopleCount: vi.fn(),
|
||||||
getMonthlyOrganizationResponseCount: vi.fn(),
|
getMonthlyOrganizationResponseCount: vi.fn(),
|
||||||
}));
|
}));
|
||||||
vi.mock("@/lib/user/service", () => ({
|
vi.mock("@/lib/user/service", () => ({
|
||||||
getUser: vi.fn(),
|
getUser: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
vi.mock("@/lib/project/service", () => ({
|
||||||
|
getUserProjects: vi.fn(),
|
||||||
|
}));
|
||||||
vi.mock("@/lib/membership/service", () => ({
|
vi.mock("@/lib/membership/service", () => ({
|
||||||
getMembershipByUserIdOrganizationId: vi.fn(),
|
getMembershipByUserIdOrganizationId: vi.fn(),
|
||||||
}));
|
}));
|
||||||
@@ -45,33 +49,13 @@ 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,
|
||||||
}));
|
}));
|
||||||
vi.mock("@/app/(app)/environments/[environmentId]/lib/organization", () => ({
|
|
||||||
getOrganizationsByUserId: vi.fn(),
|
|
||||||
}));
|
|
||||||
vi.mock("@/app/(app)/environments/[environmentId]/lib/project", () => ({
|
|
||||||
getProjectsByUserId: vi.fn(),
|
|
||||||
}));
|
|
||||||
vi.mock("@formbricks/database", () => ({
|
|
||||||
prisma: {
|
|
||||||
project: {
|
|
||||||
findMany: vi.fn(),
|
|
||||||
},
|
|
||||||
organization: {
|
|
||||||
findMany: vi.fn(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
let mockIsFormbricksCloud = false;
|
let mockIsFormbricksCloud = false;
|
||||||
let mockIsDevelopment = false;
|
let mockIsDevelopment = false;
|
||||||
@@ -87,17 +71,15 @@ 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: ({ organizationTeams, isAccessControlAllowed }: any) => (
|
MainNavigation: () => <div data-testid="main-navigation">MainNavigation</div>,
|
||||||
<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>,
|
||||||
}));
|
}));
|
||||||
|
vi.mock("@/modules/ui/components/dev-environment-banner", () => ({
|
||||||
|
DevEnvironmentBanner: ({ environment }: { environment: TEnvironment }) =>
|
||||||
|
environment.type === "development" ? <div data-testid="dev-banner">DevEnvironmentBanner</div> : null,
|
||||||
|
}));
|
||||||
vi.mock("@/modules/ui/components/limits-reached-banner", () => ({
|
vi.mock("@/modules/ui/components/limits-reached-banner", () => ({
|
||||||
LimitsReachedBanner: () => <div data-testid="limits-banner">LimitsReachedBanner</div>,
|
LimitsReachedBanner: () => <div data-testid="limits-banner">LimitsReachedBanner</div>,
|
||||||
}));
|
}));
|
||||||
@@ -117,20 +99,23 @@ const mockUser = {
|
|||||||
name: "Test User",
|
name: "Test User",
|
||||||
email: "test@example.com",
|
email: "test@example.com",
|
||||||
emailVerified: new Date(),
|
emailVerified: new Date(),
|
||||||
|
imageUrl: "",
|
||||||
twoFactorEnabled: false,
|
twoFactorEnabled: false,
|
||||||
identityProvider: "email",
|
identityProvider: "email",
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
notificationSettings: { alert: {} },
|
notificationSettings: { alert: {}, weeklySummary: {} },
|
||||||
} as unknown as TUser;
|
} as unknown as TUser;
|
||||||
|
|
||||||
const mockOrganization = {
|
const mockOrganization = {
|
||||||
id: "org-1",
|
id: "org-1",
|
||||||
name: "Test Org",
|
name: "Test Org",
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
billing: {
|
billing: {
|
||||||
plan: "free",
|
stripeCustomerId: null,
|
||||||
limits: {},
|
limits: { monthly: { responses: null } } as unknown as TOrganizationBillingPlanLimits,
|
||||||
},
|
} as unknown as TOrganizationBilling,
|
||||||
} as unknown as TOrganization;
|
} as unknown as TOrganization;
|
||||||
|
|
||||||
const mockEnvironment: TEnvironment = {
|
const mockEnvironment: TEnvironment = {
|
||||||
@@ -171,17 +156,6 @@ 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",
|
||||||
@@ -193,19 +167,15 @@ describe("EnvironmentLayout", () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.mocked(getUser).mockResolvedValue(mockUser);
|
vi.mocked(getUser).mockResolvedValue(mockUser);
|
||||||
vi.mocked(getEnvironment).mockResolvedValue(mockEnvironment);
|
vi.mocked(getEnvironment).mockResolvedValue(mockEnvironment);
|
||||||
vi.mocked(getOrganizationsByUserId).mockResolvedValue([
|
vi.mocked(getOrganizationsByUserId).mockResolvedValue([mockOrganization]);
|
||||||
{ id: mockOrganization.id, name: mockOrganization.name },
|
|
||||||
]);
|
|
||||||
vi.mocked(getOrganizationByEnvironmentId).mockResolvedValue(mockOrganization);
|
vi.mocked(getOrganizationByEnvironmentId).mockResolvedValue(mockOrganization);
|
||||||
vi.mocked(getProjectsByUserId).mockResolvedValue([{ id: mockProject.id, name: mockProject.name }]);
|
vi.mocked(getUserProjects).mockResolvedValue([mockProject]);
|
||||||
vi.mocked(getEnvironments).mockResolvedValue([mockEnvironment]);
|
vi.mocked(getEnvironments).mockResolvedValue([mockEnvironment]);
|
||||||
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue(mockMembership);
|
vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue(mockMembership);
|
||||||
vi.mocked(getMonthlyActiveOrganizationPeopleCount).mockResolvedValue(100);
|
vi.mocked(getMonthlyActiveOrganizationPeopleCount).mockResolvedValue(100);
|
||||||
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;
|
||||||
});
|
});
|
||||||
@@ -244,6 +214,33 @@ describe("EnvironmentLayout", () => {
|
|||||||
expect(screen.queryByTestId("downgrade-banner")).not.toBeInTheDocument();
|
expect(screen.queryByTestId("downgrade-banner")).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("renders DevEnvironmentBanner in development environment", async () => {
|
||||||
|
const devEnvironment = { ...mockEnvironment, type: "development" as const };
|
||||||
|
vi.mocked(getEnvironment).mockResolvedValue(devEnvironment);
|
||||||
|
mockIsDevelopment = true;
|
||||||
|
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("dev-banner")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
test("renders LimitsReachedBanner in Formbricks Cloud", async () => {
|
test("renders LimitsReachedBanner in Formbricks Cloud", async () => {
|
||||||
mockIsFormbricksCloud = true;
|
mockIsFormbricksCloud = true;
|
||||||
vi.resetModules();
|
vi.resetModules();
|
||||||
@@ -291,84 +288,6 @@ describe("EnvironmentLayout", () => {
|
|||||||
expect(screen.getByTestId("downgrade-banner")).toBeInTheDocument();
|
expect(screen.getByTestId("downgrade-banner")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
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();
|
||||||
@@ -430,7 +349,7 @@ describe("EnvironmentLayout", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("throws error if projects, environments or organizations not found", async () => {
|
test("throws error if projects, environments or organizations not found", async () => {
|
||||||
vi.mocked(getProjectsByUserId).mockResolvedValue(null as any);
|
vi.mocked(getUserProjects).mockResolvedValue(null as any);
|
||||||
vi.resetModules();
|
vi.resetModules();
|
||||||
await vi.doMock("@/modules/ee/license-check/lib/license", () => ({
|
await vi.doMock("@/modules/ee/license-check/lib/license", () => ({
|
||||||
getEnterpriseLicense: vi.fn().mockResolvedValue({
|
getEnterpriseLicense: vi.fn().mockResolvedValue({
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
import { MainNavigation } from "@/app/(app)/environments/[environmentId]/components/MainNavigation";
|
import { MainNavigation } from "@/app/(app)/environments/[environmentId]/components/MainNavigation";
|
||||||
import { TopControlBar } from "@/app/(app)/environments/[environmentId]/components/TopControlBar";
|
import { TopControlBar } from "@/app/(app)/environments/[environmentId]/components/TopControlBar";
|
||||||
import { getOrganizationsByUserId } from "@/app/(app)/environments/[environmentId]/lib/organization";
|
|
||||||
import { getProjectsByUserId } from "@/app/(app)/environments/[environmentId]/lib/project";
|
|
||||||
import { IS_DEVELOPMENT, IS_FORMBRICKS_CLOUD } from "@/lib/constants";
|
import { IS_DEVELOPMENT, IS_FORMBRICKS_CLOUD } from "@/lib/constants";
|
||||||
import { getEnvironment, getEnvironments } from "@/lib/environment/service";
|
import { getEnvironment, getEnvironments } from "@/lib/environment/service";
|
||||||
import { getMembershipByUserIdOrganizationId } from "@/lib/membership/service";
|
import { getMembershipByUserIdOrganizationId } from "@/lib/membership/service";
|
||||||
@@ -10,14 +8,14 @@ import {
|
|||||||
getMonthlyActiveOrganizationPeopleCount,
|
getMonthlyActiveOrganizationPeopleCount,
|
||||||
getMonthlyOrganizationResponseCount,
|
getMonthlyOrganizationResponseCount,
|
||||||
getOrganizationByEnvironmentId,
|
getOrganizationByEnvironmentId,
|
||||||
|
getOrganizationsByUserId,
|
||||||
} from "@/lib/organization/service";
|
} from "@/lib/organization/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 {
|
import { getOrganizationProjectsLimit } from "@/modules/ee/license-check/lib/utils";
|
||||||
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 { LimitsReachedBanner } from "@/modules/ui/components/limits-reached-banner";
|
import { LimitsReachedBanner } from "@/modules/ui/components/limits-reached-banner";
|
||||||
import { PendingDowngradeBanner } from "@/modules/ui/components/pending-downgrade-banner";
|
import { PendingDowngradeBanner } from "@/modules/ui/components/pending-downgrade-banner";
|
||||||
import { getTranslate } from "@/tolgee/server";
|
import { getTranslate } from "@/tolgee/server";
|
||||||
@@ -50,22 +48,17 @@ 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 currentUserMembership = await getMembershipByUserIdOrganizationId(session?.user.id, organization.id);
|
const [projects, environments] = await Promise.all([
|
||||||
if (!currentUserMembership) {
|
getUserProjects(user.id, organization.id),
|
||||||
throw new Error(t("common.membership_not_found"));
|
|
||||||
}
|
|
||||||
const membershipRole = currentUserMembership?.role;
|
|
||||||
|
|
||||||
const [projects, environments, isAccessControlAllowed] = await Promise.all([
|
|
||||||
getProjectsByUserId(user.id, currentUserMembership),
|
|
||||||
getEnvironments(environment.projectId),
|
getEnvironments(environment.projectId),
|
||||||
getAccessControlPermission(organization.billing.plan),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (!projects || !environments || !organizations) {
|
if (!projects || !environments || !organizations) {
|
||||||
throw new Error(t("environments.projects_environments_organizations_not_found"));
|
throw new Error(t("environments.projects_environments_organizations_not_found"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const currentUserMembership = await getMembershipByUserIdOrganizationId(session?.user.id, organization.id);
|
||||||
|
const membershipRole = currentUserMembership?.role;
|
||||||
const { isMember } = getAccessFlags(membershipRole);
|
const { isMember } = getAccessFlags(membershipRole);
|
||||||
|
|
||||||
const { features, lastChecked, isPendingDowngrade, active } = await getEnterpriseLicense();
|
const { features, lastChecked, isPendingDowngrade, active } = await getEnterpriseLicense();
|
||||||
@@ -90,17 +83,10 @@ export const EnvironmentLayout = async ({ environmentId, session, children }: En
|
|||||||
|
|
||||||
const organizationProjectsLimit = await getOrganizationProjectsLimit(organization.billing.limits);
|
const organizationProjectsLimit = await getOrganizationProjectsLimit(organization.billing.limits);
|
||||||
|
|
||||||
// Find the current project from the projects array
|
|
||||||
const project = projects.find((p) => p.id === environment.projectId);
|
|
||||||
if (!project) {
|
|
||||||
throw new Error(t("common.project_not_found"));
|
|
||||||
}
|
|
||||||
|
|
||||||
const { isManager, isOwner } = getAccessFlags(membershipRole);
|
|
||||||
const isOwnerOrManager = isManager || isOwner;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-screen min-h-screen flex-col overflow-hidden">
|
<div className="flex h-screen min-h-screen flex-col overflow-hidden">
|
||||||
|
<DevEnvironmentBanner environment={environment} />
|
||||||
|
|
||||||
{IS_FORMBRICKS_CLOUD && (
|
{IS_FORMBRICKS_CLOUD && (
|
||||||
<LimitsReachedBanner
|
<LimitsReachedBanner
|
||||||
organization={organization}
|
organization={organization}
|
||||||
@@ -115,35 +101,30 @@ export const EnvironmentLayout = async ({ environmentId, session, children }: En
|
|||||||
isPendingDowngrade={isPendingDowngrade ?? false}
|
isPendingDowngrade={isPendingDowngrade ?? false}
|
||||||
active={active}
|
active={active}
|
||||||
environmentId={environment.id}
|
environmentId={environment.id}
|
||||||
locale={user.locale}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="flex h-full">
|
<div className="flex h-full">
|
||||||
<MainNavigation
|
<MainNavigation
|
||||||
environment={environment}
|
environment={environment}
|
||||||
organization={organization}
|
organization={organization}
|
||||||
|
organizations={organizations}
|
||||||
projects={projects}
|
projects={projects}
|
||||||
|
organizationProjectsLimit={organizationProjectsLimit}
|
||||||
user={user}
|
user={user}
|
||||||
isFormbricksCloud={IS_FORMBRICKS_CLOUD}
|
isFormbricksCloud={IS_FORMBRICKS_CLOUD}
|
||||||
isDevelopment={IS_DEVELOPMENT}
|
isDevelopment={IS_DEVELOPMENT}
|
||||||
membershipRole={membershipRole}
|
membershipRole={membershipRole}
|
||||||
|
isMultiOrgEnabled={isMultiOrgEnabled}
|
||||||
|
isLicenseActive={active}
|
||||||
/>
|
/>
|
||||||
<div id="mainContent" className="flex flex-1 flex-col overflow-hidden bg-slate-50">
|
<div id="mainContent" className="flex-1 overflow-y-auto bg-slate-50">
|
||||||
<TopControlBar
|
<TopControlBar
|
||||||
|
environment={environment}
|
||||||
environments={environments}
|
environments={environments}
|
||||||
currentOrganizationId={organization.id}
|
|
||||||
organizations={organizations}
|
|
||||||
currentProjectId={project.id}
|
|
||||||
projects={projects}
|
|
||||||
isMultiOrgEnabled={isMultiOrgEnabled}
|
|
||||||
organizationProjectsLimit={organizationProjectsLimit}
|
|
||||||
isFormbricksCloud={IS_FORMBRICKS_CLOUD}
|
|
||||||
isLicenseActive={active}
|
|
||||||
isOwnerOrManager={isOwnerOrManager}
|
|
||||||
isAccessControlAllowed={isAccessControlAllowed}
|
|
||||||
membershipRole={membershipRole}
|
membershipRole={membershipRole}
|
||||||
|
projectPermission={projectPermission}
|
||||||
/>
|
/>
|
||||||
<div className="flex-1 overflow-y-auto">{children}</div>
|
<div className="mt-14">{children}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { useSignOut } from "@/modules/auth/hooks/use-sign-out";
|
import { useSignOut } from "@/modules/auth/hooks/use-sign-out";
|
||||||
import { getLatestStableFbReleaseAction } from "@/modules/projects/settings/(setup)/app-connection/actions";
|
|
||||||
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";
|
||||||
@@ -8,6 +7,7 @@ import { TEnvironment } from "@formbricks/types/environment";
|
|||||||
import { TOrganization } from "@formbricks/types/organizations";
|
import { TOrganization } from "@formbricks/types/organizations";
|
||||||
import { TProject } from "@formbricks/types/project";
|
import { TProject } from "@formbricks/types/project";
|
||||||
import { TUser } from "@formbricks/types/user";
|
import { TUser } from "@formbricks/types/user";
|
||||||
|
import { getLatestStableFbReleaseAction } from "../actions/actions";
|
||||||
import { MainNavigation } from "./MainNavigation";
|
import { MainNavigation } from "./MainNavigation";
|
||||||
|
|
||||||
// Mock constants that this test needs
|
// Mock constants that this test needs
|
||||||
@@ -32,7 +32,7 @@ vi.mock("next-auth/react", () => ({
|
|||||||
vi.mock("@/modules/auth/hooks/use-sign-out", () => ({
|
vi.mock("@/modules/auth/hooks/use-sign-out", () => ({
|
||||||
useSignOut: vi.fn(() => ({ signOut: vi.fn() })),
|
useSignOut: vi.fn(() => ({ signOut: vi.fn() })),
|
||||||
}));
|
}));
|
||||||
vi.mock("@/modules/projects/settings/(setup)/app-connection/actions", () => ({
|
vi.mock("@/app/(app)/environments/[environmentId]/actions/actions", () => ({
|
||||||
getLatestStableFbReleaseAction: vi.fn(),
|
getLatestStableFbReleaseAction: vi.fn(),
|
||||||
}));
|
}));
|
||||||
vi.mock("@/app/lib/formbricks", () => ({
|
vi.mock("@/app/lib/formbricks", () => ({
|
||||||
@@ -51,6 +51,13 @@ vi.mock("@/modules/organization/components/CreateOrganizationModal", () => ({
|
|||||||
CreateOrganizationModal: ({ open }: { open: boolean }) =>
|
CreateOrganizationModal: ({ open }: { open: boolean }) =>
|
||||||
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", () => ({
|
||||||
|
ProjectSwitcher: ({ isCollapsed }: { isCollapsed: boolean }) => (
|
||||||
|
<div data-testid="project-switcher" data-collapsed={isCollapsed}>
|
||||||
|
Project Switcher
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
}));
|
||||||
vi.mock("@/modules/ui/components/avatars", () => ({
|
vi.mock("@/modules/ui/components/avatars", () => ({
|
||||||
ProfileAvatar: () => <div data-testid="profile-avatar">Avatar</div>,
|
ProfileAvatar: () => <div data-testid="profile-avatar">Avatar</div>,
|
||||||
}));
|
}));
|
||||||
@@ -93,12 +100,13 @@ const mockUser = {
|
|||||||
id: "user1",
|
id: "user1",
|
||||||
name: "Test User",
|
name: "Test User",
|
||||||
email: "test@example.com",
|
email: "test@example.com",
|
||||||
|
imageUrl: "http://example.com/avatar.png",
|
||||||
emailVerified: new Date(),
|
emailVerified: new Date(),
|
||||||
twoFactorEnabled: false,
|
twoFactorEnabled: false,
|
||||||
identityProvider: "email",
|
identityProvider: "email",
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
notificationSettings: { alert: {} },
|
notificationSettings: { alert: {}, weeklySummary: {} },
|
||||||
role: "project_manager",
|
role: "project_manager",
|
||||||
objective: "other",
|
objective: "other",
|
||||||
} as unknown as TUser;
|
} as unknown as TUser;
|
||||||
@@ -138,7 +146,6 @@ const defaultProps = {
|
|||||||
membershipRole: "owner" as const,
|
membershipRole: "owner" as const,
|
||||||
organizationProjectsLimit: 5,
|
organizationProjectsLimit: 5,
|
||||||
isLicenseActive: true,
|
isLicenseActive: true,
|
||||||
isAccessControlAllowed: true,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
describe("MainNavigation", () => {
|
describe("MainNavigation", () => {
|
||||||
@@ -159,11 +166,13 @@ describe("MainNavigation", () => {
|
|||||||
|
|
||||||
test("renders expanded by default and collapses on toggle", async () => {
|
test("renders expanded by default and collapses on toggle", async () => {
|
||||||
render(<MainNavigation {...defaultProps} />);
|
render(<MainNavigation {...defaultProps} />);
|
||||||
|
const projectSwitcher = screen.getByTestId("project-switcher");
|
||||||
// Assuming the toggle button is the only one initially without an accessible name
|
// Assuming the toggle button is the only one initially without an accessible name
|
||||||
// A more specific selector like data-testid would be better if available.
|
// A more specific selector like data-testid would be better if available.
|
||||||
const toggleButton = screen.getByRole("button", { name: "" });
|
const toggleButton = screen.getByRole("button", { name: "" });
|
||||||
|
|
||||||
// Check initial state (expanded)
|
// Check initial state (expanded)
|
||||||
|
expect(projectSwitcher).toHaveAttribute("data-collapsed", "false");
|
||||||
expect(screen.getByAltText("environments.formbricks_logo")).toBeInTheDocument();
|
expect(screen.getByAltText("environments.formbricks_logo")).toBeInTheDocument();
|
||||||
// Check localStorage is not set initially after clear()
|
// Check localStorage is not set initially after clear()
|
||||||
expect(localStorage.getItem("isMainNavCollapsed")).toBeNull();
|
expect(localStorage.getItem("isMainNavCollapsed")).toBeNull();
|
||||||
@@ -174,6 +183,7 @@ describe("MainNavigation", () => {
|
|||||||
// Check state after first toggle (collapsed)
|
// Check state after first toggle (collapsed)
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
// Check that the attribute eventually becomes true
|
// Check that the attribute eventually becomes true
|
||||||
|
expect(projectSwitcher).toHaveAttribute("data-collapsed", "true");
|
||||||
// Check that localStorage is updated
|
// Check that localStorage is updated
|
||||||
expect(localStorage.getItem("isMainNavCollapsed")).toBe("true");
|
expect(localStorage.getItem("isMainNavCollapsed")).toBe("true");
|
||||||
});
|
});
|
||||||
@@ -188,6 +198,7 @@ describe("MainNavigation", () => {
|
|||||||
// Check state after second toggle (expanded)
|
// Check state after second toggle (expanded)
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
// Check that the attribute eventually becomes false
|
// Check that the attribute eventually becomes false
|
||||||
|
expect(projectSwitcher).toHaveAttribute("data-collapsed", "false");
|
||||||
// Check that localStorage is updated
|
// Check that localStorage is updated
|
||||||
expect(localStorage.getItem("isMainNavCollapsed")).toBe("false");
|
expect(localStorage.getItem("isMainNavCollapsed")).toBe("false");
|
||||||
});
|
});
|
||||||
@@ -197,12 +208,18 @@ describe("MainNavigation", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("renders correct active navigation link", () => {
|
||||||
|
vi.mocked(usePathname).mockReturnValue("/environments/env1/actions");
|
||||||
|
render(<MainNavigation {...defaultProps} />);
|
||||||
|
const actionsLink = screen.getByRole("link", { name: /common.actions/ });
|
||||||
|
// Check if the parent li has the active class styling
|
||||||
|
expect(actionsLink.closest("li")).toHaveClass("border-brand-dark");
|
||||||
|
});
|
||||||
|
|
||||||
test("renders user dropdown and handles logout", async () => {
|
test("renders user dropdown and handles logout", async () => {
|
||||||
const mockSignOut = vi.fn().mockResolvedValue({ url: "/auth/login" });
|
const mockSignOut = vi.fn().mockResolvedValue({ url: "/auth/login" });
|
||||||
vi.mocked(useSignOut).mockReturnValue({ signOut: mockSignOut });
|
vi.mocked(useSignOut).mockReturnValue({ signOut: mockSignOut });
|
||||||
|
|
||||||
// Set up localStorage spy on the mocked localStorage
|
|
||||||
|
|
||||||
render(<MainNavigation {...defaultProps} />);
|
render(<MainNavigation {...defaultProps} />);
|
||||||
|
|
||||||
// Find the avatar and get its parent div which acts as the trigger
|
// Find the avatar and get its parent div which acts as the trigger
|
||||||
@@ -215,6 +232,8 @@ describe("MainNavigation", () => {
|
|||||||
expect(screen.getByText("common.account")).toBeInTheDocument();
|
expect(screen.getByText("common.account")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
expect(screen.getByText("common.organization")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("common.license")).toBeInTheDocument(); // Not cloud, not member
|
||||||
expect(screen.getByText("common.documentation")).toBeInTheDocument();
|
expect(screen.getByText("common.documentation")).toBeInTheDocument();
|
||||||
expect(screen.getByText("common.logout")).toBeInTheDocument();
|
expect(screen.getByText("common.logout")).toBeInTheDocument();
|
||||||
|
|
||||||
@@ -227,14 +246,52 @@ describe("MainNavigation", () => {
|
|||||||
organizationId: "org1",
|
organizationId: "org1",
|
||||||
redirect: false,
|
redirect: false,
|
||||||
callbackUrl: "/auth/login",
|
callbackUrl: "/auth/login",
|
||||||
clearEnvironmentId: true,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(mockRouterPush).toHaveBeenCalledWith("/auth/login");
|
expect(mockRouterPush).toHaveBeenCalledWith("/auth/login");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("handles organization switching", async () => {
|
||||||
|
render(<MainNavigation {...defaultProps} />);
|
||||||
|
|
||||||
|
const userTrigger = screen.getByTestId("profile-avatar").parentElement!;
|
||||||
|
await userEvent.click(userTrigger);
|
||||||
|
|
||||||
|
// Wait for the initial dropdown items
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText("common.switch_organization")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
const switchOrgTrigger = screen.getByText("common.switch_organization").closest("div[role='menuitem']")!;
|
||||||
|
await userEvent.hover(switchOrgTrigger); // Hover to open sub-menu
|
||||||
|
|
||||||
|
const org2Item = await screen.findByText("Another Org"); // findByText includes waitFor
|
||||||
|
await userEvent.click(org2Item);
|
||||||
|
|
||||||
|
expect(mockRouterPush).toHaveBeenCalledWith("/organizations/org2/");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("opens create organization modal", async () => {
|
||||||
|
render(<MainNavigation {...defaultProps} />);
|
||||||
|
|
||||||
|
const userTrigger = screen.getByTestId("profile-avatar").parentElement!;
|
||||||
|
await userEvent.click(userTrigger);
|
||||||
|
|
||||||
|
// Wait for the initial dropdown items
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText("common.switch_organization")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
const switchOrgTrigger = screen.getByText("common.switch_organization").closest("div[role='menuitem']")!;
|
||||||
|
await userEvent.hover(switchOrgTrigger); // Hover to open sub-menu
|
||||||
|
|
||||||
|
const createOrgButton = await screen.findByText("common.create_new_organization"); // findByText includes waitFor
|
||||||
|
await userEvent.click(createOrgButton);
|
||||||
|
|
||||||
|
expect(screen.getByTestId("create-org-modal")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
test("hides new version banner for members or if no new version", async () => {
|
test("hides new version banner for members or if no new version", async () => {
|
||||||
// Test for member
|
// Test for member
|
||||||
vi.mocked(getLatestStableFbReleaseAction).mockResolvedValue({ data: "v1.1.0" });
|
vi.mocked(getLatestStableFbReleaseAction).mockResolvedValue({ data: "v1.1.0" });
|
||||||
@@ -262,25 +319,15 @@ describe("MainNavigation", () => {
|
|||||||
expect(screen.queryByTestId("project-switcher")).not.toBeInTheDocument();
|
expect(screen.queryByTestId("project-switcher")).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("passes isAccessControlAllowed props to ProjectSwitcher", () => {
|
test("shows billing link and hides license link in cloud", async () => {
|
||||||
render(<MainNavigation {...defaultProps} />);
|
render(<MainNavigation {...defaultProps} isFormbricksCloud={true} />);
|
||||||
|
const userTrigger = screen.getByTestId("profile-avatar").parentElement!;
|
||||||
|
await userEvent.click(userTrigger);
|
||||||
|
|
||||||
// Test basic navigation structure is rendered (aside element with complementary role)
|
// Wait for dropdown items
|
||||||
expect(screen.getByRole("complementary")).toBeInTheDocument();
|
await waitFor(() => {
|
||||||
expect(screen.getByTestId("profile-avatar")).toBeInTheDocument();
|
expect(screen.getByText("common.billing")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
expect(screen.queryByText("common.license")).not.toBeInTheDocument();
|
||||||
test("handles no organizationTeams", () => {
|
|
||||||
render(<MainNavigation {...defaultProps} />);
|
|
||||||
|
|
||||||
// Test that navigation renders correctly with no teams
|
|
||||||
expect(screen.getByRole("complementary")).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("handles isAccessControlAllowed false", () => {
|
|
||||||
render(<MainNavigation {...defaultProps} />);
|
|
||||||
|
|
||||||
// Test that navigation renders correctly with access control disabled
|
|
||||||
expect(screen.getByRole("complementary")).toBeInTheDocument();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,32 +1,47 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { getLatestStableFbReleaseAction } from "@/app/(app)/environments/[environmentId]/actions/actions";
|
||||||
import { NavigationLink } from "@/app/(app)/environments/[environmentId]/components/NavigationLink";
|
import { NavigationLink } from "@/app/(app)/environments/[environmentId]/components/NavigationLink";
|
||||||
import { isNewerVersion } from "@/app/(app)/environments/[environmentId]/lib/utils";
|
|
||||||
import FBLogo from "@/images/formbricks-wordmark.svg";
|
import FBLogo from "@/images/formbricks-wordmark.svg";
|
||||||
import { cn } from "@/lib/cn";
|
import { cn } from "@/lib/cn";
|
||||||
import { getAccessFlags } from "@/lib/membership/utils";
|
import { getAccessFlags } from "@/lib/membership/utils";
|
||||||
|
import { capitalizeFirstLetter } from "@/lib/utils/strings";
|
||||||
import { useSignOut } from "@/modules/auth/hooks/use-sign-out";
|
import { useSignOut } from "@/modules/auth/hooks/use-sign-out";
|
||||||
import { getLatestStableFbReleaseAction } from "@/modules/projects/settings/(setup)/app-connection/actions";
|
import { CreateOrganizationModal } from "@/modules/organization/components/CreateOrganizationModal";
|
||||||
|
import { ProjectSwitcher } from "@/modules/projects/components/project-switcher";
|
||||||
import { ProfileAvatar } from "@/modules/ui/components/avatars";
|
import { ProfileAvatar } from "@/modules/ui/components/avatars";
|
||||||
import { Button } from "@/modules/ui/components/button";
|
import { Button } from "@/modules/ui/components/button";
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
|
DropdownMenuPortal,
|
||||||
|
DropdownMenuRadioGroup,
|
||||||
|
DropdownMenuRadioItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuSub,
|
||||||
|
DropdownMenuSubContent,
|
||||||
|
DropdownMenuSubTrigger,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "@/modules/ui/components/dropdown-menu";
|
} from "@/modules/ui/components/dropdown-menu";
|
||||||
import { useTranslate } from "@tolgee/react";
|
import { useTranslate } from "@tolgee/react";
|
||||||
import {
|
import {
|
||||||
ArrowUpRightIcon,
|
ArrowUpRightIcon,
|
||||||
|
BlocksIcon,
|
||||||
ChevronRightIcon,
|
ChevronRightIcon,
|
||||||
Cog,
|
Cog,
|
||||||
|
CreditCardIcon,
|
||||||
|
KeyIcon,
|
||||||
LogOutIcon,
|
LogOutIcon,
|
||||||
MessageCircle,
|
MessageCircle,
|
||||||
|
MousePointerClick,
|
||||||
PanelLeftCloseIcon,
|
PanelLeftCloseIcon,
|
||||||
PanelLeftOpenIcon,
|
PanelLeftOpenIcon,
|
||||||
|
PlusIcon,
|
||||||
RocketIcon,
|
RocketIcon,
|
||||||
UserCircleIcon,
|
UserCircleIcon,
|
||||||
UserIcon,
|
UserIcon,
|
||||||
|
UsersIcon,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
@@ -35,40 +50,53 @@ import { useEffect, useMemo, useState } from "react";
|
|||||||
import { TEnvironment } from "@formbricks/types/environment";
|
import { TEnvironment } from "@formbricks/types/environment";
|
||||||
import { TOrganizationRole } from "@formbricks/types/memberships";
|
import { TOrganizationRole } from "@formbricks/types/memberships";
|
||||||
import { TOrganization } from "@formbricks/types/organizations";
|
import { TOrganization } from "@formbricks/types/organizations";
|
||||||
|
import { TProject } from "@formbricks/types/project";
|
||||||
import { TUser } from "@formbricks/types/user";
|
import { TUser } from "@formbricks/types/user";
|
||||||
import packageJson from "../../../../../package.json";
|
import packageJson from "../../../../../package.json";
|
||||||
|
|
||||||
interface NavigationProps {
|
interface NavigationProps {
|
||||||
environment: TEnvironment;
|
environment: TEnvironment;
|
||||||
|
organizations: TOrganization[];
|
||||||
user: TUser;
|
user: TUser;
|
||||||
organization: TOrganization;
|
organization: TOrganization;
|
||||||
projects: { id: string; name: string }[];
|
projects: TProject[];
|
||||||
|
isMultiOrgEnabled: boolean;
|
||||||
isFormbricksCloud: boolean;
|
isFormbricksCloud: boolean;
|
||||||
isDevelopment: boolean;
|
isDevelopment: boolean;
|
||||||
membershipRole?: TOrganizationRole;
|
membershipRole?: TOrganizationRole;
|
||||||
|
organizationProjectsLimit: number;
|
||||||
|
isLicenseActive: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const MainNavigation = ({
|
export const MainNavigation = ({
|
||||||
environment,
|
environment,
|
||||||
|
organizations,
|
||||||
organization,
|
organization,
|
||||||
user,
|
user,
|
||||||
projects,
|
projects,
|
||||||
|
isMultiOrgEnabled,
|
||||||
membershipRole,
|
membershipRole,
|
||||||
isFormbricksCloud,
|
isFormbricksCloud,
|
||||||
|
organizationProjectsLimit,
|
||||||
|
isLicenseActive,
|
||||||
isDevelopment,
|
isDevelopment,
|
||||||
}: NavigationProps) => {
|
}: NavigationProps) => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const { t } = useTranslate();
|
const { t } = useTranslate();
|
||||||
|
const [currentOrganizationName, setCurrentOrganizationName] = useState("");
|
||||||
|
const [currentOrganizationId, setCurrentOrganizationId] = useState("");
|
||||||
|
const [showCreateOrganizationModal, setShowCreateOrganizationModal] = useState(false);
|
||||||
const [isCollapsed, setIsCollapsed] = useState(true);
|
const [isCollapsed, setIsCollapsed] = useState(true);
|
||||||
const [isTextVisible, setIsTextVisible] = useState(true);
|
const [isTextVisible, setIsTextVisible] = useState(true);
|
||||||
const [latestVersion, setLatestVersion] = useState("");
|
const [latestVersion, setLatestVersion] = useState("");
|
||||||
const { signOut: signOutWithAudit } = useSignOut({ id: user.id, email: user.email });
|
const { signOut: signOutWithAudit } = useSignOut({ id: user.id, email: user.email });
|
||||||
|
|
||||||
const project = projects.find((project) => project.id === environment.projectId);
|
const project = projects.find((project) => project.id === environment.projectId);
|
||||||
const { isManager, isOwner, isBilling } = getAccessFlags(membershipRole);
|
const { isManager, isOwner, isMember, isBilling } = getAccessFlags(membershipRole);
|
||||||
|
|
||||||
const isOwnerOrManager = isManager || isOwner;
|
const isOwnerOrManager = isManager || isOwner;
|
||||||
|
const isPricingDisabled = isMember;
|
||||||
|
|
||||||
const toggleSidebar = () => {
|
const toggleSidebar = () => {
|
||||||
setIsCollapsed(!isCollapsed);
|
setIsCollapsed(!isCollapsed);
|
||||||
@@ -89,11 +117,40 @@ export const MainNavigation = ({
|
|||||||
}, [isCollapsed]);
|
}, [isCollapsed]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Auto collapse project navbar on org and account settings
|
if (organization && organization.name !== "") {
|
||||||
if (pathname?.includes("/settings")) {
|
setCurrentOrganizationName(organization.name);
|
||||||
setIsCollapsed(true);
|
setCurrentOrganizationId(organization.id);
|
||||||
}
|
}
|
||||||
}, [pathname]);
|
}, [organization]);
|
||||||
|
|
||||||
|
const sortedOrganizations = useMemo(() => {
|
||||||
|
return [...organizations].sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
}, [organizations]);
|
||||||
|
|
||||||
|
const sortedProjects = useMemo(() => {
|
||||||
|
const channelOrder: (string | null)[] = ["website", "app", "link", null];
|
||||||
|
|
||||||
|
const groupedProjects = projects.reduce(
|
||||||
|
(acc, project) => {
|
||||||
|
const channel = project.config.channel;
|
||||||
|
const key = channel !== null ? channel : "null";
|
||||||
|
acc[key] = acc[key] || [];
|
||||||
|
acc[key].push(project);
|
||||||
|
return acc;
|
||||||
|
},
|
||||||
|
{} as Record<string, typeof projects>
|
||||||
|
);
|
||||||
|
|
||||||
|
Object.keys(groupedProjects).forEach((channel) => {
|
||||||
|
groupedProjects[channel].sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
});
|
||||||
|
|
||||||
|
return channelOrder.flatMap((channel) => groupedProjects[channel !== null ? channel : "null"] || []);
|
||||||
|
}, [projects]);
|
||||||
|
|
||||||
|
const handleEnvironmentChangeByOrganization = (organizationId: string) => {
|
||||||
|
router.push(`/organizations/${organizationId}/`);
|
||||||
|
};
|
||||||
|
|
||||||
const mainNavigation = useMemo(
|
const mainNavigation = useMemo(
|
||||||
() => [
|
() => [
|
||||||
@@ -110,6 +167,18 @@ export const MainNavigation = ({
|
|||||||
icon: UserIcon,
|
icon: UserIcon,
|
||||||
isActive: pathname?.includes("/contacts") || pathname?.includes("/segments"),
|
isActive: pathname?.includes("/contacts") || pathname?.includes("/segments"),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: t("common.actions"),
|
||||||
|
href: `/environments/${environment.id}/actions`,
|
||||||
|
icon: MousePointerClick,
|
||||||
|
isActive: pathname?.includes("/actions"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: t("common.integrations"),
|
||||||
|
href: `/environments/${environment.id}/integrations`,
|
||||||
|
icon: BlocksIcon,
|
||||||
|
isActive: pathname?.includes("/integrations"),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: t("common.configuration"),
|
name: t("common.configuration"),
|
||||||
href: `/environments/${environment.id}/project/general`,
|
href: `/environments/${environment.id}/project/general`,
|
||||||
@@ -127,14 +196,25 @@ export const MainNavigation = ({
|
|||||||
icon: UserCircleIcon,
|
icon: UserCircleIcon,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: t("common.documentation"),
|
label: t("common.organization"),
|
||||||
href: "https://formbricks.com/docs",
|
href: `/environments/${environment.id}/settings/general`,
|
||||||
target: "_blank",
|
icon: UsersIcon,
|
||||||
icon: ArrowUpRightIcon,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: t("common.share_feedback"),
|
label: t("common.billing"),
|
||||||
href: "https://github.com/formbricks/formbricks/issues",
|
href: `/environments/${environment.id}/settings/billing`,
|
||||||
|
hidden: !isFormbricksCloud,
|
||||||
|
icon: CreditCardIcon,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: t("common.license"),
|
||||||
|
href: `/environments/${environment.id}/settings/enterprise`,
|
||||||
|
hidden: isFormbricksCloud || isPricingDisabled,
|
||||||
|
icon: KeyIcon,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: t("common.documentation"),
|
||||||
|
href: "https://formbricks.com/docs",
|
||||||
target: "_blank",
|
target: "_blank",
|
||||||
icon: ArrowUpRightIcon,
|
icon: ArrowUpRightIcon,
|
||||||
},
|
},
|
||||||
@@ -147,7 +227,7 @@ export const MainNavigation = ({
|
|||||||
const latestVersionTag = res.data;
|
const latestVersionTag = res.data;
|
||||||
const currentVersionTag = `v${packageJson.version}`;
|
const currentVersionTag = `v${packageJson.version}`;
|
||||||
|
|
||||||
if (isNewerVersion(currentVersionTag, latestVersionTag)) {
|
if (currentVersionTag !== latestVersionTag) {
|
||||||
setLatestVersion(latestVersionTag);
|
setLatestVersion(latestVersionTag);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -163,7 +243,8 @@ export const MainNavigation = ({
|
|||||||
<aside
|
<aside
|
||||||
className={cn(
|
className={cn(
|
||||||
"z-40 flex flex-col justify-between rounded-r-xl border-r border-slate-200 bg-white pt-3 shadow-md transition-all duration-100",
|
"z-40 flex flex-col justify-between rounded-r-xl border-r border-slate-200 bg-white pt-3 shadow-md transition-all duration-100",
|
||||||
!isCollapsed ? "w-sidebar-collapsed" : "w-sidebar-expanded"
|
!isCollapsed ? "w-sidebar-collapsed" : "w-sidebar-expanded",
|
||||||
|
environment.type === "development" ? `h-[calc(100vh-1.25rem)]` : "h-screen"
|
||||||
)}>
|
)}>
|
||||||
<div>
|
<div>
|
||||||
{/* Logo and Toggle */}
|
{/* Logo and Toggle */}
|
||||||
@@ -229,6 +310,22 @@ export const MainNavigation = ({
|
|||||||
</Link>
|
</Link>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Project Switch */}
|
||||||
|
{!isBilling && (
|
||||||
|
<ProjectSwitcher
|
||||||
|
environmentId={environment.id}
|
||||||
|
projects={sortedProjects}
|
||||||
|
project={project}
|
||||||
|
isCollapsed={isCollapsed}
|
||||||
|
isFormbricksCloud={isFormbricksCloud}
|
||||||
|
isLicenseActive={isLicenseActive}
|
||||||
|
isOwnerOrManager={isOwnerOrManager}
|
||||||
|
isTextVisible={isTextVisible}
|
||||||
|
organization={organization}
|
||||||
|
organizationProjectsLimit={organizationProjectsLimit}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* User Switch */}
|
{/* User Switch */}
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
@@ -237,27 +334,29 @@ export const MainNavigation = ({
|
|||||||
id="userDropdownTrigger"
|
id="userDropdownTrigger"
|
||||||
className="w-full rounded-br-xl border-t py-4 transition-colors duration-200 hover:bg-slate-50 focus:outline-none">
|
className="w-full rounded-br-xl border-t py-4 transition-colors duration-200 hover:bg-slate-50 focus:outline-none">
|
||||||
<div
|
<div
|
||||||
|
tabIndex={0}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex cursor-pointer flex-row items-center gap-3",
|
"flex cursor-pointer flex-row items-center space-x-3",
|
||||||
isCollapsed ? "justify-center px-2" : "px-4"
|
isCollapsed ? "pl-2" : "pl-4"
|
||||||
)}>
|
)}>
|
||||||
<ProfileAvatar userId={user.id} />
|
<ProfileAvatar userId={user.id} imageUrl={user.imageUrl} />
|
||||||
{!isCollapsed && !isTextVisible && (
|
{!isCollapsed && !isTextVisible && (
|
||||||
<>
|
<>
|
||||||
<div
|
<div className={cn(isTextVisible ? "opacity-0" : "opacity-100")}>
|
||||||
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 truncate text-sm font-bold text-slate-700"
|
"ph-no-capture ph-no-capture -mb-0.5 max-w-28 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 className="text-sm text-slate-700">{t("common.account")}</p>
|
<p
|
||||||
|
title={capitalizeFirstLetter(organization?.name)}
|
||||||
|
className="max-w-28 truncate text-sm text-slate-500">
|
||||||
|
{capitalizeFirstLetter(organization?.name)}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<ChevronRightIcon
|
<ChevronRightIcon className={cn("h-5 w-5 text-slate-700 hover:text-slate-500")} />
|
||||||
className={cn("h-5 w-5 shrink-0 text-slate-700 hover:text-slate-500")}
|
|
||||||
/>
|
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -271,20 +370,24 @@ export const MainNavigation = ({
|
|||||||
align="end">
|
align="end">
|
||||||
{/* Dropdown Items */}
|
{/* Dropdown Items */}
|
||||||
|
|
||||||
{dropdownNavigation.map((link) => (
|
{dropdownNavigation.map(
|
||||||
<Link
|
(link) =>
|
||||||
href={link.href}
|
!link.hidden && (
|
||||||
target={link.target}
|
<Link
|
||||||
className="flex w-full items-center"
|
href={link.href}
|
||||||
key={link.label}
|
target={link.target}
|
||||||
rel={link.target === "_blank" ? "noopener noreferrer" : undefined}>
|
className="flex w-full items-center"
|
||||||
<DropdownMenuItem>
|
key={link.label}>
|
||||||
<link.icon className="mr-2 h-4 w-4" strokeWidth={1.5} />
|
<DropdownMenuItem>
|
||||||
{link.label}
|
<link.icon className="mr-2 h-4 w-4" strokeWidth={1.5} />
|
||||||
</DropdownMenuItem>
|
{link.label}
|
||||||
</Link>
|
</DropdownMenuItem>
|
||||||
))}
|
</Link>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Logout */}
|
{/* Logout */}
|
||||||
|
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
const route = await signOutWithAudit({
|
const route = await signOutWithAudit({
|
||||||
@@ -293,19 +396,61 @@ export const MainNavigation = ({
|
|||||||
organizationId: organization.id,
|
organizationId: organization.id,
|
||||||
redirect: false,
|
redirect: false,
|
||||||
callbackUrl: "/auth/login",
|
callbackUrl: "/auth/login",
|
||||||
clearEnvironmentId: true,
|
|
||||||
});
|
});
|
||||||
router.push(route?.url || "/auth/login"); // NOSONAR // We want to check for empty strings
|
router.push(route?.url || "/auth/login"); // NOSONAR // We want to check for empty strings
|
||||||
}}
|
}}
|
||||||
icon={<LogOutIcon className="mr-2 h-4 w-4" strokeWidth={1.5} />}>
|
icon={<LogOutIcon className="mr-2 h-4 w-4" strokeWidth={1.5} />}>
|
||||||
{t("common.logout")}
|
{t("common.logout")}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|
||||||
|
{/* Organization Switch */}
|
||||||
|
|
||||||
|
{(isMultiOrgEnabled || organizations.length > 1) && (
|
||||||
|
<DropdownMenuSub>
|
||||||
|
<DropdownMenuSubTrigger className="rounded-lg">
|
||||||
|
<div>
|
||||||
|
<p>{currentOrganizationName}</p>
|
||||||
|
<p className="block text-xs text-slate-500">{t("common.switch_organization")}</p>
|
||||||
|
</div>
|
||||||
|
</DropdownMenuSubTrigger>
|
||||||
|
<DropdownMenuPortal>
|
||||||
|
<DropdownMenuSubContent sideOffset={10} alignOffset={5}>
|
||||||
|
<DropdownMenuRadioGroup
|
||||||
|
value={currentOrganizationId}
|
||||||
|
onValueChange={(organizationId) =>
|
||||||
|
handleEnvironmentChangeByOrganization(organizationId)
|
||||||
|
}>
|
||||||
|
{sortedOrganizations.map((organization) => (
|
||||||
|
<DropdownMenuRadioItem
|
||||||
|
value={organization.id}
|
||||||
|
className="cursor-pointer rounded-lg"
|
||||||
|
key={organization.id}>
|
||||||
|
{organization.name}
|
||||||
|
</DropdownMenuRadioItem>
|
||||||
|
))}
|
||||||
|
</DropdownMenuRadioGroup>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
{isMultiOrgEnabled && (
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() => setShowCreateOrganizationModal(true)}
|
||||||
|
icon={<PlusIcon className="mr-2 h-4 w-4" />}>
|
||||||
|
<span>{t("common.create_new_organization")}</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
|
</DropdownMenuSubContent>
|
||||||
|
</DropdownMenuPortal>
|
||||||
|
</DropdownMenuSub>
|
||||||
|
)}
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
)}
|
)}
|
||||||
|
<CreateOrganizationModal
|
||||||
|
open={showCreateOrganizationModal}
|
||||||
|
setOpen={(val) => setShowCreateOrganizationModal(val)}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -36,6 +36,8 @@ describe("PosthogIdentify", () => {
|
|||||||
{
|
{
|
||||||
name: "Test User",
|
name: "Test User",
|
||||||
email: "test@example.com",
|
email: "test@example.com",
|
||||||
|
role: "engineer",
|
||||||
|
objective: "increase_conversion",
|
||||||
} as TUser
|
} as TUser
|
||||||
}
|
}
|
||||||
environmentId="env-456"
|
environmentId="env-456"
|
||||||
@@ -55,6 +57,8 @@ describe("PosthogIdentify", () => {
|
|||||||
expect(mockIdentify).toHaveBeenCalledWith("user-123", {
|
expect(mockIdentify).toHaveBeenCalledWith("user-123", {
|
||||||
name: "Test User",
|
name: "Test User",
|
||||||
email: "test@example.com",
|
email: "test@example.com",
|
||||||
|
role: "engineer",
|
||||||
|
objective: "increase_conversion",
|
||||||
});
|
});
|
||||||
|
|
||||||
// environment + organization groups
|
// environment + organization groups
|
||||||
@@ -138,6 +142,8 @@ describe("PosthogIdentify", () => {
|
|||||||
expect(mockIdentify).toHaveBeenCalledWith("user-123", {
|
expect(mockIdentify).toHaveBeenCalledWith("user-123", {
|
||||||
name: "Test User",
|
name: "Test User",
|
||||||
email: "test@example.com",
|
email: "test@example.com",
|
||||||
|
role: undefined,
|
||||||
|
objective: undefined,
|
||||||
});
|
});
|
||||||
// No environmentId or organizationId => no group calls
|
// No environmentId or organizationId => no group calls
|
||||||
expect(mockGroup).not.toHaveBeenCalled();
|
expect(mockGroup).not.toHaveBeenCalled();
|
||||||
|
|||||||
@@ -32,6 +32,8 @@ export const PosthogIdentify = ({
|
|||||||
posthog.identify(session.user.id, {
|
posthog.identify(session.user.id, {
|
||||||
name: user.name,
|
name: user.name,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
|
role: user.role,
|
||||||
|
objective: user.objective,
|
||||||
});
|
});
|
||||||
if (environmentId) {
|
if (environmentId) {
|
||||||
posthog.group("environment", environmentId, { name: environmentId });
|
posthog.group("environment", environmentId, { name: environmentId });
|
||||||
@@ -54,6 +56,8 @@ export const PosthogIdentify = ({
|
|||||||
organizationBilling,
|
organizationBilling,
|
||||||
user.name,
|
user.name,
|
||||||
user.email,
|
user.email,
|
||||||
|
user.role,
|
||||||
|
user.objective,
|
||||||
isPosthogEnabled,
|
isPosthogEnabled,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ const TestComponent = () => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div data-testid="responseStatus">{selectedFilter.responseStatus}</div>
|
<div data-testid="onlyComplete">{selectedFilter.onlyComplete.toString()}</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" },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
responseStatus: "complete",
|
onlyComplete: true,
|
||||||
})
|
})
|
||||||
}>
|
}>
|
||||||
Update Filter
|
Update Filter
|
||||||
@@ -81,7 +81,7 @@ describe("ResponseFilterContext", () => {
|
|||||||
</ResponseFilterProvider>
|
</ResponseFilterProvider>
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(screen.getByTestId("responseStatus").textContent).toBe("all");
|
expect(screen.getByTestId("onlyComplete").textContent).toBe("false");
|
||||||
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("responseStatus").textContent).toBe("complete");
|
expect(screen.getByTestId("onlyComplete").textContent).toBe("true");
|
||||||
expect(screen.getByTestId("filterLength").textContent).toBe("1");
|
expect(screen.getByTestId("filterLength").textContent).toBe("1");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -16,11 +16,9 @@ export interface FilterValue {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export type TResponseStatus = "all" | "complete" | "partial";
|
|
||||||
|
|
||||||
export interface SelectedFilterValue {
|
export interface SelectedFilterValue {
|
||||||
filter: FilterValue[];
|
filter: FilterValue[];
|
||||||
responseStatus: TResponseStatus;
|
onlyComplete: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface SelectedFilterOptions {
|
interface SelectedFilterOptions {
|
||||||
@@ -49,7 +47,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: [],
|
||||||
responseStatus: "all",
|
onlyComplete: false,
|
||||||
});
|
});
|
||||||
// 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>({
|
||||||
@@ -69,7 +67,7 @@ const ResponseFilterProvider = ({ children }: { children: React.ReactNode }) =>
|
|||||||
});
|
});
|
||||||
setSelectedFilter({
|
setSelectedFilter({
|
||||||
filter: [],
|
filter: [],
|
||||||
responseStatus: "all",
|
onlyComplete: false,
|
||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user