Compare commits

..
6 Commits
Author SHA1 Message Date
Charles Bochetandetiennejouan d3cbbb4311 Fix one to many relation and multi select fields on table (#14576)
Fixes:
- relation one to many cannot be set (we have deprecated limit: keyword
in graphql at it was not use, we should only use first or last)
- https://github.com/twentyhq/twenty/issues/14556
2025-09-18 12:11:30 +02:00
Weiko bb9add4c48 various UI fixes in calendar view (#14551) 2025-09-17 16:29:22 +02:00
Thomas TrompetteandWeiko 538bd944cd Put back previous empty option (#14542)
Adding that option puts No Value everywhere. Removing it.
2025-09-16 17:38:56 +02:00
Weiko 27a21dea35 Add dnd to calendar view (#14539) 2025-09-16 17:38:51 +02:00
Thomas TrompetteandWeiko fabeeafad6 Add form select field (#14538)
- create a WorkflowFormFieldInput component that takes a fieldMetadataId
as input and display a form field input
- add a select field for forms


https://github.com/user-attachments/assets/42f8ce98-c17a-4809-b1be-032e3066a596
2025-09-16 17:38:47 +02:00
Weiko 2168a678d8 Add compact view to calendar (#14527)
<img width="1263" height="785" alt="Screenshot 2025-09-16 at 11 44 44"
src="https://github.com/user-attachments/assets/dc61e69f-b887-4a4d-9f9c-e50ffa076082"
/>
<img width="1263" height="785" alt="Screenshot 2025-09-16 at 11 43 45"
src="https://github.com/user-attachments/assets/2dd917b3-6e6d-40f2-bb10-6c82de83c15d"
/>
2025-09-16 17:38:42 +02:00
10267 changed files with 183587 additions and 733484 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
{
"install": "curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash - && sudo apt-get install -y nodejs && node --version && yarn install && echo 'Setting up Docker Compose environment...' && cd packages/twenty-docker && cp -n docker-compose.yml docker-compose.dev.yml || true && echo 'Dependencies installed and docker-compose prepared'",
"install": "yarn install && echo 'Setting up Docker Compose environment...' && cd packages/twenty-docker && cp -n docker-compose.yml docker-compose.dev.yml || true && echo 'Dependencies installed and docker-compose prepared'",
"start": "sudo service docker start && echo 'Docker service started' && cd packages/twenty-docker && echo 'Installing yq for YAML processing...' && sudo apt-get update -qq && sudo apt-get install -y wget && wget -qO /usr/local/bin/yq https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 && sudo chmod +x /usr/local/bin/yq && echo 'Patching docker-compose for local development...' && yq eval 'del(.services.server.image)' -i docker-compose.dev.yml && yq eval '.services.server.build.context = \"../../\"' -i docker-compose.dev.yml && yq eval '.services.server.build.dockerfile = \"./packages/twenty-docker/twenty/Dockerfile\"' -i docker-compose.dev.yml && yq eval 'del(.services.worker.image)' -i docker-compose.dev.yml && yq eval '.services.worker.build.context = \"../../\"' -i docker-compose.dev.yml && yq eval '.services.worker.build.dockerfile = \"./packages/twenty-docker/twenty/Dockerfile\"' -i docker-compose.dev.yml && echo 'Setting up .env file with database configuration...' && echo 'SERVER_URL=http://localhost:3000' > .env && echo 'APP_SECRET='$(openssl rand -base64 32) >> .env && echo 'PG_DATABASE_PASSWORD='$(openssl rand -hex 16) >> .env && echo 'PG_DATABASE_URL=postgres://postgres:password@localhost:5432/postgres' >> .env && echo 'SIGN_IN_PREFILLED=true' >> .env && echo 'Building and starting services...' && docker-compose -f docker-compose.dev.yml up -d --build && echo 'Waiting for services to initialize...' && sleep 30 && echo 'Checking service health...' && docker-compose -f docker-compose.dev.yml ps && echo 'Environment setup complete!'",
"terminals": [
{
+3 -3
View File
@@ -1,10 +1,10 @@
{
"install": "curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash - && sudo apt-get install -y nodejs && node --version && yarn install && echo 'Installing dependencies complete'",
"start": "sudo service docker start && echo 'Docker service started' && sleep 3 && echo 'Starting PostgreSQL and Redis containers...' && make postgres-on-docker && make redis-on-docker && echo 'Waiting for containers to initialize...' && sleep 20 && echo 'Checking container status...' && docker ps --filter name=twenty_ && echo 'Waiting for PostgreSQL to be ready...' && until docker exec twenty_pg pg_isready -U postgres -h localhost; do echo 'PostgreSQL not ready yet, waiting...'; sleep 3; done && echo 'PostgreSQL is ready!' && echo 'Setting up database...' && cd packages/twenty-server && npx nx database:reset twenty-server || echo 'Database already initialized' && echo 'Environment setup complete!'",
"install": "yarn install && echo 'Installing dependencies complete'",
"start": "sudo service docker start && echo 'Docker service started' && sleep 3 && echo 'Starting PostgreSQL and Redis containers...' && make postgres-on-docker && make redis-on-docker && echo 'Waiting for containers to initialize...' && sleep 20 && echo 'Checking container status...' && docker ps --filter name=twenty_ && echo 'Waiting for PostgreSQL to be ready...' && until docker exec twenty_pg pg_isready -U postgres -h localhost; do echo 'PostgreSQL not ready yet, waiting...'; sleep 3; done && echo 'PostgreSQL is ready!' && echo 'Setting up database...' && cd packages/twenty-server && npm run database:init || echo 'Database already initialized' && echo 'Environment setup complete!'",
"terminals": [
{
"name": "Development Server",
"command": "echo 'Waiting for database to be fully ready...' && sleep 30 && until docker exec twenty_pg pg_isready -U postgres -h localhost; do echo 'Waiting for PostgreSQL...'; sleep 2; done && echo 'Starting Twenty development server...' && export SERVER_URL=http://localhost:3000 && export PG_DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres && yarn start"
"command": "echo 'Waiting for database to be fully ready...' && sleep 30 && until docker exec twenty_pg pg_isready -U postgres -h localhost; do echo 'Waiting for PostgreSQL...'; sleep 2; done && echo 'Starting Twenty development server...' && export SERVER_URL=http://localhost:3000 && export PG_DATABASE_URL=postgres://postgres:password@localhost:5432/postgres && yarn start"
},
{
"name": "Database Management",
-319
View File
@@ -1,319 +0,0 @@
---
description: Process and guidelines for creating release changelogs for Twenty CRM
globs: ["**/releases/*.mdx", "**/releases/**"]
alwaysApply: false
---
# Twenty Release Changelog Process
Complete guide for creating release changelogs, including codebase research, file structure, and content guidelines.
## Prerequisites
Before starting, gather the following information:
### Required Information
**Version Number**: `{VERSION}` (e.g., 1.9.0, 2.0.0, 2.1.0)
**Release Date**: Use today's date in format: YYYY-MM-DD
### Changes/Features to Document
List the features and changes to include in this release:
1. **Feature Name**: ______________________________
- Brief description: ______________________________
- Related area (workflow, UI, backend, etc.): ______________________________
2. **Feature Name**: ______________________________
- Brief description: ______________________________
- Related area: ______________________________
3. **Feature Name**: ______________________________
- Brief description: ______________________________
- Related area: ______________________________
## Codebase Research Guide
If feature descriptions are not provided or need enhancement, research the codebase:
### Where to Look
**For Workflow Features:**
- Frontend: `packages/twenty-front/src/modules/workflow/`
- Backend: `packages/twenty-server/src/modules/workflow/`
- Components: `packages/twenty-front/src/modules/workflow/components/`
**For UI/UX Changes:**
- Components: `packages/twenty-front/src/modules/ui/`
- Layout: `packages/twenty-front/src/modules/layout/`
- Design system: `packages/twenty-ui/src/`
**For Backend/API Features:**
- Server modules: `packages/twenty-server/src/modules/`
- Entities: `packages/twenty-server/src/entities/`
- Services: Look for `*.service.ts` files
**For Database/ORM Changes:**
- Migrations: `packages/twenty-server/src/database/typeorm/`
- Entities: `packages/twenty-server/src/entities/`
### Research Commands
```bash
# Find recent merged PRs (adjust date as needed)
gh pr list --search "merged:>2025-10-01" --limit 50 --state merged
# View recent commits
git log --since="2 weeks ago" --oneline --no-merges
# View commits between releases (replace with actual release tags)
git log v1.7.0..v1.8.0 --oneline
# Search for specific feature keywords in code
grep -r "iterator" packages/twenty-front/src/modules/workflow/
grep -r "bulk select" packages/twenty-front/src/modules/workflow/
# Find recent changes in specific directory
git log --since="2 weeks ago" --oneline -- packages/twenty-front/src/modules/workflow/
```
### Using Codebase Search
Use the AI codebase search to find:
- "How does the workflow iterator node work?"
- "Where is bulk select implemented for workflows?"
- "What changes were made to the search node limit?"
## Step-by-Step Process
### 1. Setup Git Branch
```bash
cd /Users/thomascolasdesfrancs/code/twenty
git checkout main
git pull origin main
git checkout -b {VERSION}
```
Replace `{VERSION}` with the actual version number (e.g., `1.9.0`)
### 2. Create File Structure
**Create changelog file:**
- Path: `packages/twenty-website/src/content/releases/{VERSION}.mdx`
- Example: `packages/twenty-website/src/content/releases/1.9.0.mdx`
**Create image folder:**
- Path: `packages/twenty-website/public/images/releases/{MINOR_VERSION}/`
- Example for version 1.9.0: `packages/twenty-website/public/images/releases/1.9/`
- Example for version 2.0.0: `packages/twenty-website/public/images/releases/2.0/`
```bash
# Create the image folder
mkdir -p packages/twenty-website/public/images/releases/{MINOR_VERSION}
```
### 3. Move Illustration Files
**Source:** `/Users/thomascolasdesfrancs/Downloads/🆕`
**Destination:** `packages/twenty-website/public/images/releases/{MINOR_VERSION}/`
**Naming Convention:** `{VERSION}-descriptive-name.png`
Examples:
- `1.9.0-feature-name.png`
- `1.9.0-another-feature.png`
```bash
# Move and rename files
cp ~/Downloads/🆕/source-file.png packages/twenty-website/public/images/releases/{MINOR_VERSION}/{VERSION}-feature-name.png
```
### 4. Research Features (if needed)
If descriptions are not provided:
1. Use the research commands above to find recent PRs and commits
2. Search the codebase for feature-related code
3. Read PR descriptions for context
4. Check component comments and documentation
### 5. Write Changelog Content
Create the MDX file with this structure:
```markdown
---
release: {VERSION}
Date: {YYYY-MM-DD}
---
# Feature 1 Name
Short description explaining what the feature does and why it's useful. Keep it user-focused and concise (1-2 sentences).
![](/images/releases/{MINOR_VERSION}/{VERSION}-feature-1.png)
# Feature 2 Name
Another short description of the second feature.
![](/images/releases/{MINOR_VERSION}/{VERSION}-feature-2.png)
# Feature 3 Name
Description of the third feature.
![](/images/releases/{MINOR_VERSION}/{VERSION}-feature-3.png)
```
**Style Guidelines:**
- Use H1 (`#`) for feature names
- Keep descriptions to 1-2 sentences
- Focus on user benefits, not technical implementation
- Use active voice
- Start with what the user can now do
**Reference Previous Changelogs:**
- Check `packages/twenty-website/src/content/releases/` for examples
- Recent releases: 1.7.0.mdx, 1.6.0.mdx, 1.5.0.mdx
### 6. Review
Open the changelog file for review:
```bash
# Open in Cursor
cursor packages/twenty-website/src/content/releases/{VERSION}.mdx
# Open image folder to verify illustrations
open packages/twenty-website/public/images/releases/{MINOR_VERSION}
```
Review checklist:
- [ ] Version number is correct in frontmatter
- [ ] Date is today's date
- [ ] All features are documented
- [ ] Image paths are correct
- [ ] Image files exist in the folder
- [ ] Descriptions are clear and user-focused
- [ ] Spelling and grammar are correct
### 7. Present Changelog for User Approval
**IMPORTANT**: Before committing and creating the PR, always show the complete changelog content to the user and wait for explicit approval.
**What to show:**
1. Display the full MDX content of the changelog file
2. Confirm that illustration files were moved to the correct location
3. List the image file names and paths
**What to say:**
```
I've created the changelog for version {VERSION}. Here's the content for your review:
[Show full MDX content]
Images moved to:
- packages/twenty-website/public/images/releases/{MINOR_VERSION}/{VERSION}-feature-1.png
- packages/twenty-website/public/images/releases/{MINOR_VERSION}/{VERSION}-feature-2.png
Please review the content. Once you approve, I'll commit the changes and create the pull request.
```
**Wait for user approval before proceeding to step 8.**
Possible user responses:
- "Looks good" / "Approve" / "Create the PR" → Proceed to step 8
- Requests changes → Make the requested edits, then show content again
- Asks questions → Answer them, then wait for approval
### 8. Commit Changes
```bash
# Check status
git status
# Add files
git add packages/twenty-website/src/content/releases/{VERSION}.mdx
git add packages/twenty-website/public/images/releases/{MINOR_VERSION}/
# Commit
git commit -m "Add {VERSION} release changelog"
# Push branch
git push -u origin {VERSION}
```
### 9. Create Pull Request
```bash
# Create PR using GitHub CLI
gh pr create \
--title "Release {VERSION}" \
--body "## Release {VERSION}
This release includes:
- Feature 1
- Feature 2
- Feature 3
Changelog file: \`packages/twenty-website/src/content/releases/{VERSION}.mdx\`
Release date: {DATE}" \
--base main \
--head {VERSION}
```
Or visit: `https://github.com/twentyhq/twenty/pull/new/{VERSION}`
## File Naming Conventions
### Changelog Files
- **Format**: `{MAJOR}.{MINOR}.{PATCH}.mdx`
- **Convention**: One file per complete version
- **Examples**: `1.6.0.mdx`, `1.7.0.mdx`, `2.0.0.mdx`
- **Location**: `packages/twenty-website/src/content/releases/`
### Image Folders
- **Format**: `{MAJOR}.{MINOR}/`
- **Convention**: One folder per minor version (shared across patches)
- **Examples**: `1.6/`, `1.7/`, `2.0/`
- **Location**: `packages/twenty-website/public/images/releases/`
### Image Files
- **Format**: `{VERSION}-descriptive-name.png`
- **Convention**: Kebab-case descriptive names
- **Examples**:
- `1.8.0-workflow-iterator.png`
- `1.8.0-bulk-select.png`
- `1.9.0-new-feature.png`
## Quick Reference Template
Copy and fill this for each release:
```
VERSION: ___________
DATE: ___________
MINOR_VERSION: ___________
Features to document:
1. ___________________________
2. ___________________________
3. ___________________________
Branch name: {VERSION}
Changelog path: packages/twenty-website/src/content/releases/{VERSION}.mdx
Images path: packages/twenty-website/public/images/releases/{MINOR_VERSION}/
```
## Tips
- **Start early**: Begin documenting features as they're developed
- **User perspective**: Write for users, not developers
- **Be concise**: 1-2 sentences per feature
- **Visual first**: Illustrations should showcase the feature clearly
- **Consistent style**: Match tone and structure of previous changelogs
- **Test links**: Verify all image paths work before committing
- **Research thoroughly**: Use codebase search to understand features deeply
+3 -58
View File
@@ -30,18 +30,6 @@ type ButtonProps = {}; // Component props suffix with 'Props'
// ✅ Files and directories - kebab-case
// user-profile.component.tsx
// user-profile.styles.ts
// ❌ NEVER use abbreviations in variable names
// Bad
const users = data.map((u) => u.name);
const field = items.find((f) => f.id === id);
// Good
const users = data.map((user) => user.name);
const field = items.find((item) => item.id === id);
const fieldMetadata = inlineFields.find(
(fieldMetadataItem) => fieldMetadataItem.name === fieldName,
);
```
## Import Organization
@@ -71,11 +59,11 @@ const processUserData = (
): ProcessedUser => {
const processedUser = transformUserData(user);
applyOptions(processedUser, options);
if (callback) {
callback(processedUser);
}
return processedUser;
};
```
@@ -83,7 +71,7 @@ const processUserData = (
## Comments
```typescript
// ✅ Use short-form comments, NOT JSDoc blocks
// ✅ Explain business logic and non-obvious intentions (WHY, not WHAT)
// ✅ Explain business logic and non-obvious intentions
// Apply 15% discount for premium users with orders > $100
const discount = isPremiumUser && orderTotal > 100 ? 0.15 : 0;
@@ -97,55 +85,12 @@ const calculateTotalPrice = (basePrice: number): number => {
// Implementation
};
// ❌ AVOID obvious comments that just describe what code does
// Bad: Get all inline fields dynamically
const { inlineFieldMetadataItems } = useFieldListFieldMetadataItems({...});
// Bad: Define standard fields in display order
const standardFieldOrder = ['startsAt', 'endsAt', 'conferenceLink'];
// Bad: Split fields into standard and custom
const standardFields = standardFieldOrder.map(...)
// ✅ GOOD: Only comment if explaining non-obvious business logic
// Calendar events display standard fields first, then custom fields after participants
// to maintain consistency with the legacy UI behavior
const standardFields = standardFieldOrder.map(...)
// ❌ AVOID JSDoc blocks - use short comments instead
/**
* This style is NOT preferred in this codebase
*/
```
**Comment Guidelines:**
- **DO** comment complex business rules or domain-specific logic
- **DO** comment non-obvious algorithmic decisions
- **DO** add TODOs for future improvements
- **DON'T** comment obvious variable declarations or function calls
- **DON'T** comment what is already clear from well-named variables/functions
- **DON'T** add comments that just repeat what the code says
## Utility Helpers
```typescript
// ✅ Use existing utility helpers instead of manual checks
import { isDefined } from 'twenty-shared/utils';
import { isNonEmptyString, isNonEmptyArray } from '@sniptt/guards';
// ❌ Manual type guards
const validItems = items.filter((item): item is Item => item !== undefined);
const hasValue = value !== null && value !== undefined;
// ✅ Use utility helpers
const validItems = items.filter(isDefined);
const hasValue = isDefined(value);
// Other useful helpers:
// - isDefined(value) - checks !== null && !== undefined
// - isNonEmptyString(value) - checks string is defined and not empty
// - isNonEmptyArray(value) - checks array is defined and has items
```
## Security Patterns
```typescript
// ✅ CSV Export: Always apply security first, then formatting
-39
View File
@@ -69,45 +69,6 @@ beforeEach(() => {
- **Keep tests isolated** - Independent and repeatable
- **70% unit, 20% integration, 10% E2E** - Test pyramid
## Running Tests
### Single Test File Execution
```bash
# ✅ Run a specific test file (PREFERRED - Fast & Efficient)
npx jest path/to/test.test.ts --config=packages/PROJECT/jest.config.mjs
# Key Benefits:
# - Only runs the specific test file (fast)
# - No dependency resolution overhead
# - Immediate feedback for test development
# ✅ Examples:
# Frontend tests (use .test.ts extension)
npx jest packages/twenty-front/src/modules/localization/utils/detection/detectNumberFormat.test.ts --config=packages/twenty-front/jest.config.mjs
# Server tests (use .spec.ts extension)
npx jest packages/twenty-server/src/utils/__test__/is-work-email.spec.ts --config=packages/twenty-server/jest.config.mjs
# ❌ AVOID - This runs ALL tests (slow):
npx nx test twenty-front --testPathPattern=detectNumberFormat.test.ts
# ✅ Run tests in watch mode for development:
npx jest path/to/test.test.ts --config=packages/twenty-front/jest.config.mjs --watch
# ✅ Run with coverage for single file:
npx jest path/to/test.test.ts --config=packages/twenty-front/jest.config.mjs --coverage
```
### Test Suite Execution
```bash
# Run all tests for a project (use sparingly)
npx nx test twenty-front
npx nx test twenty-server
# Run tests matching a pattern
npx jest --testNamePattern="UserService" --config=packages/twenty-front/jest.config.mjs
```
## Common Patterns
```typescript
// Async testing
-8
View File
@@ -1,8 +0,0 @@
{
"setup-worktree": [
"nvm use",
"yarn",
"cp $ROOT_WORKTREE_PATH/packages/twenty-server/.env packages/twenty-server/.env || true",
"cp $ROOT_WORKTREE_PATH/packages/twenty-front/.env packages/twenty-front/.env || true"
]
}
-28
View File
@@ -1,28 +0,0 @@
* text=auto eol=lf
*.ts text eol=lf
*.tsx text eol=lf
*.js text eol=lf
*.jsx text eol=lf
*.json text eol=lf
*.md text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
*.sh text eol=lf
*.mjs text eol=lf
*.cjs text eol=lf
# Patch files may have mixed line endings by design
*.patch -text
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.svg binary
*.woff binary
*.woff2 binary
*.ttf binary
*.eot binary
+4 -4
View File
@@ -1,21 +1,21 @@
# Contributing to Twenty
Thanks for considering contributing to Twenty!
Thanks for considering contributing to Twenty!
Please make sure to go through the [documentation](https://docs.twenty.com) before.
Please make sure to go through the [documentation](https://docs.twenty.com) before.
<br>
## Good first issues
Good first issues are a great way to start contributing and get familiar with the codebase. You can find them on by filtering on the [good first issue](https://github.com/twentyhq/twenty/labels/good%20first%20issue) label.
Good first issues are a great way to start contributing and get familiar with the codebase. You can find them on by filtering on the [good first issue](https://github.com/twentyhq/twenty/labels/good%20first%20issue) label.
## Issue assignment
To avoid conflicts, we follow these guidelines:
1. For `Good First Issue` and `Experienced Contributor` issues without `size: long` labels, we'll merge the first PRs that meet our [code quality standards](https://docs.twenty.com/developers). **We don't assign contributors to these issues**. For `priority: high` issues, our core team will step in within days if no adequate contributions are received.
1. For `Good First Issue` and `Experienced Contributor` issues without `size: long` labels, we'll merge the first PRs that meet our [code quality standards](https://twenty.com/developers). **We don't assign contributors to these issues**. For `priority: high` issues, our core team will step in within days if no adequate contributions are received.
2. For `size: long` Issues, assigned contributors have one week to submit their first draft PR.
## How to Contribute
-15
View File
@@ -1,15 +0,0 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 3
versioning-strategy: "lockfile-only"
assignees:
- "mabdullahabaid"
ignore:
- dependency-name: "@graphql-yoga/nestjs"
- dependency-name: "@nestjs/graphql"
- dependency-name: "@ptc-org/nestjs-query-graphql"
- dependency-name: "typeorm"
-5
View File
@@ -1,13 +1,8 @@
name: CD deploy main
permissions:
contents: read
on:
push:
branches:
- main
jobs:
deploy-main:
timeout-minutes: 3
-5
View File
@@ -1,13 +1,8 @@
name: CD deploy tag
permissions:
contents: read
on:
push:
tags:
- 'v*'
jobs:
deploy-tag:
timeout-minutes: 3
-1
View File
@@ -1,5 +1,4 @@
name: Changed files reusable workflow
on:
workflow_call:
inputs:
+11 -17
View File
@@ -6,9 +6,12 @@ on:
branches:
- main
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
cancel-in-progress: true
env:
MAIN_SERVER_PORT: 3000
@@ -34,7 +37,7 @@ jobs:
needs: changed-files-check
if: needs.changed-files-check.outputs.any_changed == 'true'
timeout-minutes: 45
runs-on: ubuntu-latest
runs-on: depot-ubuntu-24.04-8
services:
postgres:
image: twentycrm/twenty-postgres-spilo
@@ -55,7 +58,7 @@ jobs:
ports:
- 6379:6379
clickhouse:
image: clickhouse/clickhouse-server:25.8.8
image: clickhouse/clickhouse-server:latest
env:
CLICKHOUSE_PASSWORD: clickhousePassword
CLICKHOUSE_URL: "http://default:clickhousePassword@localhost:8123/twenty"
@@ -124,14 +127,13 @@ jobs:
- name: Setup current branch database
run: |
npx nx reset:env twenty-server
# Function to set or update environment variable
set_env_var() {
local var_name="$1"
local var_value="$2"
local env_file="packages/twenty-server/.env"
echo "" >> "$env_file"
if grep -q "^${var_name}=" "$env_file" 2>/dev/null; then
if grep -q "^${var_name}=" "$env_file"; then
sed -i "s|^${var_name}=.*|${var_name}=${var_value}|" "$env_file"
else
echo "${var_name}=${var_value}" >> "$env_file"
@@ -258,16 +260,13 @@ jobs:
run: |
git stash
git checkout origin/main
git reset --hard
git clean -xfd -ff
rm -rf node_modules packages/*/node_modules packages/*/dist dist .nx/cache
git clean -fd
- name: Install dependencies for main branch
uses: ./.github/workflows/actions/yarn-install
- name: Build main branch dependencies
run: |
npx nx reset
npx nx build twenty-shared
npx nx build twenty-emails
@@ -276,15 +275,13 @@ jobs:
- name: Setup main branch database
run: |
npx nx reset:env twenty-server
# Function to set or update environment variable
set_env_var() {
local var_name="$1"
local var_value="$2"
local env_file="packages/twenty-server/.env"
echo "" >> "$env_file"
if grep -q "^${var_name}=" "$env_file" 2>/dev/null; then
if grep -q "^${var_name}=" "$env_file"; then
sed -i "s|^${var_name}=.*|${var_name}=${var_value}|" "$env_file"
else
echo "${var_name}=${var_value}" >> "$env_file"
@@ -293,9 +290,6 @@ jobs:
set_env_var "PG_DATABASE_URL" "postgres://postgres:postgres@localhost:5432/main_branch"
set_env_var "NODE_PORT" "${{ env.MAIN_SERVER_PORT }}"
set_env_var "REDIS_URL" "redis://localhost:6379"
set_env_var "CLICKHOUSE_URL" "http://default:clickhousePassword@localhost:8123/twenty"
set_env_var "CLICKHOUSE_PASSWORD" "clickhousePassword"
npx nx run twenty-server:database:init:prod
npx nx run twenty-server:database:migrate:prod
+2 -51
View File
@@ -1,5 +1,4 @@
name: CI CLI
on:
push:
branches:
@@ -12,7 +11,7 @@ permissions:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
cancel-in-progress: true
jobs:
changed-files-check:
@@ -20,7 +19,6 @@ jobs:
with:
files: |
packages/twenty-cli/**
packages/twenty-server/**
cli-test:
needs: changed-files-check
if: needs.changed-files-check.outputs.any_changed == 'true'
@@ -45,58 +43,11 @@ jobs:
with:
tag: scope:cli
tasks: ${{ matrix.task }}
cli-e2e-test:
timeout-minutes: 30
runs-on: depot-ubuntu-24.04-8
needs: [changed-files-check, cli-test]
if: needs.changed-files-check.outputs.any_changed == 'true'
services:
postgres:
image: twentycrm/twenty-postgres-spilo
env:
PGUSER_SUPERUSER: postgres
PGPASSWORD_SUPERUSER: postgres
ALLOW_NOSSL: 'true'
SPILO_PROVIDER: 'local'
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
redis:
image: redis
ports:
- 6379:6379
env:
NODE_ENV: test
steps:
- name: Fetch custom Github Actions and base branch history
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
- name: Server / Append billing config to .env.test
working-directory: packages/twenty-server
run: |
echo "" >> .env.test
echo "IS_BILLING_ENABLED=true" >> .env.test
echo "BILLING_STRIPE_API_KEY=test-api-key" >> .env.test
echo "BILLING_STRIPE_BASE_PLAN_PRODUCT_ID=test-base-plan-product-id" >> .env.test
echo "BILLING_STRIPE_WEBHOOK_SECRET=test-webhook-secret" >> .env.test
echo "BILLING_PLAN_REQUIRED_LINK=http://localhost:3001/stripe-redirection" >> .env.test
- name: Server / Create Test DB
run: |
PGPASSWORD=postgres psql -h localhost -p 5432 -U postgres -d postgres -c 'CREATE DATABASE "test";'
- name: CLI / Run E2E Tests
run: npx nx test:e2e twenty-cli
ci-cli-status-check:
if: always() && !cancelled()
timeout-minutes: 5
runs-on: ubuntu-latest
needs: [changed-files-check, cli-test, cli-e2e-test]
needs: [changed-files-check, cli-test]
steps:
- name: Fail job if any needs failed
if: contains(needs.*.result, 'failure')
-47
View File
@@ -1,47 +0,0 @@
name: CI Docs
on:
push:
branches:
- main
pull_request:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
changed-files-check:
uses: ./.github/workflows/changed-files.yaml
with:
files: |
package.json
packages/twenty-docs/**
eslint.config.mjs
docs-lint:
needs: changed-files-check
if: needs.changed-files-check.outputs.any_changed == 'true'
timeout-minutes: 10
runs-on: ubuntu-latest
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.11.0
with:
access_token: ${{ github.token }}
- name: Fetch local actions
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
- name: Docs / Lint English MDX files
run: npx eslint "packages/twenty-docs/{developers,user-guide,twenty-ui,getting-started,snippets}/**/*.mdx" --max-warnings 0
+1 -2
View File
@@ -1,5 +1,4 @@
name: CI E2E Playwright Tests
on:
push:
branches:
@@ -12,7 +11,7 @@ permissions:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
cancel-in-progress: true
jobs:
changed-files-check:
+2 -6
View File
@@ -1,8 +1,4 @@
name: CI Emails
permissions:
contents: read
on:
push:
branches:
@@ -12,7 +8,7 @@ on:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
cancel-in-progress: true
jobs:
changed-files-check:
@@ -56,7 +52,7 @@ jobs:
ci-emails-status-check:
if: always() && !cancelled()
timeout-minutes: 5
runs-on: ubuntu-latest
runs-on: depot-ubuntu-24.04-8
needs: [changed-files-check, emails-test]
steps:
- name: Fail job if any needs failed
+5 -8
View File
@@ -1,5 +1,4 @@
name: CI Front
on:
push:
branches:
@@ -12,7 +11,7 @@ permissions:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
cancel-in-progress: true
env:
STORYBOOK_BUILD_CACHE_KEY_FOR_RESTORE_ACTION: storybook-build-depot-ubuntu-24.04-8-runner
@@ -24,7 +23,6 @@ jobs:
with:
files: |
package.json
yarn.lock
packages/twenty-front/**
packages/twenty-ui/**
packages/twenty-shared/**
@@ -95,7 +93,7 @@ jobs:
path: packages/twenty-front/coverage/storybook/coverage-shard-${{matrix.shard}}.json
merge-reports-and-check-coverage:
timeout-minutes: 30
runs-on: ubuntu-latest
runs-on: depot-ubuntu-24.04-8
needs: front-sb-test
env:
PATH_TO_COVERAGE: packages/twenty-front/coverage/storybook
@@ -141,15 +139,14 @@ jobs:
run: |
cd packages/twenty-front
touch .env
echo "" >> .env
echo "REACT_APP_SERVER_BASE_URL=$REACT_APP_SERVER_BASE_URL" >> .env
echo "REACT_APP_SERVER_BASE_URL: $REACT_APP_SERVER_BASE_URL" >> .env
- name: Publish to Chromatic
run: npx nx run twenty-front:chromatic:ci
front-task:
needs: changed-files-check
if: needs.changed-files-check.outputs.any_changed == 'true'
timeout-minutes: 30
runs-on: ubuntu-latest
runs-on: depot-ubuntu-24.04-8
env:
TASK_CACHE_KEY: front-task-${{ matrix.task }}
strategy:
@@ -188,7 +185,7 @@ jobs:
ci-front-status-check:
if: always() && !cancelled()
timeout-minutes: 5
runs-on: ubuntu-latest
runs-on: depot-ubuntu-24.04-8
needs:
[
changed-files-check,
+11 -25
View File
@@ -1,9 +1,4 @@
name: "Release: create"
permissions:
contents: read
pull-requests: write
on:
workflow_dispatch:
inputs:
@@ -18,42 +13,33 @@ on:
default: true
description: Create a release after merging the PR
defaults:
run:
shell: bash --noprofile --norc -euo pipefail {0}
jobs:
create_pr:
timeout-minutes: 10
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v2
with:
ref: ${{ github.event.inputs.ref }}
- name: Sanitize version
id: sanitize
env:
RAW_VERSION: ${{ github.event.inputs.version }}
run: |
VERSION="${RAW_VERSION#v}"
printf 'version=%s\n' "$VERSION" >> "$GITHUB_OUTPUT"
echo version=$(echo ${{ github.event.inputs.version }} | sed 's/^v//') >> $GITHUB_OUTPUT
- name: Update versions
env:
VERSION: ${{ steps.sanitize.outputs.version }}
run: |
printf '%s\n' "$VERSION" > version.txt
echo ${{ steps.sanitize.outputs.version }} > version.txt
- name: Create Pull Request
uses: peter-evans/create-pull-request@v6
with:
branch: release/${{ steps.sanitize.outputs.version }}
commit-message: "chore: release v${{ steps.sanitize.outputs.version }}"
committer: Github Action Deploy <github-action-deploy@twenty.com>
author: Github Action Deploy <github-action-deploy@twenty.com>
title: Release v${{ steps.sanitize.outputs.version }}
labels: |
release
${{ github.event.inputs.create_release == true && 'create_release' || '' }}
branch: release/${{ steps.sanitize.outputs.version }}
commit-message: "chore: release v${{ steps.sanitize.outputs.version }}"
committer: Github Action Deploy <github-action-deploy@twenty.com>
author: Github Action Deploy <github-action-deploy@twenty.com>
title: Release v${{ steps.sanitize.outputs.version }}
labels: |
release
${{ github.event.inputs.create_release == true && 'create_release' || '' }}
+7 -22
View File
@@ -1,17 +1,9 @@
name: "Release: on merge"
permissions:
contents: write
on:
pull_request:
types:
- closed
defaults:
run:
shell: bash --noprofile --norc -euo pipefail {0}
jobs:
tag_and_release:
timeout-minutes: 10
@@ -20,40 +12,33 @@ jobs:
steps:
- name: Check PR Author
id: check_author
env:
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
run: |
set -euo pipefail
if [[ "$PR_AUTHOR" != "github-actions[bot]" ]]; then
echo "PR author ($PR_AUTHOR) is not trusted. Exiting."
if [[ "${{ github.event.pull_request.user.login }}" != "github-actions[bot]" ]]; then
echo "PR author (${AUTHOR}) is not trusted. Exiting."
exit 1
fi
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v2
with:
ref: main
- name: Get version from PR title
id: extract_version
env:
PR_TITLE: ${{ github.event.pull_request.title }}
run: |
set -euo pipefail
VERSION=$(printf '%s' "$PR_TITLE" | sed -n 's/.*Release v\([0-9][0-9.]*\).*/\1/p')
VERSION=$(echo "${{ github.event.pull_request.title }}" | sed -n 's/.*Release v\([0-9.]*\).*/\1/p')
if [ -z "$VERSION" ]; then
echo "No valid version found in PR title. Exiting."
exit 1
fi
printf 'VERSION=%s\n' "$VERSION" >> "$GITHUB_ENV"
echo "VERSION=$VERSION" >> $GITHUB_ENV
- name: Push new tag
run: |
set -euo pipefail
git config --global user.name 'Github Action Deploy'
git config --global user.email 'github-action-deploy@twenty.com'
git tag "v${{ env.VERSION }}"
git push origin "v${{ env.VERSION }}"
git tag v${{ env.VERSION }}
git push origin v${{ env.VERSION }}
- uses: release-drafter/release-drafter@v5
if: contains(github.event.pull_request.labels.*.name, 'create_release')
+13 -16
View File
@@ -1,5 +1,4 @@
name: CI Server
on:
push:
branches:
@@ -12,7 +11,7 @@ permissions:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
cancel-in-progress: true
env:
SERVER_SETUP_CACHE_KEY: server-setup
@@ -23,7 +22,6 @@ jobs:
with:
files: |
package.json
yarn.lock
packages/twenty-server/**
packages/twenty-front/src/generated/**
packages/twenty-front/src/generated-metadata/**
@@ -117,7 +115,7 @@ jobs:
echo "$CORE_MIGRATION_OUTPUT"
rm -f packages/twenty-server/*core-migration-check.ts
exit 1
fi
- name: GraphQL / Check for Pending Generation
@@ -126,13 +124,13 @@ jobs:
npx nx run twenty-front:graphql:generate
npx nx run twenty-front:graphql:generate --configuration=metadata
# Check if GraphQL generated files were modified
if ! git diff --quiet -- packages/twenty-front/src/generated packages/twenty-front/src/generated-metadata; then
# Check if any files were modified
if ! git diff --quiet; then
echo "::error::GraphQL schema changes detected. Please run 'npx nx run twenty-front:graphql:generate' and 'npx nx run twenty-front:graphql:generate --configuration=metadata' and commit the changes."
echo ""
echo "The following GraphQL schema changes were detected:"
echo "==================================================="
git diff -- packages/twenty-front/src/generated packages/twenty-front/src/generated-metadata
git diff
echo "==================================================="
echo ""
echo "Please run 'npx nx run twenty-front:graphql:generate' and 'npx nx run twenty-front:graphql:generate --configuration=metadata' and commit the changes."
@@ -171,7 +169,7 @@ jobs:
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4, 5]
shard: [1, 2, 3, 4]
services:
postgres:
image: twentycrm/twenty-postgres-spilo
@@ -192,7 +190,7 @@ jobs:
ports:
- 6379:6379
clickhouse:
image: clickhouse/clickhouse-server:25.8.8
image: clickhouse/clickhouse-server:latest
env:
CLICKHOUSE_PASSWORD: clickhousePassword
CLICKHOUSE_URL: "http://default:clickhousePassword@localhost:8123/twenty"
@@ -200,16 +198,16 @@ jobs:
- 8123:8123
- 9000:9000
options: >-
--health-cmd "clickhouse-client --host=localhost --port=9000 --user=default --password=clickhousePassword --query='SELECT 1'"
--health-interval 10s
--health-timeout 5s
--health-cmd "clickhouse-client --host=localhost --port=9000 --user=default --password=clickhousePassword --query='SELECT 1'"
--health-interval 10s
--health-timeout 5s
--health-retries 5
env:
NODE_ENV: test
ANALYTICS_ENABLED: true
CLICKHOUSE_URL: "http://default:clickhousePassword@localhost:8123/twenty"
CLICKHOUSE_PASSWORD: clickhousePassword
SHARD_COUNTER: 5
SHARD_COUNTER: 4
steps:
- name: Fetch custom Github Actions and base branch history
uses: actions/checkout@v4
@@ -219,7 +217,6 @@ jobs:
uses: ./.github/workflows/actions/yarn-install
- name: Update .env.test for integrations tests
run: |
echo "" >> .env.test
echo "IS_BILLING_ENABLED=true" >> .env.test
echo "BILLING_STRIPE_API_KEY=test-api-key" >> .env.test
echo "BILLING_STRIPE_BASE_PLAN_PRODUCT_ID=test-base-plan-product-id" >> .env.test
@@ -252,9 +249,9 @@ jobs:
ci-server-status-check:
if: always() && !cancelled()
timeout-minutes: 5
runs-on: ubuntu-latest
runs-on: depot-ubuntu-24.04-8
needs: [changed-files-check, server-setup, server-test, server-integration-test]
steps:
- name: Fail job if any needs failed
- name: Fail job if any needs failed
if: contains(needs.*.result, 'failure')
run: exit 1
+1 -2
View File
@@ -1,5 +1,4 @@
name: CI Shared
on:
push:
branches:
@@ -12,7 +11,7 @@ permissions:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
cancel-in-progress: true
jobs:
changed-files-check:
@@ -4,7 +4,7 @@ on:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
cancel-in-progress: true
jobs:
changed-files-check:
@@ -33,7 +33,6 @@ jobs:
echo "Setting up .env file..."
cp .env.example .env
echo "Generating secrets..."
echo "" >> .env
echo "# === Randomly generated secrets ===" >>.env
echo "APP_SECRET=$(openssl rand -base64 32)" >>.env
echo "PGPASSWORD_SUPERUSER=$(openssl rand -hex 16)" >>.env
-3
View File
@@ -1,5 +1,4 @@
name: CI Utils
on:
# it's usually not recommended to use pull_request_target
# but we consider it's safe here if we keep the same steps
@@ -7,7 +6,6 @@ on:
# and: https://github.com/facebook/react-native/pull/34370/files
pull_request_target:
types: [opened, synchronize, reopened, closed]
permissions:
actions: write
checks: write
@@ -15,7 +13,6 @@ permissions:
issues: write
pull-requests: write
statuses: write
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
# We don't cancel in-progress because this workflow is triggered on
+1 -5
View File
@@ -1,8 +1,4 @@
name: CI Website
permissions:
contents: read
on:
push:
branches:
@@ -12,7 +8,7 @@ on:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
cancel-in-progress: true
jobs:
changed-files-check:
-155
View File
@@ -1,155 +0,0 @@
name: 'Pull docs translations from Crowdin'
permissions:
contents: write
pull-requests: write
on:
schedule:
- cron: '0 */2 * * *' # Every two hours
workflow_dispatch:
inputs:
force_pull:
description: 'Force pull translations regardless of status'
required: false
type: boolean
default: false
workflow_call:
inputs:
force_pull:
description: 'Force pull translations regardless of status'
required: false
type: boolean
default: false
pull_request:
paths:
- 'packages/twenty-docs/**'
- 'crowdin.yml'
- '.github/workflows/docs-i18n-pull.yaml'
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
pull_docs_translations:
name: Pull docs translations
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
token: ${{ github.token }}
ref: ${{ github.event_name == 'pull_request' && github.head_ref || github.ref }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
cache-dependency-path: 'yarn.lock'
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
cache-dependency-path: 'yarn.lock'
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Setup i18n branch
if: github.event_name != 'pull_request'
run: |
git fetch origin i18n || true
git checkout -B i18n origin/i18n || git checkout -b i18n
- name: Configure git
run: |
git config --global user.name 'github-actions'
git config --global user.email 'github-actions@twenty.com'
- name: Stash any changes before pulling translations
if: github.event_name != 'pull_request'
run: |
git add .
git stash || true
- name: Pull translated docs from Crowdin
if: github.event_name != 'pull_request' && (inputs.force_pull == true || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
uses: crowdin/github-action@v2
with:
upload_sources: false
upload_translations: false
download_translations: true
source: 'packages/twenty-docs/**/*.mdx'
translation: 'packages/twenty-docs/l/%two_letters_code%/**/%original_file_name%'
export_only_approved: false
localization_branch_name: i18n
base_url: 'https://twenty.api.crowdin.com'
skip_untranslated_files: true
push_translations: false
create_pull_request: false
skip_ref_checkout: true
dryrun_action: false
env:
GITHUB_TOKEN: ${{ github.token }}
CROWDIN_PROJECT_ID: '1'
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
- name: Fix file permissions
if: github.event_name != 'pull_request'
run: sudo chown -R runner:docker . || true
- name: Fix translated documentation links
run: bash packages/twenty-docs/scripts/fix-translated-links.sh
- name: Regenerate navigation template
if: github.event_name == 'pull_request'
run: yarn docs:generate-navigation-template
- name: Regenerate docs.json
run: yarn docs:generate
- name: Commit artifacts to pull request branch
if: github.event_name == 'pull_request'
run: |
git add packages/twenty-docs/docs.json packages/twenty-docs/navigation/navigation.template.json
if git diff --staged --quiet --exit-code; then
echo "No navigation/doc changes to commit."
exit 0
fi
git commit -m "chore: sync docs artifacts"
git push origin HEAD:${{ github.head_ref }}
- name: Check for changes and commit
if: github.event_name != 'pull_request'
id: check_changes
run: |
git add .
if ! git diff --staged --quiet --exit-code; then
git commit -m "chore: update docs translations from Crowdin and fix internal links"
echo "changes_detected=true" >> $GITHUB_OUTPUT
else
echo "changes_detected=false" >> $GITHUB_OUTPUT
fi
- name: Push changes
if: github.event_name != 'pull_request' && steps.check_changes.outputs.changes_detected == 'true'
run: git push origin HEAD:i18n
- name: Create pull request
if: github.event_name != 'pull_request' && steps.check_changes.outputs.changes_detected == 'true'
run: |
if git diff --name-only origin/main..HEAD | grep -q .; then
gh pr create -B main -H i18n --title 'i18n - docs translations' --body 'Created by Github action' || true
else
echo "No file differences between branches, skipping PR creation"
fi
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-68
View File
@@ -1,68 +0,0 @@
name: 'Push docs to Crowdin'
permissions:
contents: write
on:
workflow_dispatch:
workflow_call:
push:
branches: ['main', 'docs-localized-navigation']
paths:
- 'packages/twenty-docs/**/*.mdx'
- '!packages/twenty-docs/fr/**'
- 'crowdin.yml'
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
push_docs:
name: Push documentation to Crowdin
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
token: ${{ github.token }}
ref: ${{ github.ref }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
cache-dependency-path: 'yarn.lock'
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Generate navigation template for Crowdin
run: yarn docs:generate-navigation-template
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
cache-dependency-path: 'yarn.lock'
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Generate navigation template for Crowdin
run: yarn docs:generate-navigation-template
- name: Upload docs to Crowdin
uses: crowdin/github-action@v2
with:
upload_sources: true
upload_translations: false
download_translations: false
localization_branch_name: i18n
base_url: 'https://twenty.api.crowdin.com'
env:
CROWDIN_PROJECT_ID: 1
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
+7 -9
View File
@@ -3,10 +3,6 @@
name: 'Pull translations from Crowdin'
permissions:
contents: write
pull-requests: write
on:
schedule:
- cron: '0 */2 * * *' # Every two hours.
@@ -27,12 +23,16 @@ on:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
cancel-in-progress: true
jobs:
pull_translations:
name: Pull translations
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -74,8 +74,6 @@ jobs:
upload_sources: false
upload_translations: false
download_translations: true
source: '**/en.po'
translation: '%original_path%/%locale%.po'
export_only_approved: false
localization_branch_name: i18n
base_url: 'https://twenty.api.crowdin.com'
@@ -93,7 +91,7 @@ jobs:
GITHUB_TOKEN: ${{ github.token }}
CROWDIN_PROJECT_ID: '1'
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
# As the files are extracted from a Docker container, they belong to root:root
# We need to fix this before the next steps
- name: Fix file permissions
@@ -105,7 +103,7 @@ jobs:
# if: inputs.force_pull || steps.compile_translations_strict.outcome == 'failure'
run: |
npx nx run twenty-server:lingui:compile
npx nx run twenty-emails:lingui:compile
npx nx run twenty-emails:lingui:compile
npx nx run twenty-front:lingui:compile
git status
git config --global user.name 'github-actions'
+4 -5
View File
@@ -1,9 +1,5 @@
name: 'Push translations to Crowdin'
permissions:
contents: write
pull-requests: write
on:
workflow_dispatch:
workflow_call:
@@ -12,12 +8,15 @@ on:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
cancel-in-progress: true
jobs:
extract_translations:
name: Extract and upload translations
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- name: Checkout
uses: actions/checkout@v4
+4 -5
View File
@@ -1,10 +1,5 @@
name: 'Preview Environment Dispatch'
permissions:
contents: write
actions: write
pull-requests: read
on:
# Using pull_request_target instead of pull_request to have access to secrets for external contributors
# Security note: This is safe because we're only using the repository-dispatch action with limited scope
@@ -24,6 +19,10 @@ concurrency:
jobs:
trigger-preview:
permissions:
contents: write
actions: write
pull-requests: read
if: github.event.action == 'opened' || github.event.action == 'synchronize' || github.event.action == 'reopened' || (github.event.action == 'labeled' && github.event.label.name == 'preview-app')
timeout-minutes: 5
runs-on: ubuntu-latest
@@ -1,9 +1,5 @@
name: 'Preview Environment Keep Alive'
permissions:
contents: read
pull-requests: write
on:
repository_dispatch:
types: [preview-environment]
@@ -37,7 +33,6 @@ jobs:
cp packages/twenty-docker/.env.example packages/twenty-docker/.env
echo "Generating secrets..."
echo "" >> packages/twenty-docker/.env
echo "# === Randomly generated secrets ===" >> packages/twenty-docker/.env
echo "APP_SECRET=$(openssl rand -base64 32)" >> packages/twenty-docker/.env
echo "PG_DATABASE_PASSWORD=$(openssl rand -hex 16)" >> packages/twenty-docker/.env
@@ -61,7 +56,6 @@ jobs:
# Update the SERVER_URL with the tunnel URL
echo "Setting SERVER_URL to ${{ steps.expose-tunnel.outputs.tunnel-url }}"
sed -i '/SERVER_URL=/d' .env
echo "" >> .env
echo "SERVER_URL=${{ steps.expose-tunnel.outputs.tunnel-url }}" >> .env
# Start the services
-24
View File
@@ -1,24 +0,0 @@
{
"mcpServers": {
"postgres": {
"type": "stdio",
"command": "uv",
"args": ["run", "postgres-mcp", "--access-mode=unrestricted"],
"env": {
"DATABASE_URI": "${PG_DATABASE_URL}"
}
},
"playwright": {
"type": "stdio",
"command": "npx",
"args": ["@playwright/mcp@latest", "--no-sandbox", "--headless"],
"env": {}
},
"context7": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@upstash/context7-mcp"],
"env": {}
}
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
{
"singleQuote": true,
"trailingComma": "all",
"endOfLine": "lf"
}
"endOfLine": "auto"
}
+14 -7
View File
@@ -8,7 +8,11 @@
"runtimeVersion": "24.5",
"request": "launch",
"runtimeExecutable": "npx",
"runtimeArgs": ["nx", "run", "twenty-server:start"],
"runtimeArgs": [
"nx",
"run",
"twenty-server:start"
],
"outputCapture": "std",
"internalConsoleOptions": "openOnSessionStart",
"console": "internalConsole",
@@ -19,7 +23,11 @@
"type": "node",
"request": "launch",
"runtimeExecutable": "npx",
"runtimeArgs": ["nx", "run", "twenty-server:worker"],
"runtimeArgs": [
"nx",
"run",
"twenty-server:worker"
],
"outputCapture": "std",
"internalConsoleOptions": "openOnSessionStart",
"console": "internalConsole",
@@ -66,15 +74,14 @@
"--",
"--config",
"./jest-integration.config.ts",
"${relativeFile}",
"--silent=false"
"${relativeFile}"
],
"cwd": "${workspaceFolder}/packages/twenty-server",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"env": {
"NODE_ENV": "test"
}
},
},
{
"type": "node",
@@ -95,7 +102,7 @@
"internalConsoleOptions": "neverOpen",
"env": {
"NODE_ENV": "test"
}
},
}
]
}
}
+1 -3
View File
@@ -1,8 +1,6 @@
{
"editor.formatOnSave": false,
"files.eol": "\n",
"files.insertFinalNewline": true,
"files.trimTrailingWhitespace": true,
"files.eol": "auto",
"[typescript]": {
"editor.formatOnSave": false,
"editor.codeActionsOnSave": {
+3 -8
View File
@@ -29,9 +29,6 @@ npx nx run twenty-server:test:integration:with-db-reset # Integration tests wit
# Storybook
npx nx storybook:build twenty-front # Build Storybook
npx nx storybook:serve-and-test:static twenty-front # Run Storybook tests
When testing the UI end to end, click on "Continue with Email" and use the prefilled credentials.
```
### Code Quality
@@ -65,10 +62,10 @@ npx nx run twenty-server:database:init:prod # Initialize database
npx nx run twenty-server:database:migrate:prod # Run migrations
# Generate migration
npx nx run twenty-server:typeorm migration:generate src/database/typeorm/core/migrations/common/[name] -d src/database/typeorm/core/core.datasource.ts
npx nx run twenty-server:typeorm migration:generate src/database/typeorm/core/migrations/[name] -d src/database/typeorm/core/core.datasource.ts
# Sync metadata
npx nx run twenty-server:command workspace:sync-metadata
npx nx run twenty-server:command workspace:sync-metadata -f
```
### GraphQL
@@ -125,8 +122,6 @@ packages/
## Development Workflow
IMPORTANT: Use Context7 for code generation, setup or configuration steps, or library/API documentation. Automatically use the Context7 MCP tools to resolve library IDs and get library docs without waiting for explicit requests.
### Before Making Changes
1. Always run linting and type checking after code changes
2. Test changes with relevant test suites
@@ -149,4 +144,4 @@ IMPORTANT: Use Context7 for code generation, setup or configuration steps, or li
- `nx.json` - Nx workspace configuration with task definitions
- `tsconfig.base.json` - Base TypeScript configuration
- `package.json` - Root package with workspace definitions
- `.cursor/rules/` - Development guidelines and best practices
- `.cursor/rules/` - Development guidelines and best practices
+10 -5
View File
@@ -3,7 +3,8 @@ DOCKER_NETWORK=twenty_network
ensure-docker-network:
docker network inspect $(DOCKER_NETWORK) >/dev/null 2>&1 || docker network create $(DOCKER_NETWORK)
postgres-on-docker: ensure-docker-network
postgres-on-docker:
make ensure-docker-network
docker run -d --network $(DOCKER_NETWORK) \
--name twenty_pg \
-e POSTGRES_USER=postgres \
@@ -21,13 +22,16 @@ postgres-on-docker: ensure-docker-network
-c "CREATE DATABASE \"default\" WITH OWNER postgres;" \
-c "CREATE DATABASE \"test\" WITH OWNER postgres;"
redis-on-docker: ensure-docker-network
redis-on-docker:
make ensure-docker-network
docker run -d --network $(DOCKER_NETWORK) --name twenty_redis -p 6379:6379 redis/redis-stack-server:latest
clickhouse-on-docker: ensure-docker-network
clickhouse-on-docker:
make ensure-docker-network
docker run -d --network $(DOCKER_NETWORK) --name twenty_clickhouse -p 8123:8123 -p 9000:9000 -e CLICKHOUSE_PASSWORD=devPassword clickhouse/clickhouse-server:latest \
grafana-on-docker: ensure-docker-network
grafana-on-docker:
make ensure-docker-network
docker run -d --network $(DOCKER_NETWORK) \
--name twenty_grafana \
-p 4000:3000 \
@@ -37,7 +41,8 @@ grafana-on-docker: ensure-docker-network
-v $(PWD)/packages/twenty-docker/grafana/provisioning/datasources:/etc/grafana/provisioning/datasources \
grafana/grafana-oss:latest
opentelemetry-collector-on-docker: ensure-docker-network
opentelemetry-collector-on-docker:
make ensure-docker-network
docker run -d --network $(DOCKER_NETWORK) \
--name twenty_otlp_collector \
-p 4317:4317 \
+11 -9
View File
@@ -1,3 +1,5 @@
<br />
<p align="center">
<a href="https://www.twenty.com">
<img src="./packages/twenty-website/public/images/core/logo.svg" width="100px" alt="Twenty logo" />
@@ -6,7 +8,7 @@
<h2 align="center" >The #1 Open-Source CRM </h2>
<p align="center"><a href="https://twenty.com">🌐 Website</a> · <a href="https://docs.twenty.com">📚 Documentation</a> · <a href="https://github.com/orgs/twentyhq/projects/1"><img src="./packages/twenty-website/public/images/readme/planner-icon.svg" width="12" height="12"/> Roadmap </a> · <a href="https://discord.gg/cx5n4Jzs57"><img src="./packages/twenty-website/public/images/readme/discord-icon.svg" width="12" height="12"/> Discord</a> · <a href="https://www.figma.com/file/xt8O9mFeLl46C5InWwoMrN/Twenty"><img src="./packages/twenty-website/public/images/readme/figma-icon.png" width="12" height="12"/> Figma</a></p>
<p align="center"><a href="https://twenty.com">🌐 Website</a> · <a href="https://twenty.com/developers">📚 Documentation</a> · <a href="https://github.com/orgs/twentyhq/projects/1"><img src="./packages/twenty-website/public/images/readme/planner-icon.svg" width="12" height="12"/> Roadmap </a> · <a href="https://discord.gg/cx5n4Jzs57"><img src="./packages/twenty-website/public/images/readme/discord-icon.svg" width="12" height="12"/> Discord</a> · <a href="https://www.figma.com/file/xt8O9mFeLl46C5InWwoMrN/Twenty"><img src="./packages/twenty-website/public/images/readme/figma-icon.png" width="12" height="12"/> Figma</a></p>
<br />
@@ -22,11 +24,11 @@
<br />
# Installation
# Installation
See:
🚀 [Self-hosting](https://docs.twenty.com/developers/self-hosting/docker-compose)
🖥️ [Local Setup](https://docs.twenty.com/developers/local-setup)
See:
🚀 [Self-hosting](https://twenty.com/developers/section/self-hosting)
🖥️ [Local Setup](https://twenty.com/developers/local-setup)
# Does the world need another CRM?
@@ -42,7 +44,7 @@ We built Twenty for three reasons:
# What You Can Do With Twenty
Please feel free to flag any specific needs you have by creating an issue.
Please feel free to flag any specific needs you have by creating an issue.
Below are a few features we have implemented to date:
@@ -129,7 +131,7 @@ Below are a few features we have implemented to date:
- Star the repo
- Subscribe to releases (watch -> custom -> releases)
- Follow us on [Twitter](https://twitter.com/twentycrm) or [LinkedIn](https://www.linkedin.com/company/twenty/)
- Follow us on [Twitter](https://twitter.com/twentycrm) or [LinkedIn](https://www.linkedin.com/company/twenty/)
- Join our [Discord](https://discord.gg/cx5n4Jzs57)
- Improve translations on [Crowdin](https://twenty.crowdin.com/twenty)
- [Contributions](https://github.com/twentyhq/twenty/contribute) are, of course, most welcome!
- Improve translations on [Crowdin](https://twenty.crowdin.com/twenty)
- [Contributions](https://github.com/twentyhq/twenty/contribute) are, of course, most welcome!
+1 -33
View File
@@ -27,37 +27,5 @@ files: [
# e.g. "/resources/%two_letters_code%/%original_file_name%"
#
"translation": "%original_path%/%locale%.po",
},
{
#
# MDX documentation files - user-guide
# Using md type to preserve JSX component structure
# This prevents Crowdin from reformatting <Warning>, <Accordion>, etc.
#
"source": "packages/twenty-docs/user-guide/**/*.mdx",
"translation": "packages/twenty-docs/l/%two_letters_code%/user-guide/**/%original_file_name%",
},
{
#
# MDX documentation files - developers
# Using md type to preserve JSX component structure
#
"source": "packages/twenty-docs/developers/**/*.mdx",
"translation": "packages/twenty-docs/l/%two_letters_code%/developers/**/%original_file_name%",
},
{
#
# MDX documentation files - twenty-ui
# Using md type to preserve JSX component structure
#
"source": "packages/twenty-docs/twenty-ui/**/*.mdx",
"translation": "packages/twenty-docs/l/%two_letters_code%/twenty-ui/**/%original_file_name%",
},
{
#
# Navigation labels template - translated into per-locale navigation.json
#
"source": "packages/twenty-docs/navigation/navigation.template.json",
"translation": "packages/twenty-docs/l/%two_letters_code%/navigation.json",
}
]
]
+10 -42
View File
@@ -4,7 +4,6 @@ import typescriptEslint from '@typescript-eslint/eslint-plugin';
import typescriptParser from '@typescript-eslint/parser';
import importPlugin from 'eslint-plugin-import';
import linguiPlugin from 'eslint-plugin-lingui';
import * as mdxPlugin from 'eslint-plugin-mdx';
import preferArrowPlugin from 'eslint-plugin-prefer-arrow';
import prettierPlugin from 'eslint-plugin-prettier';
import unicornPlugin from 'eslint-plugin-unicorn';
@@ -20,28 +19,27 @@ export default [
// Global ignores
{
ignores: ['**/node_modules/**'],
ignores: [
'**/node_modules/**',
],
},
// Base configuration for all files
{
files: ['**/*.{js,jsx,ts,tsx}'],
plugins: {
prettier: prettierPlugin,
lingui: linguiPlugin,
'prettier': prettierPlugin,
'lingui': linguiPlugin,
'@nx': nxPlugin,
'prefer-arrow': preferArrowPlugin,
import: importPlugin,
'import': importPlugin,
'unused-imports': unusedImportsPlugin,
unicorn: unicornPlugin,
'unicorn': unicornPlugin,
},
rules: {
// General rules
'func-style': ['error', 'declaration', { allowArrowFunctions: true }],
'no-console': [
'warn',
{ allow: ['group', 'groupCollapsed', 'groupEnd'] },
],
'no-console': ['warn', { allow: ['group', 'groupCollapsed', 'groupEnd'] }],
'no-control-regex': 0,
'no-debugger': 'error',
'no-duplicate-imports': 'error',
@@ -55,14 +53,6 @@ export default [
enforceBuildableLibDependency: true,
allow: [],
depConstraints: [
{
sourceTag: 'scope:apps',
onlyDependOnLibsWithTags: ['scope:apps', 'scope:sdk'],
},
{
sourceTag: 'scope:sdk',
onlyDependOnLibsWithTags: ['scope:sdk', 'scope:shared'],
},
{
sourceTag: 'scope:shared',
onlyDependOnLibsWithTags: ['scope:shared'],
@@ -133,9 +123,9 @@ export default [
'@typescript-eslint/ban-ts-comment': 'error',
'@typescript-eslint/consistent-type-imports': [
'error',
{
{
prefer: 'type-imports',
fixStyle: 'inline-type-imports',
fixStyle: 'inline-type-imports'
},
],
'@typescript-eslint/explicit-function-return-type': 'off',
@@ -192,26 +182,4 @@ export default [
parser: jsoncParser,
},
},
// MDX files
{
...mdxPlugin.flat,
plugins: {
...mdxPlugin.flat.plugins,
'@nx': nxPlugin,
},
},
mdxPlugin.flatCodeBlocks,
{
files: ['**/*.mdx'],
rules: {
'no-unused-vars': 'off',
'unused-imports/no-unused-imports': 'off',
'unused-imports/no-unused-vars': 'off',
// Enforce JSX tags on separate lines to prevent Crowdin translation issues
'@nx/workspace-mdx-component-newlines': 'error',
// Disallow angle bracket placeholders to prevent Crowdin translation errors
'@nx/workspace-no-angle-bracket-placeholders': 'error',
},
},
];
+4 -4
View File
@@ -36,7 +36,7 @@
"dependsOn": ["^build"]
},
"start": {
"cache": false,
"cache": true,
"dependsOn": ["^build"]
},
"lint": {
@@ -133,7 +133,7 @@
"outputs": ["{projectRoot}/{options.output-dir}"],
"options": {
"cwd": "{projectRoot}",
"command": "VITE_DISABLE_TYPESCRIPT_CHECKER=true storybook build --test",
"command": "VITE_DISABLE_TYPESCRIPT_CHECKER=true VITE_DISABLE_ESLINT_CHECKER=true storybook build --test",
"output-dir": "storybook-static",
"config-dir": ".storybook"
},
@@ -234,7 +234,7 @@
"command": "nx storybook:build {projectName}",
"forwardAllArgs": false
},
"chromatic --storybook-build-dir=storybook-static {args.ci}"
"cross-var chromatic --project-token=$CHROMATIC_PROJECT_TOKEN --storybook-build-dir=storybook-static {args.ci}"
],
"parallel": false
},
@@ -280,7 +280,7 @@
}
},
"installation": {
"version": "22.0.3"
"version": "21.3.11"
},
"generators": {
"@nx/react": {
+33 -22
View File
@@ -2,23 +2,26 @@
"private": true,
"dependencies": {
"@apollo/client": "^3.7.17",
"@date-fns/tz": "^1.4.1",
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@floating-ui/react": "^0.24.3",
"@linaria/core": "^6.2.0",
"@linaria/react": "^6.2.1",
"@radix-ui/colors": "^3.0.0",
"@react-email/components": "0.0.35",
"@react-email/render": "0.0.17",
"@sentry/profiling-node": "^9.26.0",
"@sentry/react": "^9.26.0",
"@sniptt/guards": "^0.2.0",
"@tabler/icons-react": "^3.31.0",
"@wyw-in-js/vite": "^0.7.0",
"add": "^2.0.6",
"archiver": "^7.0.1",
"danger-plugin-todos": "^1.3.1",
"date-fns": "^2.30.0",
"date-fns-tz": "^2.0.0",
"deep-equal": "^2.2.2",
"dotenv-cli": "^7.2.1",
"drizzle-orm": "^0.29.3",
"file-type": "16.5.4",
"framer-motion": "^11.18.0",
"fuse.js": "^7.1.0",
@@ -39,10 +42,13 @@
"lodash.mapvalues": "^4.6.0",
"lodash.merge": "^4.6.2",
"lodash.omit": "^4.5.0",
"lodash.pick": "^4.4.0",
"lodash.pickby": "^4.6.0",
"lodash.snakecase": "^4.1.1",
"lodash.upperfirst": "^4.3.1",
"microdiff": "^1.3.2",
"moize": "^6.1.6",
"patch-package": "^8.0.0",
"planer": "^1.2.0",
"pluralize": "^8.0.0",
"react": "^18.2.0",
@@ -51,6 +57,8 @@
"react-router-dom": "^6.4.4",
"react-tooltip": "^5.13.1",
"recoil": "^0.7.7",
"rehype-slug": "^6.0.0",
"remark-behead": "^3.1.0",
"remark-gfm": "^3.0.1",
"rxjs": "^7.2.0",
"semver": "^7.5.4",
@@ -63,7 +71,7 @@
"uuid": "^9.0.0",
"vite-tsconfig-paths": "^4.2.1",
"xlsx-ugnis": "^0.19.3",
"zod": "^4.1.11"
"zod": "3.23.8"
},
"devDependencies": {
"@babel/core": "^7.14.5",
@@ -75,14 +83,15 @@
"@graphql-codegen/typescript": "^3.0.4",
"@graphql-codegen/typescript-operations": "^3.0.4",
"@graphql-codegen/typescript-react-apollo": "^3.3.7",
"@nx/eslint": "22.0.3",
"@nx/eslint-plugin": "22.0.3",
"@nx/jest": "22.0.3",
"@nx/js": "22.0.3",
"@nx/react": "22.0.3",
"@nx/storybook": "22.0.3",
"@nx/vite": "22.0.3",
"@nx/web": "22.0.3",
"@nx/eslint": "21.3.11",
"@nx/eslint-plugin": "21.3.11",
"@nx/jest": "21.3.11",
"@nx/js": "21.3.11",
"@nx/react": "21.3.11",
"@nx/storybook": "21.3.11",
"@nx/vite": "21.3.11",
"@nx/web": "21.3.11",
"@playwright/test": "^1.46.0",
"@sentry/types": "^8",
"@storybook/addon-actions": "8.6.14",
"@storybook/addon-coverage": "^1.0.0",
@@ -114,6 +123,7 @@
"@types/express": "^4.17.13",
"@types/fs-extra": "^11.0.4",
"@types/graphql-fields": "^1.3.6",
"@types/imapflow": "^1.0.21",
"@types/inquirer": "^9.0.9",
"@types/jest": "^30.0.0",
"@types/lodash.camelcase": "^4.3.7",
@@ -127,9 +137,11 @@
"@types/lodash.kebabcase": "^4.1.7",
"@types/lodash.mapvalues": "^4.6.9",
"@types/lodash.omit": "^4.5.9",
"@types/lodash.pick": "^4.3.7",
"@types/lodash.pickby": "^4.6.9",
"@types/lodash.snakecase": "^4.1.7",
"@types/lodash.upperfirst": "^4.3.7",
"@types/mailparser": "^3.4.6",
"@types/ms": "^0.7.31",
"@types/node": "^24.0.0",
"@types/passport-google-oauth20": "^2.0.11",
@@ -145,18 +157,19 @@
"@typescript-eslint/parser": "^8.39.0",
"@typescript-eslint/utils": "^8.39.0",
"@vitejs/plugin-react-swc": "3.11.0",
"@vitest/ui": "1.4.0",
"@yarnpkg/types": "^4.0.0",
"chromatic": "^6.18.0",
"concurrently": "^8.2.2",
"danger": "^13.0.4",
"dotenv-cli": "^7.4.4",
"esbuild": "^0.25.10",
"cross-var": "^1.1.0",
"danger": "^11.3.0",
"dotenv-cli": "^7.2.1",
"esbuild": "^0.23.0",
"eslint": "^9.32.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-lingui": "^0.9.0",
"eslint-plugin-mdx": "^3.6.2",
"eslint-plugin-prefer-arrow": "^1.2.3",
"eslint-plugin-prettier": "^5.1.2",
"eslint-plugin-project-structure": "^3.9.1",
@@ -175,7 +188,8 @@
"jsdom": "~22.1.0",
"msw": "^2.0.11",
"msw-storybook-addon": "^2.0.5",
"nx": "22.0.3",
"nx": "21.3.11",
"playwright": "^1.46.0",
"prettier": "^3.1.1",
"raw-loader": "^4.0.2",
"rimraf": "^5.0.5",
@@ -193,7 +207,8 @@
"vite-plugin-checker": "^0.10.2",
"vite-plugin-cjs-interop": "^2.2.0",
"vite-plugin-dts": "3.8.1",
"vite-plugin-svgr": "^4.2.0"
"vite-plugin-svgr": "^4.2.0",
"vitest": "1.4.0"
},
"engines": {
"node": "^24.5.0",
@@ -204,7 +219,7 @@
"name": "twenty",
"packageManager": "yarn@4.9.2",
"resolutions": {
"graphql": "16.8.1",
"graphql": "16.8.0",
"type-fest": "4.10.1",
"typescript": "5.9.2",
"graphql-redis-subscriptions/ioredis": "^5.6.0",
@@ -214,8 +229,6 @@
"version": "0.2.1",
"nx": {},
"scripts": {
"docs:generate": "tsx packages/twenty-docs/scripts/generate-docs-json.ts",
"docs:generate-navigation-template": "tsx packages/twenty-docs/scripts/generate-navigation-template.ts",
"start": "npx concurrently --kill-others 'npx nx run-many -t start -p twenty-server twenty-front' 'npx wait-on tcp:3000 && npx nx run twenty-server:worker'"
},
"workspaces": {
@@ -227,10 +240,8 @@
"packages/twenty-utils",
"packages/twenty-zapier",
"packages/twenty-website",
"packages/twenty-docs",
"packages/twenty-e2e-testing",
"packages/twenty-shared",
"packages/twenty-sdk",
"packages/twenty-apps",
"packages/twenty-cli",
"tools/eslint-rules"
-1
View File
@@ -1 +0,0 @@
generated
+404
View File
@@ -0,0 +1,404 @@
# Contributing to Twenty Apps (WIP WIP WIP - DO NOT USE)
Thank you for your interest in contributing applications to the Twenty ecosystem! This guide will help you create, test, and submit high-quality applications.
## 🚀 Quick Start
### Prerequisites
- Twenty development environment set up
- Basic understanding of Twenty's architecture
### Create Your First Application
1. **Create Application Directory**
```bash
mkdir packages/twenty-apps/my-awesome-app
cd packages/twenty-apps/my-awesome-app
```
2. **Create Application Manifest**
```bash
cat > twenty-app.json << 'EOF'
{
"universalIdentifier": "com.yourcompany.my-awesome-app",
"label": "My Awesome App",
"description": "A brief description of what your app does",
"version": "1.0.0",
"icon": "⭐",
"roles": [],
"objects": [],
"functions": [],
"agents": [],
"views": []
}
EOF
```
3. **Create Documentation**
```bash
cat > README.md << 'EOF'
# My Awesome App
Brief description of your application.
## Features
- Feature 1
- Feature 2
## Installation
```bash
npx nx app:install twenty-server \
--source "./packages/twenty-apps/my-awesome-app" \
--workspaceId "your-workspace-id" \
--sourceType "local"
```
EOF
```
4. **Validate Your Application**
```bash
npx nx validate twenty-apps
```
5. **Test Installation**
```bash
# Build the server first
npx nx build twenty-server
# Install your app
npx nx app:install twenty-server \
--source "./packages/twenty-apps/my-awesome-app" \
--workspaceId "your-workspace-id" \
--sourceType "local" \
--verbose
```
## 📋 Application Structure
### Required Files
- `twenty-app.json` - Application manifest (required)
- `README.md` - Application documentation (required)
### Optional Files
- `DEVELOPMENT.md` - Development guide
- `functions/` - Serverless function source files
- `assets/` - Icons, screenshots, etc.
- `examples/` - Usage examples
### Manifest Schema
Your `twenty-app.json` must follow this structure:
```json
{
"universalIdentifier": "com.company.app-name",
"label": "Human Readable Name",
"description": "Brief description (max 500 chars)",
"version": "1.0.0",
"icon": "🚀",
"repositoryUrl": "https://github.com/user/repo",
"roles": [
{
"universalIdentifier": "com.company.app-name.role-name",
"label": "Role Display Name",
"description": "What this role can do",
"permissions": {
"canReadAllObjectRecords": false,
"canUpdateAllObjectRecords": false,
"canAccessAllTools": false,
"canUpdateAllSettings": false
}
}
],
"objects": [
{
"universalIdentifier": "com.company.app-name.object-name",
"nameSingular": "objectName",
"namePlural": "objectNames",
"labelSingular": "Object Name",
"labelPlural": "Object Names",
"description": "What this object represents",
"icon": "📊",
"fields": [
{
"universalIdentifier": "com.company.app-name.object-name.field-name",
"name": "fieldName",
"label": "Field Label",
"type": "TEXT|NUMBER|CURRENCY|DATE_TIME|SELECT|RELATION",
"isNullable": true,
"defaultValue": "optional"
}
]
}
],
"functions": [
{
"universalIdentifier": "com.company.app-name.function-name",
"name": "functionName",
"description": "What this function does",
"sourceCode": "export const handler = async (event) => { ... };",
"runtime": "nodejs22.x",
"timeoutSeconds": 30
}
],
"agents": [
{
"universalIdentifier": "com.company.app-name.agent-name",
"name": "agentName",
"label": "Agent Display Name",
"description": "What this agent helps with",
"prompt": "You are a helpful assistant that...",
"modelId": "gpt-4"
}
],
"views": [
{
"universalIdentifier": "com.company.app-name.view-name",
"name": "View Name",
"objectName": "objectName",
"type": "TABLE|KANBAN|CALENDAR",
"icon": "📊",
"fields": [],
"filters": [],
"sorts": []
}
]
}
```
## 🛠️ Development Workflow
### 1. Development Mode
Use development mode for rapid iteration:
```bash
# Using environment variable (recommended)
export TWENTY_API_KEY="20202020-f401-4d8a-a731-64d007c27bad" # Default dev API key
npx nx app:dev twenty-server \
--path "./packages/twenty-apps/my-awesome-app" \
--verbose
# Or using command line parameter
npx nx app:dev twenty-server \
--path "./packages/twenty-apps/my-awesome-app" \
--api-key "your-api-key-here" \
--verbose
```
**Getting an API Key:**
1. Start your Twenty development server
2. Go to Settings → APIs & Webhooks
3. Generate a new API key
4. Use the default seeded key `20202020-f401-4d8a-a731-64d007c27bad` for development
This will:
- Watch for file changes
- Automatically sync updates to Twenty
- Show detailed logs of what's happening
### 2. Testing Your Application
#### Validation
```bash
# Validate manifest structure
npx nx validate twenty-apps
# List all applications
npx nx run twenty-apps:list
# Show application info
npx nx run twenty-apps:info
```
#### Installation Testing
```bash
# Test fresh installation (uses TWENTY_API_KEY environment variable)
npx nx app:install twenty-server \
--source "./packages/twenty-apps/my-awesome-app" \
--verbose
```
#### Manual Testing
1. Install your application in a test workspace
2. Verify all objects, roles, and functions are created
3. Test the functionality works as expected
4. Check that views display correctly
5. Test any AI agents respond appropriately
### 3. Common Development Patterns
#### Field Types
- `TEXT` - String values
- `NUMBER` - Numeric values
- `CURRENCY` - Monetary amounts
- `DATE_TIME` - Timestamps
- `SELECT` - Dropdown options
- `RELATION` - Links to other objects
#### Serverless Functions
```javascript
export const handler = async (event) => {
// Access event data
const { recordId, workspaceId } = event;
// Perform your logic
const result = await processData(recordId);
// Return response
return {
statusCode: 200,
body: JSON.stringify(result)
};
};
```
#### AI Agent Prompts
```json
{
"prompt": "You are a helpful assistant for [specific domain]. You can help users with:\n\n1. Specific task 1\n2. Specific task 2\n3. Specific task 3\n\nAlways be professional and provide actionable advice."
}
```
## ✅ Quality Guidelines
### Code Quality
- ✅ Valid JSON in manifest
- ✅ All required fields present
- ✅ Unique universal identifiers
- ✅ Proper field types and constraints
- ✅ Meaningful descriptions
### Documentation Quality
- ✅ Clear README with installation instructions
- ✅ Feature list with descriptions
- ✅ Usage examples
- ✅ Screenshots or demos (if applicable)
### Functionality Quality
- ✅ Application installs without errors
- ✅ All features work as described
- ✅ No conflicts with existing Twenty functionality
- ✅ Proper error handling in functions
### User Experience
- ✅ Intuitive object and field names
- ✅ Helpful descriptions and labels
- ✅ Logical default views and sorts
- ✅ Appropriate icons and visual elements
## 🔍 Review Process
### Self-Review Checklist
Before submitting, ensure:
- [ ] Application validates successfully (`npx nx validate twenty-apps`)
- [ ] Installation works in a clean workspace
- [ ] All features function as documented
- [ ] README is complete and accurate
- [ ] Universal identifiers follow reverse domain notation
- [ ] No hardcoded values or test data
- [ ] Functions handle errors gracefully
- [ ] AI agents provide helpful responses
### Submission Process
1. **Fork the Repository**
```bash
git clone https://github.com/twentyhq/twenty.git
```
2. **Create Feature Branch**
```bash
git checkout -b feature/my-awesome-app
```
3. **Commit Your Application**
```bash
git add packages/twenty-apps/my-awesome-app/
git commit -m "feat: add My Awesome App for [specific use case]"
```
4. **Push and Create PR**
```bash
git push origin feature/my-awesome-app
# Create pull request on GitHub
```
### PR Requirements
Your pull request should include:
- **Clear Title**: "feat: add [App Name] for [use case]"
- **Description**: What the app does and why it's useful
- **Screenshots**: Show the app in action
- **Testing**: Confirm you've tested installation and functionality
- **Documentation**: Link to your app's README
### Review Criteria
Applications are reviewed for:
1. **Functionality** - Does it work as described?
2. **Code Quality** - Is the manifest well-structured?
3. **Documentation** - Is it well-documented?
4. **Uniqueness** - Does it provide unique value?
5. **Compatibility** - Works with current Twenty version?
6. **Security** - No security vulnerabilities?
## 🎯 Application Categories
### Business Applications
- **CRM Extensions** - Sales, marketing, customer service
- **Project Management** - Tasks, resources, timelines
- **Financial** - Invoicing, expenses, reporting
- **HR** - Employee management, recruiting
### Industry-Specific
- **Real Estate** - Properties, leads, transactions
- **Healthcare** - Patients, appointments, records
- **Education** - Students, courses, grades
- **Legal** - Cases, clients, documents
### Utility Applications
- **Data Integration** - Import/export, connectors
- **Automation** - Workflows, triggers, notifications
- **Reporting** - Dashboards, analytics, insights
- **Communication** - Messaging, notifications, alerts
## 🆘 Getting Help
### Resources
- [Twenty Documentation](https://docs.twenty.com)
- [Application Examples](./crm-extension/)
- [Community Discord](https://discord.gg/twenty)
### Common Issues
**"Invalid universal identifier"**
- Use reverse domain notation: `com.company.app-name`
- Ensure uniqueness across your application
- Use lowercase with hyphens
**"Validation failed"**
- Check JSON syntax with `jq . twenty-app.json`
- Ensure all required fields are present
- Verify field types match schema
**"Installation failed"**
- Check workspace ID is correct
- Ensure Twenty server is running
- Verify no conflicting applications
### Support Channels
1. Check existing applications for examples
2. Review validation error messages
3. Ask in Twenty Discord #applications channel
4. Open GitHub issue for bugs
---
**Ready to build amazing applications for Twenty?** Start with our [CRM Extension example](./crm-extension/) to see what's possible, then create your own application to solve real business problems!
+299
View File
@@ -0,0 +1,299 @@
# Twenty Apps (WIP WIP WIP - DO NOT USE)
Welcome to the Twenty Apps collection! This package will contain a curated set of applications to extend Twenty CRM's functionality.
## 🚀 Available Applications
### 📊 CRM Extension Demo
**Location**: `./crm-extension/`
**Description**: A comprehensive demo showcasing custom objects, roles, serverless functions, and AI agents for sales territory and activity management.
**Features**:
- 🗺️ Sales Territory Management
- 📈 Sales Activity Tracking
- 🤖 AI Sales Assistant
- ⚡ Automated Performance Calculations
- 👥 Role-based Access Control
## 📦 Installation
### Prerequisites
#### For Local Development (Current)
The Twenty CLI is not yet published to npm. Use it locally from the monorepo:
```bash
# From the twenty monorepo root directory
# Use nx to run CLI commands:
npx nx run twenty-cli:start -- auth login
# All CLI commands follow this pattern:
npx nx run twenty-cli:start -- [command] [options]
```
#### For Published Version (Coming Soon)
```bash
# Once published to npm
npm install -g twenty-cli
twenty auth login
```
### Installing an application
```bash
# Install any application from this package (from monorepo root)
npx nx run twenty-cli:start -- app install \
--source "./packages/twenty-apps/crm-extension" \
--type local \
--workspace-id "your-workspace-id"
```
### Developing an application
```bash
# Navigate to the application directory
cd packages/twenty-apps/crm-extension
# Start development mode with auto-sync (from monorepo root)
npx nx run twenty-cli:start -- app dev \
--verbose
```
## 🏗️ Application Structure
Each application in this package follows the standard Twenty application structure:
```
app-name/
├── twenty-app.json # Application manifest
├── README.md # Application documentation
├── DEVELOPMENT.md # Development guide (optional)
├── functions/ # Serverless functions (optional)
│ ├── function1.js
│ └── function2.js
└── assets/ # Static assets (optional)
├── icons/
└── screenshots/
```
## 📋 Application Manifest
Every Twenty application must include a `twenty-app.json` file:
```json
{
"universalIdentifier": "com.company.app-name",
"label": "App Display Name",
"description": "Brief description of the app",
"version": "1.0.0",
"icon": "🚀",
"agents": [
{
"universalIdentifier": "com.company.app-name.agent-name",
"name": "agentName",
"label": "Agent Display Name",
"description": "What this agent helps with",
"prompt": "You are a helpful assistant that...",
"modelId": "gpt-4",
"responseFormat": {
"type": "text"
}
}
]
}
```
> **Note**: Currently, Twenty applications primarily support AI agents. Support for custom objects, roles, functions, and views is planned for future releases.
## 🛠️ Development Workflow
### 1. Create a New Application
```bash
# Create application using the CLI (from monorepo root)
npx nx run twenty-cli:start -- app init my-new-app
cd my-new-app
# Or create manually in the twenty-apps package
mkdir packages/twenty-apps/my-new-app
cd packages/twenty-apps/my-new-app
# Create manifest
cat > twenty-app.json << 'EOF'
{
"universalIdentifier": "com.mycompany.my-new-app",
"label": "My New App",
"description": "Description of my application",
"version": "1.0.0",
"icon": "⭐",
"agents": []
}
EOF
```
### 2. Develop with Live Reload
```bash
# Navigate to your application directory
cd packages/twenty-apps/my-new-app
# Start development mode with file watching (from monorepo root)
npx nx run twenty-cli:start -- app dev \
--workspace-id "your-workspace-id" \
--verbose
```
### 3. Test Installation
```bash
# Test installation from local source (from monorepo root)
npx nx run twenty-cli:start -- app install \
--source "./packages/twenty-apps/my-new-app" \
--type local \
--workspace-id "test-workspace-id"
```
## 📚 Application Categories
### 🏢 Business Applications
- **CRM Extensions**: Sales, marketing, customer service enhancements
- **Project Management**: Task tracking, resource management
- **Financial**: Invoicing, expense tracking, reporting
### 🤖 AI-Powered Applications
- **Customer Support**: Intelligent chatbots and support agents
- **Sales Automation**: Lead qualification and follow-up agents
- **Data Analysis**: AI agents for reporting and insights
### 🎨 Industry-Specific Agents
- **Real Estate**: Property recommendation and client management agents
- **Healthcare**: Patient communication and scheduling assistants
- **Education**: Student support and course guidance agents
## 🤝 Contributing Applications
We welcome contributions! To add your application to this collection:
### 1. Application Requirements
- ✅ Complete `twenty-app.json` manifest
- ✅ Comprehensive README.md
- ✅ Proper universal identifier (reverse domain notation)
- ✅ Tested functionality
- ✅ Clear documentation
### 2. Submission Process
1. Fork the repository
2. Create your application in `packages/twenty-apps/your-app-name/`
3. Test thoroughly using the development workflow
4. Submit a pull request with:
- Application code and manifest
- Screenshots/demos
- Installation and usage instructions
### 3. Review Criteria
- **Functionality**: Does it work as described?
- **Documentation**: Is it well-documented?
- **Code Quality**: Is the manifest well-structured?
- **Uniqueness**: Does it provide unique value?
- **Compatibility**: Works with current Twenty version?
## ⚙️ CLI Configuration
The Twenty CLI supports both global and project-level configuration:
```bash
# Set global configuration (applies to all projects)
twenty config set apiUrl "https://your-twenty-instance.com"
twenty config set workspaceId "your-default-workspace-id"
# Set project-level configuration (applies to current directory)
twenty config set workspaceId "project-specific-workspace-id" --project
# View current configuration
twenty config list
```
Configuration files:
- **Global**: `~/.twenty/config.json`
- **Project**: `.twenty.json` in your project directory
## 🔍 Application Discovery
### Browse Applications
```bash
# List all available applications in this package
ls packages/twenty-apps/
# View application details
cat packages/twenty-apps/crm-extension/twenty-app.json
# List installed applications in your workspace (from monorepo root)
npx nx run twenty-cli:start -- app list --workspace-id "your-workspace-id"
```
### Search by Category
Applications are organized by functionality and industry. Check individual README files for detailed feature lists.
## 🚨 Troubleshooting
### Common Issues
**"Authentication failed"**
- Run `npx nx run twenty-cli:start -- auth login` to authenticate
- Check your API key is valid and not expired
- Verify you have access to the workspace
**"Application not found"**
- Verify the path to your application directory
- Ensure `twenty-app.json` exists and is valid JSON
- Check the file is in the correct location
**"Invalid workspace ID"**
- Check your workspace ID is correct
- Use `npx nx run twenty-cli:start -- config get workspaceId` to see your configured workspace
- Ensure you have access to the workspace
**"Manifest validation failed"**
- Validate your JSON syntax using a JSON validator
- Check all required fields are present (universalIdentifier, label, version)
- Ensure universal identifier follows reverse domain notation (com.company.app)
### Getting Help
1. Check the application's README.md for specific instructions
2. Review the Twenty CLI documentation: `npx nx run twenty-cli:start -- --help`
3. Check Twenty's main documentation
4. Open an issue on GitHub with detailed error messages
## 📄 License
All applications in this package are licensed under AGPL-3.0 unless otherwise specified in individual application directories.
## 🌟 Featured Applications
### 🏆 Most Popular
1. **CRM Extension Demo** - Comprehensive sales management
2. *More applications coming soon!*
### 🆕 Recently Added
1. **CRM Extension Demo** - Initial demo application
---
## 🚀 Getting Started
**Ready to extend Twenty CRM with AI agents?**
### For Local Development (Current)
1. **Clone the repo**: `git clone https://github.com/twentyhq/twenty.git && cd twenty`
2. **Authenticate**: `npx nx run twenty-cli:start -- auth login`
3. **Explore the demo**: Check out the CRM Extension demo to see what's possible
4. **Create your own**: `npx nx run twenty-cli:start -- app init my-app`
### For Published Version (Coming Soon)
1. **Install the CLI**: `npm install -g twenty-cli`
2. **Authenticate**: `twenty auth login`
3. **Explore the demo**: Check out the CRM Extension demo
4. **Create your own**: `twenty app init my-app`
Start with the CRM Extension demo to see AI agents in action, then create your own applications to solve your unique business needs!
@@ -0,0 +1,60 @@
import { promises as fs } from 'fs';
import * as path from 'path';
describe('Twenty Apps Package', () => {
describe('Package Structure', () => {
it('should have a hello-world app with manifest', async () => {
const manifestPath = path.join(__dirname, '../hello-world/twenty-app.json');
const manifestExists = await fs.access(manifestPath).then(() => true).catch(() => false);
expect(manifestExists).toBe(true);
});
it('should have a template app with manifest', async () => {
const templatePath = path.join(__dirname, '../_template/twenty-app.json');
const templateExists = await fs.access(templatePath).then(() => true).catch(() => false);
expect(templateExists).toBe(true);
});
});
describe('App Manifests', () => {
it('should have valid JSON in hello-world manifest', async () => {
const manifestPath = path.join(__dirname, '../hello-world/twenty-app.json');
const manifestContent = await fs.readFile(manifestPath, 'utf8');
expect(() => JSON.parse(manifestContent)).not.toThrow();
const manifest = JSON.parse(manifestContent);
expect(manifest).toHaveProperty('standardId');
expect(manifest).toHaveProperty('label');
expect(manifest).toHaveProperty('version');
});
it('should have valid JSON in template manifest', async () => {
const templatePath = path.join(__dirname, '../_template/twenty-app.json');
const templateContent = await fs.readFile(templatePath, 'utf8');
expect(() => JSON.parse(templateContent)).not.toThrow();
const template = JSON.parse(templateContent);
expect(template).toHaveProperty('standardId');
expect(template).toHaveProperty('label');
expect(template).toHaveProperty('version');
});
});
describe('Package Configuration', () => {
it('should have a valid package.json', async () => {
const packagePath = path.join(__dirname, '../package.json');
const packageContent = await fs.readFile(packagePath, 'utf8');
expect(() => JSON.parse(packageContent)).not.toThrow();
const packageJson = JSON.parse(packageContent);
expect(packageJson.name).toBe('twenty-apps');
expect(packageJson).toHaveProperty('version');
expect(packageJson).toHaveProperty('description');
});
});
});
+175
View File
@@ -0,0 +1,175 @@
# Your App Name
A brief description of what your application does and the problems it solves.
## 🚀 Features
- **Feature 1**: Description of what this feature does
- **Feature 2**: Description of what this feature does
- **Feature 3**: Description of what this feature does
## 📦 What Gets Installed
When you install this application, Twenty will automatically create:
### 🗂️ Objects
- **Example Object**: Description of what this object represents
### 👥 Roles
- **App Administrator**: Full access to all app features
- **App User**: Standard user access with limited permissions
### ⚡ Functions
- **Example Function**: Description of what this function does
### 🤖 AI Agents
- **App Assistant**: AI helper for app-related questions and tasks
### 📊 Views
- **All Example Objects**: Default view showing all example objects
## 🛠️ Installation
### Prerequisites
- Twenty CRM instance running
- Valid workspace ID
- Server built (`npx nx build twenty-server`)
### Install Command
```bash
npx nx app:install twenty-server \
--source "./packages/twenty-apps/your-app-name" \
--workspaceId "your-workspace-id" \
--sourceType "local" \
--verbose
```
### Development Mode
For active development with auto-sync:
```bash
npx nx app:dev twenty-server \
--appPath "./packages/twenty-apps/your-app-name" \
--workspaceId "your-workspace-id" \
--verbose
```
## 📖 Usage
### Getting Started
1. After installation, navigate to the new objects in your Twenty workspace
2. Assign users to the appropriate roles (App Administrator or App User)
3. Start creating records using the new objects
4. Use the AI assistant for help and guidance
### Common Workflows
#### Workflow 1: [Describe a common use case]
1. Step 1 description
2. Step 2 description
3. Step 3 description
#### Workflow 2: [Describe another use case]
1. Step 1 description
2. Step 2 description
3. Step 3 description
### Tips and Best Practices
- **Tip 1**: Helpful advice for users
- **Tip 2**: Another useful tip
- **Tip 3**: Best practice recommendation
## 🔧 Configuration
### Role Permissions
- **App Administrator**: Can read and update all records
- **App User**: Limited to their own records (customize as needed)
### Field Customization
You can customize the following fields after installation:
- Field 1: How to customize it
- Field 2: How to customize it
### Function Configuration
The serverless functions can be configured for:
- Setting 1: Description
- Setting 2: Description
## 🤝 Integration
### With Existing Objects
This app integrates with Twenty's core objects:
- **Companies**: How it relates to companies
- **People**: How it relates to people
- **Opportunities**: How it relates to opportunities
### API Usage
Access your app's data via Twenty's GraphQL API:
```graphql
query GetExampleObjects {
exampleObjects {
id
name
status
createdDate
}
}
```
### Webhooks
Set up webhooks to react to changes:
- When example objects are created
- When status changes
- When records are updated
## 🚨 Troubleshooting
### Common Issues
**Issue 1: [Common problem]**
- **Cause**: Why this happens
- **Solution**: How to fix it
**Issue 2: [Another problem]**
- **Cause**: Why this happens
- **Solution**: How to fix it
### Getting Help
1. Check the AI assistant for quick help
2. Review the Twenty documentation
3. Ask in the Twenty Discord community
4. Open an issue on GitHub
## 🔄 Updates
### Version History
- **v1.0.0**: Initial release with core features
### Updating
To update to a newer version:
```bash
npx nx app:install twenty-server \
--source "./packages/twenty-apps/your-app-name" \
--workspaceId "your-workspace-id" \
--sourceType "local"
```
## 📄 License
This application is licensed under [LICENSE] - see the LICENSE file for details.
## 🤝 Contributing
Contributions are welcome! Please read the [contributing guidelines](../CONTRIBUTING.md) before submitting changes.
### Development Setup
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Test thoroughly
5. Submit a pull request
---
**Need help?** The App Assistant AI agent is available in your Twenty workspace to help with questions and provide guidance on using this application effectively!
@@ -0,0 +1,22 @@
{
"standardId": "com.yourcompany.your-app-name",
"label": "Your App Name",
"description": "A brief description of what your application does",
"version": "1.0.0",
"icon": "⭐",
"agents": [
{
"standardId": "com.yourcompany.your-app-name.assistant",
"name": "assistant",
"label": "App Assistant",
"description": "AI assistant for your application",
"icon": "🤖",
"prompt": "You are a helpful assistant for [Your App Name]. Help users with:\n\n1. Understanding app features\n2. Navigating the interface\n3. Completing common tasks\n4. Troubleshooting issues\n5. Providing guidance and tips\n\nBe helpful, clear, and focused on the user's needs.",
"modelId": "gpt-4",
"responseFormat": {
"type": "text"
}
}
]
}
@@ -1,6 +0,0 @@
TWENTY_API_KEY=<SET_YOUR_TWENTY_API>
DAYS_AGO=<SET_YOUR_DAYS_AGO>
DISCORD_WEBHOOK_URL=<SET_YOUR_DISCORD_WEBHOOK_URL>
FB_GRAPH_TOKEN=<SET_YOUR_FB_GRAPH_TOKEN>
WHATSAPP_RECIPIENT_PHONE_NUMBER=<SET_YOUR_WHATSAPP_RECIPIENT_PHONE_NUMBER>
SLACK_HOOK_URL=<SET_YOUR_SLACK_HOOK_URL>
@@ -1,2 +0,0 @@
.yarn/install-state.gz
.env
File diff suppressed because one or more lines are too long
@@ -1,3 +0,0 @@
yarnPath: .yarn/releases/yarn-4.9.2.cjs
nodeLinker: node-modules
@@ -1,108 +0,0 @@
# Twenty CRM Activity Reporter
A TypeScript-based reporting bot that summarizes activity from your Twenty CRM workspace and sends daily/periodic reports to Slack, Discord, and WhatsApp. Meet Kylian Mbaguette, your friendly CRM activity reporter!
## Features
- 🧑‍💻 **People & Company Tracking**: Summarizes newly created people and companies
- 🎯 **Opportunity Monitoring**: Reports on new opportunities created, broken down by stage
-**Task Analytics**:
- Tracks task creation
- Calculates on-time completion rates
- Identifies team members with the most overdue tasks (the "slackers")
- 🔔 **Multi-Platform Notifications**: Send reports to Slack, Discord, and/or WhatsApp
-**Configurable Time Range**: Look back any number of days
## Prerequisites
- Node.js (v14 or higher recommended)
- TypeScript
- A [Twenty CRM](https://twenty.com) account with API access
- Optional: Slack webhook, Discord webhook, and/or WhatsApp Business API access
## Installing dependencies
```bash
# Install dependencies
yarn install
```
### Environment Variables
| Variable | Required | Description |
|----------|----------|-------------|
| `TWENTY_API_KEY` | ✅ Yes | Your Twenty CRM API key |
| `DAYS_AGO` | ✅ Yes | Number of days to look back for the report |
| `SLACK_HOOK_URL` | ❌ No | Slack incoming webhook URL |
| `DISCORD_WEBHOOK_URL` | ❌ No | Discord webhook URL |
| `FB_GRAPH_TOKEN` | ❌ No | Facebook Graph API token for WhatsApp |
| `WHATSAPP_RECIPIENT_PHONE_NUMBER` | ❌ No | WhatsApp recipient phone number (with country code) |
## Project Structure
```
.
├── index.ts # Main entry point
├── people-creation-summariser.ts # Summarizes people/company creation
├── opportunity-creation-summariser.ts # Summarizes opportunity creation
├── task-creation-summariser.ts # Summarizes task creation & completion
├── senders.ts # Handles sending to Slack/Discord/WhatsApp
├── utils.ts # API request utility
└── README.md
```
## How It Works
1. **Data Collection**: The bot queries the Twenty CRM API for activities within the specified time range
2. **Analysis**:
- Counts new people and companies
- Categorizes opportunities by stage
- Calculates task completion rates and identifies overdue tasks
3. **Reporting**: Formats the data into friendly messages
4. **Distribution**: Sends reports to configured platforms (Slack, Discord, WhatsApp)
## Report Format
Each report includes:
```
Bonjour! 🥖 Je m'appelle Kylian Mbaguette. Over the last X days:
🧑‍💻 People & Companies
- X People and Y Companies were added
🎯 Opportunities
- X Opportunities were added: Y in NEW, Z in PROPOSAL
📋 Tasks
- X Tasks were created
- Y% Tasks were completed on time
- [Name] slacked the most with Z Tasks overdue
```
## API Integration
This bot uses the [Twenty CRM REST API](https://api.twenty.com/rest/). The following endpoints are used:
- `GET /people` - Fetch people data
- `GET /opportunities` - Fetch opportunity data
- `GET /tasks` - Fetch task data
- `GET /workspaceMembers/{id}` - Fetch workspace member details
## Notes
- The "slacker" detection is lighthearted and identifies team members with the most overdue tasks
- At least one messaging platform must be configured for the bot to send reports
- The bot uses ISO date format (YYYY-MM-DD) for date filtering
- Task completion percentage only considers incomplete tasks (excludes already completed tasks from the calculation)
## Troubleshooting
**Issue**: No messages being sent
- **Solution**: Ensure at least one messaging platform is configured with valid credentials
**Issue**: API authentication errors
- **Solution**: Verify your `TWENTY_API_KEY` is correct and has necessary permissions
**Issue**: WhatsApp messages not sending
- **Solution**: Ensure both `FB_GRAPH_TOKEN` and `WHATSAPP_RECIPIENT_PHONE_NUMBER` are set correctly
## Contributing
Built with ❤️ and 🥖 by Azmat, Ali and Mike from 9dots
@@ -1,45 +0,0 @@
import { type ApplicationConfig } from 'twenty-sdk/application';
const config: ApplicationConfig = {
universalIdentifier: 'b53627f5-ca60-478c-bc43-c7ab4904e34a',
displayName: 'Activity Summary',
description:
'A TypeScript-based reporting bot that summarizes activity from your Twenty CRM workspace and sends daily/periodic reports to Slack, Discord, and WhatsApp. Meet Kylian Mbaguette, your friendly CRM activity reporter!',
applicationVariables: {
TWENTY_API_KEY: {
universalIdentifier: '304b7d5d-e2bb-4444-9b04-6b3ae8b73730',
description: 'Twenty API Key',
isSecret: true,
},
DAYS_AGO: {
universalIdentifier: '040a3097-9cee-4f74-b957-c2f9bf636c3f',
description:
'How far back into the past we want to summarise defaults to the past 7 days',
value: '7',
isSecret: false,
},
SLACK_HOOK_URL: {
universalIdentifier: 'fd16e370-934c-4267-83b4-7d88259bf7e1',
description: 'Slack hook URL for sending message to channel',
isSecret: true,
},
DISCORD_WEBHOOK_URL: {
universalIdentifier: 'f3741075-d525-4988-ba42-55d519c6fd76',
description:
'Discord webhook URL for sending message to channel of a server',
isSecret: true,
},
FB_GRAPH_TOKEN: {
universalIdentifier: 'fb907f49-74ac-4aa5-ba45-cfc9250ecc44',
description: 'For Facebook auth',
isSecret: true,
},
WHATSAPP_RECIPIENT_PHONE_NUMBER: {
universalIdentifier: 'c856ee5d-44bf-42f4-9a39-2553a94af518',
description: 'Phone number for receiving WhatsApp message',
isSecret: true,
},
},
};
export default config;
@@ -1,17 +0,0 @@
{
"name": "activity-summary",
"version": "0.0.1",
"license": "MIT",
"engines": {
"node": "^24.5.0",
"npm": "please-use-yarn",
"yarn": ">=4.0.2"
},
"packageManager": "yarn@4.9.2",
"dependencies": {
"twenty-sdk": "0.0.3"
},
"devDependencies": {
"@types/node": "^24.7.2"
}
}
@@ -1,80 +0,0 @@
import { summariseOpportunityCreation } from './opportunity-creation-summariser';
import { summarisePeopleCreation } from './people-creation-summariser';
import { sendToDiscord, sendToSlack, sendToWhatsApp } from './senders';
import { summariseTaskCreation } from './task-creation-summariser';
import { type ServerlessFunctionConfig } from 'twenty-sdk/application';
export const main = async (): Promise<object> => {
let date: string | Date = new Date();
date.setDate(new Date().getDate() - Number(process.env.DAYS_AGO));
date = date.toISOString().substring(0, 10);
const peopleCreationSummary = await summarisePeopleCreation(date);
const opportunityCreationSummary = await summariseOpportunityCreation(date);
const taskCreationSummary = await summariseTaskCreation(date);
let body = {
daysAgo: Number(process.env.DAYS_AGO),
peopleCreationSummary,
opportunityCreationSummary,
taskCreationSummary,
discord: {},
whatsapp: {},
slack: {},
};
if (process.env.SLACK_HOOK_URL) {
const slackBody = await sendToSlack({
peopleCreationSummary,
opportunityCreationSummary,
taskCreationSummary,
});
body = {
...body,
slack: slackBody,
};
}
if (process.env.DISCORD_WEBHOOK_URL) {
const discordBody = await sendToDiscord({
peopleCreationSummary,
opportunityCreationSummary,
taskCreationSummary,
});
body = {
...body,
discord: discordBody,
};
}
if (
process.env.FB_GRAPH_TOKEN &&
process.env.WHATSAPP_RECIPIENT_PHONE_NUMBER
) {
const whatsappBody = await sendToWhatsApp({
peopleCreationSummary,
opportunityCreationSummary,
taskCreationSummary,
});
body = {
...body,
whatsapp: whatsappBody,
};
}
return body;
};
export const config: ServerlessFunctionConfig = {
universalIdentifier: 'c5b0e3f7-cbbd-4bd6-b01c-150d52cf2ce9',
name: 'summarise-and-send',
triggers: [
{
universalIdentifier: '36e1c4c7-8664-4d6d-a88f-ac56f1bd0651',
type: 'cron',
pattern: '0 9 * * *',
},
],
};
@@ -1,28 +0,0 @@
import { request } from "./utils"
type Opportunity = {
stage: 'NEW' | 'PROPOSAL'
}
export const summariseOpportunityCreation = async (date: string) => {
const { opportunities }: { opportunities: Opportunity[] } = await request(
`opportunities?filter=createdAt[gte]:${date}`,
)
if (opportunities.length === 0) {
return `- No Opportunities were added`
}
const stageSummary = Object.entries(
opportunities.reduce((hash: Record<string,number>, opportunity) => {
if (!hash[opportunity.stage]) {
hash[opportunity.stage] = 0
}
hash[opportunity.stage] += 1
return hash
}, {})
).map(([stage, value]) => `${value} in ${stage}`).join(', ')
return `- ${opportunities.length} Opportunities were added: ${stageSummary}`
}
@@ -1,38 +0,0 @@
import { request } from "./utils"
type Person = {
companyId: string
company: Company
}
type Company = {
id: string
accountOwnerId: string
}
export const summarisePeopleCreation = async (date: string) => {
const { people }: { people: Person[] } = await request(
`people?depth=1&filter=createdAt[gte]:${date}`,
)
if (people.length === 0) {
return '- No People were added'
}
let createdForCompanies: Record<string, Company> = {}
let numberOfAccountOwnerlessCompanies = 0
for (const person of people) {
const isCompanyTracked = createdForCompanies[person.companyId]
if (person.companyId && !isCompanyTracked) {
createdForCompanies[person.company.id] = person.company
if (!person?.company?.accountOwnerId) {
numberOfAccountOwnerlessCompanies += 1
}
}
}
return `- ${people.length} People were added for ${Object.keys(createdForCompanies).length} Companies
- Out of those, ${numberOfAccountOwnerlessCompanies} Companies don't have account owners yet`
}
@@ -1,172 +0,0 @@
export const sendToSlack = async (params: {
peopleCreationSummary: string;
opportunityCreationSummary: string;
taskCreationSummary: string;
}) => {
const {
peopleCreationSummary,
opportunityCreationSummary,
taskCreationSummary,
} = params;
const slackMessage = {
blocks: [
{
type: 'header',
text: {
type: 'plain_text',
text: `Bonjour! 🥖 Je m'appelle Kylian Mbaguette. Over the last ${process.env.DAYS_AGO} days`,
emoji: true,
},
},
{
type: 'header',
text: {
type: 'plain_text',
text: '🧑‍💻 People & Companies',
emoji: true,
},
},
{
type: 'section',
text: {
type: 'plain_text',
text: peopleCreationSummary,
emoji: true,
},
},
{
type: 'header',
text: {
type: 'plain_text',
text: '🎯 Opportunities',
emoji: true,
},
},
{
type: 'section',
text: {
type: 'plain_text',
text: opportunityCreationSummary,
emoji: true,
},
},
{
type: 'header',
text: {
type: 'plain_text',
text: '📋 Tasks',
emoji: true,
},
},
{
type: 'section',
text: {
type: 'plain_text',
text: taskCreationSummary,
emoji: true,
},
},
],
};
const response = await fetch(process.env.SLACK_HOOK_URL ?? '', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(slackMessage),
});
return {
formattedMessage: slackMessage,
webhookStatus: response.status,
};
};
export const sendToDiscord = async (params: {
peopleCreationSummary: string;
opportunityCreationSummary: string;
taskCreationSummary: string;
}) => {
const {
peopleCreationSummary,
opportunityCreationSummary,
taskCreationSummary,
} = params;
const formattedMessage = `Bonjour! 🥖 Je m'appelle Kylian Mbaguette. Over the last ${process.env.DAYS_AGO} days:
**🧑‍💻 People & Companies**
${peopleCreationSummary}
**🎯 Opportunities**
${opportunityCreationSummary}
**📋 Tasks**
${taskCreationSummary}`;
const body = {
username: 'Twenty Bot',
content: formattedMessage,
};
const response = await fetch(process.env.DISCORD_WEBHOOK_URL ?? '', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
return {
formattedMessage,
webhookStatus: response.status,
};
};
export const sendToWhatsApp = async (params: {
peopleCreationSummary: string;
opportunityCreationSummary: string;
taskCreationSummary: string;
}): Promise<object> => {
const {
peopleCreationSummary,
opportunityCreationSummary,
taskCreationSummary,
} = params;
const formattedMessage = `Bonjour! 🥖 Je m'appelle Kylian Mbaguette. Over the last ${process.env.DAYS_AGO} days:
*🧑‍💻 People & Companies*
${peopleCreationSummary}
*🎯 Opportunities*
${opportunityCreationSummary}
*📋 Tasks*
${taskCreationSummary}`;
const response = await fetch(
'https://graph.facebook.com/v22.0/828771160324576/messages',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.FB_GRAPH_TOKEN}`,
},
body: JSON.stringify({
messaging_product: 'whatsapp',
recipient_type: 'individual',
to: process.env.WHATSAPP_RECIPIENT_PHONE_NUMBER,
type: 'text',
text: {
preview_url: true,
body: formattedMessage,
},
}),
},
);
const responseBody = await response.json();
return {
formattedMessage,
webhookStatus: response.status,
webhookResponse: responseBody,
};
};
@@ -1,89 +0,0 @@
import { request } from "./utils"
type Task = {
status: string
dueAt: string
createdBy: {
workspaceMemberId: string
}
}
export const summariseTaskCreation = async (date: string) => {
const { tasks }: { tasks: Task[] } = await request(
`tasks?filter=createdAt[gte]:${date}`,
)
if (tasks.length === 0) {
return '- No Tasks were added'
}
const presentDateISOString = new Date().toISOString()
const workspaceMemberIdsDueDateCounter: Record<string, number> = {}
let workspaceMembers = []
tasks.forEach((task) => {
if (task.status === 'DONE') {
return
}
if (presentDateISOString >= task.dueAt) {
if (!workspaceMemberIdsDueDateCounter[task.createdBy.workspaceMemberId]) {
workspaceMemberIdsDueDateCounter[task.createdBy.workspaceMemberId] = 0
}
workspaceMemberIdsDueDateCounter[task.createdBy.workspaceMemberId] += 1
}
})
for (const { userId, count } of findMaxIncompleteKeys(workspaceMemberIdsDueDateCounter)) {
const data = await request(`workspaceMembers/${userId}`)
if (data.workspaceMember) {
workspaceMembers.push({
...data.workspaceMember,
slackCount: count
})
}
}
let slackerMessage = workspaceMembers.length > 0 ? workspaceMembers.reduce((text, member, index) => {
if (index === 0 && workspaceMembers.length === 1) {
return `${member.name.firstName} slacked the most with ${member.slackCount} Tasks overdue`
}
if (index !== workspaceMembers.length - 1) {
return text.concat(`, ${member.name.firstName}`)
}
if (index === workspaceMembers.length - 1) {
return text.concat(`, and ${member.name.firstName} slacked the most with ${member.slackCount} Tasks overdue`)
}
}, '') : 'No one was caught slacking!'
const tasksCompletedOnTime = tasks.filter(
task => task.status === 'DONE' && task.dueAt >= presentDateISOString
)
const taskCompletionPercentage = tasksCompletedOnTime.length > 0
? (tasksCompletedOnTime.length / tasks.length) * 100
: NaN
const taskCompletionMessage = isNaN(taskCompletionPercentage)
? 'No completed Tasks yet'
: `${taskCompletionPercentage.toFixed(2)}% of Tasks were completed on time`
return `- ${tasks.length} Tasks were created
- ${taskCompletionMessage}
- ${slackerMessage}`
}
/**
* @description This is generated by AI
*/
const findMaxIncompleteKeys = (workspaceMemberIdsDueDateCounter: Record<string,number>) => {
// Get the maximum incomplete count
const max = Math.max(...Object.values(workspaceMemberIdsDueDateCounter));
// Filter keys that match the maximum value
return Object.entries(workspaceMemberIdsDueDateCounter)
.filter(([_, count]) => count === max)
.map(([userId, count]) => ({ userId, count }))
};
@@ -1,13 +0,0 @@
export const request = async (route: string, authToken?: string) => {
const response = await fetch(
`https://api.twenty.com/rest/${route}`,
{
headers: {
Authorization: `Bearer ${process.env.TWENTY_API_KEY}`
},
}
)
const json = await response.json()
return json.data
}
@@ -1,26 +0,0 @@
{
"compileOnSave": false,
"compilerOptions": {
"sourceMap": true,
"declaration": true,
"outDir": "./dist",
"rootDir": ".",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"strict": true,
"target": "es2018",
"module": "esnext",
"lib": ["es2020", "dom"],
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"resolveJsonModule": true
},
"exclude": [
"node_modules",
"dist",
"**/*.test.ts",
"**/*.spec.ts"
]
}
@@ -1,38 +0,0 @@
# This file is generated by running "yarn install" inside your project.
# Manual changes might be lost - proceed with caution!
__metadata:
version: 8
cacheKey: 10c0
"@types/node@npm:^24.7.2":
version: 24.9.2
resolution: "@types/node@npm:24.9.2"
dependencies:
undici-types: "npm:~7.16.0"
checksum: 10c0/7905d43f65cee72ef475fe76316e10bbf6ac5d08a7f0f6c38f2b6285d7ca3009e8fcafc8f8a1d2bf3f55889c9c278dbb203a9081fd0cf2d6d62161703924c6fa
languageName: node
linkType: hard
"activity-summary@workspace:.":
version: 0.0.0-use.local
resolution: "activity-summary@workspace:."
dependencies:
"@types/node": "npm:^24.7.2"
twenty-sdk: "npm:0.0.3"
languageName: unknown
linkType: soft
"twenty-sdk@npm:0.0.3":
version: 0.0.3
resolution: "twenty-sdk@npm:0.0.3"
checksum: 10c0/0a3c85c27edb22fb50f7eb0da4f9770e85729fce05e9e0118ad0cdfc36e42425c93340a6cd1c276daf30aeeaa612db0cd905831c0a8287a31bff3da5be9b0562
languageName: node
linkType: hard
"undici-types@npm:~7.16.0":
version: 7.16.0
resolution: "undici-types@npm:7.16.0"
checksum: 10c0/3033e2f2b5c9f1504bdc5934646cb54e37ecaca0f9249c983f7b1fc2e87c6d18399ebb05dc7fd5419e02b2e915f734d872a65da2e3eeed1813951c427d33cc9a
languageName: node
linkType: hard
@@ -1,19 +0,0 @@
# Set environment values for your application here.
# Use the format: KEY=value
#
# These variables are automatically loaded when running your serverless functions.
# You can access them directly in your code using:
# const myValue = process.env.KEY;
#
# To make these variables available to your application,
# add them to package.json "env" key. This "env" key defines all
# environment variables that will be provided to your serverless
# functions at runtime.
#
# Example:
# API_TOKEN=your-api-token
# TIMEOUT_MS=3000
TWENTY_API_URL=
TWENTY_API_KEY=
OPENAI_API_KEY=
@@ -1,2 +0,0 @@
.yarn/install-state.gz
.env
File diff suppressed because one or more lines are too long
@@ -1,3 +0,0 @@
yarnPath: .yarn/releases/yarn-4.9.2.cjs
nodeLinker: node-modules
@@ -1,159 +0,0 @@
# AI Meeting Transcript
Automatically process meeting transcripts to extract insights, action items, and follow-ups using AI.
## Features
- **Automatic Transcript Processing**: Receives meeting transcripts via webhook from Granola or similar transcription tools
- **AI-Powered Analysis**: Uses OpenAI to extract:
- Meeting summary
- Key discussion points
- Action items with assignees and due dates
- Commitments made by participants
- **Rich Note Creation**: Creates formatted notes in Twenty with summary and key points
- **Task Generation**: Automatically creates tasks for action items and commitments, linked to the meeting note
## Requirements
- `twenty-cli` - Install globally: `npm install -g twenty-cli`
- `apiKey` - Go to `https://twenty.com/settings/api-webhooks` to generate one
- `OpenAI API Key` - Get your API key from [OpenAI](https://platform.openai.com/api-keys)
## Installation
1. Copy the environment file:
```bash
cp .env.example .env
```
2. Edit `.env` and replace the placeholders:
- `<SET_YOUR_TWENTY_API>` with your Twenty API key
- `<SET_YOUR_OPENAI_API_KEY>` with your OpenAI API key
3. Install dependencies:
```bash
yarn install
```
4. Sync the app to your Twenty workspace:
```bash
twenty auth login
twenty app sync
```
## Configuration
After syncing, configure the environment variables in your Twenty workspace:
1. Go to Settings → Apps → AI Meeting Transcript
2. Set the following environment variables:
- `TWENTY_API_KEY` - Your Twenty API key
- `TWENTY_API_URL` - Your Twenty instance URL (e.g., `https://api.twenty.com` or `http://localhost:3000` for local development)
- `OPENAI_API_KEY` - Your OpenAI API key
**Important**: `TWENTY_API_URL` is required and must be set to your Twenty instance URL. For local development, use `http://localhost:3000`. For production, use your actual Twenty instance URL.
## Usage
### Webhook Endpoint
The app exposes a public serverless route trigger.
```
POST /s/webhook/transcript
```
Examples:
- Local: `POST http://localhost:3000/s/webhook/transcript`
- Hosted: `POST https://your-twenty-instance.com/s/webhook/transcript`
### Webhook Payload Format
Send a POST request with the following JSON structure:
```json
{
"transcript": "Full meeting transcript text here...",
"meetingTitle": "Q4 Planning Meeting",
"meetingDate": "2024-01-15",
"participants": ["John Doe", "Jane Smith"],
"metadata": {
"duration": "45 minutes",
"location": "Conference Room A"
}
}
```
**Required Fields:**
- `transcript` (string): The full meeting transcript text
**Optional Fields:**
- `meetingTitle` (string): Title of the meeting
- `meetingDate` (string): Date of the meeting (ISO format or readable date)
- `participants` (string[]): List of meeting participants
- `metadata` (object): Additional metadata about the meeting
### Example Webhook Call
```bash
curl -X POST https://your-twenty-instance.com/s/webhook/transcript \
-H "Content-Type: application/json" \
-d '{
"transcript": "John: Let'\''s start the meeting. Today we need to discuss Q4 goals. Jane: I agree. We should focus on customer retention. John: Great point. Can you prepare a report by Friday? Jane: Yes, I will have it ready.",
"meetingTitle": "Q4 Planning Meeting",
"meetingDate": "2024-01-15"
}'
```
### What Happens
1. **Transcript Analysis**: The transcript is sent to OpenAI for analysis
2. **Note Creation**: A formatted note is created in Twenty with:
- Meeting summary
- Key discussion points
- Reference to the transcript source
3. **Task Creation**: Tasks are automatically created for:
- Each action item identified
- Each commitment made by participants
- Tasks include a reference to the meeting note ID in their description
## Development
Run dev mode to see application updates on your workspace instantly:
```bash
twenty app dev
```
## Integration with Granola
To integrate with Granola or similar transcription tools:
1. Set up a webhook in your transcription service
2. Configure it to POST to: `https://your-twenty-instance.com/s/webhook/transcript`
3. Map the transcription service's payload format to the expected format above
### Granola Webhook Setup
If using Granola, configure the webhook to send:
- `transcript` field with the transcript text
- Optionally include meeting metadata fields
## API Response
The webhook returns a JSON response:
```json
{
"success": true,
"noteId": "uuid-of-created-note",
"taskIds": ["uuid-of-task-1", "uuid-of-task-2"],
"summary": {
"noteCreated": true,
"tasksCreated": 2,
"actionItemsProcessed": 1,
"commitmentsProcessed": 1
}
}
```
@@ -1,30 +0,0 @@
import { type ApplicationConfig } from 'twenty-sdk/application';
const config: ApplicationConfig = {
universalIdentifier: '028754f1-3235-43b9-9427-fa6a62dbd473',
displayName: 'AI Meeting Transcript',
description:
'Automatically process meeting transcripts to extract insights, action items, and follow-ups',
applicationVariables: {
TWENTY_API_KEY: {
universalIdentifier: '1359d05c-4947-4673-809f-abd55bede365',
isSecret: true,
value: '',
description: 'Twenty API key',
},
TWENTY_API_URL: {
universalIdentifier: 'dbe83355-b574-445c-92c0-5c2b94a61ddb',
isSecret: true,
value: '',
description: 'Twenty API URL',
},
OPENAI_API_KEY: {
universalIdentifier: '9559470d-15eb-4bc2-9cbc-3bc5c869d1fd',
isSecret: true,
value: '',
description: 'OpenAI API key for transcript analysis',
},
},
};
export default config;
@@ -1,19 +0,0 @@
{
"name": "ai-meeting-transcript",
"version": "0.0.1",
"license": "MIT",
"engines": {
"node": "^24.5.0",
"npm": "please-use-yarn",
"yarn": ">=4.0.2"
},
"packageManager": "yarn@4.9.2",
"dependencies": {
"axios": "^1.12.2",
"openai": "^4.28.0",
"twenty-sdk": "0.0.3"
},
"devDependencies": {
"@types/node": "^24.7.2"
}
}
@@ -1,306 +0,0 @@
import axios from 'axios';
import OpenAI from 'openai';
import { type ServerlessFunctionConfig } from 'twenty-sdk/application';
type TranscriptWebhookPayload = {
transcript: string;
meetingTitle?: string;
meetingDate?: string;
participants?: string[];
metadata?: Record<string, unknown>;
};
type ActionItem = {
title: string;
description: string;
assignee?: string;
dueDate?: string;
};
type Commitment = {
person: string;
commitment: string;
dueDate?: string;
};
type AnalysisResult = {
summary: string;
keyPoints: string[];
actionItems: ActionItem[];
commitments: Commitment[];
};
type RichTextV2Data = {
markdown: string;
blocknote: null;
};
type TwentyApiResponse = {
id: string;
};
const OPENAI_MODEL = 'gpt-4o-mini';
const OPENAI_TEMPERATURE = 0.3;
const analyzeTranscript = async (
transcript: string,
openaiApiKey: string,
): Promise<AnalysisResult> => {
const openai = new OpenAI({ apiKey: openaiApiKey });
const prompt = `Analyze the following meeting transcript and extract:
1. A concise summary (2-3 sentences)
2. Key discussion points (bullet list)
3. Action items with titles, descriptions, and any mentioned assignees or due dates
4. Commitments made by participants with names and any mentioned due dates
Return the response as a JSON object with this structure:
{
"summary": "string",
"keyPoints": ["string"],
"actionItems": [{"title": "string", "description": "string", "assignee": "string (optional)", "dueDate": "string (optional)"}],
"commitments": [{"person": "string", "commitment": "string", "dueDate": "string (optional)"}]
}
Transcript:
${transcript}`;
const completion = await openai.chat.completions.create({
model: OPENAI_MODEL,
messages: [
{
role: 'system',
content:
'You are a meeting analysis assistant. Extract key insights, action items, and commitments from meeting transcripts. Always return valid JSON.',
},
{
role: 'user',
content: prompt,
},
],
response_format: { type: 'json_object' },
temperature: OPENAI_TEMPERATURE,
});
const content = completion.choices[0]?.message?.content;
if (!content) {
throw new Error('No response from OpenAI');
}
return JSON.parse(content) as AnalysisResult;
};
const getTwentyApiConfig = () => {
const apiKey = process.env.TWENTY_API_KEY;
if (!apiKey) {
throw new Error('TWENTY_API_KEY environment variable is not set');
}
const baseUrl = process.env.TWENTY_API_URL;
return { apiKey, baseUrl };
};
const formatNoteBody = (summary: string, keyPoints: string[]): string => {
const keyPointsList = keyPoints.map((point) => `- ${point}`).join('\n');
return `## Summary\n\n${summary}\n\n## Key Points\n\n${keyPointsList}\n\n*Generated from meeting transcript*`;
};
const createNoteInTwenty = async (
summary: string,
keyPoints: string[],
meetingTitle?: string,
meetingDate?: string,
): Promise<TwentyApiResponse> => {
const { apiKey, baseUrl } = getTwentyApiConfig();
const noteTitle =
meetingTitle ||
`Meeting Notes - ${meetingDate || new Date().toLocaleDateString()}`;
const noteBodyMarkdown = formatNoteBody(summary, keyPoints);
const requestData = {
title: noteTitle,
bodyV2: {
markdown: noteBodyMarkdown,
blocknote: null,
} satisfies RichTextV2Data,
};
try {
const { data } = await axios.post<TwentyApiResponse>(
`${baseUrl}/rest/notes`,
requestData,
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
},
);
return data;
} catch (error) {
if (axios.isAxiosError(error)) {
const errorMessage = error.response?.data
? JSON.stringify(error.response.data, null, 2)
: error.message;
const status = error.response?.status;
throw new Error(
`Failed to create note: ${errorMessage}. Status: ${status}`,
);
}
throw error;
}
};
const createTaskInTwenty = async (
actionItem: ActionItem,
): Promise<TwentyApiResponse> => {
const { apiKey, baseUrl } = getTwentyApiConfig();
const taskData: {
title: string;
bodyV2: RichTextV2Data;
dueAt?: string;
} = {
title: actionItem.title,
bodyV2: {
markdown: actionItem.description,
blocknote: null,
},
};
if (actionItem.dueDate) {
taskData.dueAt = new Date(actionItem.dueDate).toISOString();
}
try {
const { data } = await axios.post<TwentyApiResponse>(
`${baseUrl}/rest/tasks`,
taskData,
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
},
);
return data;
} catch (error) {
if (axios.isAxiosError(error)) {
const errorMessage = error.response?.data
? JSON.stringify(error.response.data, null, 2)
: error.message;
const status = error.response?.status;
throw new Error(
`Failed to create task "${actionItem.title}": ${errorMessage}. Status: ${status}`,
);
}
throw error;
}
};
const createTasksFromActionItems = async (
actionItems: ActionItem[],
noteId: string,
): Promise<string[]> => {
const taskIds: string[] = [];
for (const actionItem of actionItems) {
try {
const taskDescription = `${actionItem.description}\n\n*Related to meeting note: ${noteId}*`;
const task = await createTaskInTwenty({
...actionItem,
description: taskDescription,
});
taskIds.push(task.id);
} catch (error) {
// Task creation failed, continue with next task
}
}
return taskIds;
};
const createTasksFromCommitments = async (
commitments: Commitment[],
noteId: string,
): Promise<string[]> => {
const taskIds: string[] = [];
for (const commitment of commitments) {
try {
const taskDescription = `Commitment from ${commitment.person}: ${commitment.commitment}\n\n*Related to meeting note: ${noteId}*`;
const task = await createTaskInTwenty({
title: `Follow up: ${commitment.commitment}`,
description: taskDescription,
dueDate: commitment.dueDate,
});
taskIds.push(task.id);
} catch (error) {
// Commitment task creation failed, continue with next commitment
}
}
return taskIds;
};
export const main = async (
params: TranscriptWebhookPayload,
): Promise<object> => {
const { transcript, meetingTitle, meetingDate } = params;
if (!transcript || typeof transcript !== 'string') {
throw new Error('Transcript is required and must be a string');
}
const openaiApiKey = process.env.OPENAI_API_KEY;
if (!openaiApiKey) {
throw new Error('OPENAI_API_KEY environment variable is not set');
}
const analysis = await analyzeTranscript(transcript, openaiApiKey);
const note = await createNoteInTwenty(
analysis.summary,
analysis.keyPoints,
meetingTitle,
meetingDate,
);
const actionItemTaskIds = await createTasksFromActionItems(
analysis.actionItems,
note.id,
);
const commitmentTaskIds = await createTasksFromCommitments(
analysis.commitments,
note.id,
);
const allTaskIds = [...actionItemTaskIds, ...commitmentTaskIds];
return {
success: true,
noteId: note.id,
taskIds: allTaskIds,
summary: {
noteCreated: true,
tasksCreated: allTaskIds.length,
actionItemsProcessed: analysis.actionItems.length,
commitmentsProcessed: analysis.commitments.length,
},
};
};
export const config: ServerlessFunctionConfig = {
universalIdentifier: 'dae52ab2-174f-4f81-a031-604ee2e81eba',
name: 'ai-meeting-transcriptor',
triggers: [
{
universalIdentifier: 'b011303d-2c24-44d4-9923-55eb060a1ff6',
type: 'route',
path: '/webhook/transcript',
httpMethod: 'POST',
isAuthRequired: false,
},
],
};
@@ -1,26 +0,0 @@
{
"compileOnSave": false,
"compilerOptions": {
"sourceMap": true,
"declaration": true,
"outDir": "./dist",
"rootDir": ".",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"strict": true,
"target": "es2018",
"module": "esnext",
"lib": ["es2020", "dom"],
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"resolveJsonModule": true
},
"exclude": [
"node_modules",
"dist",
"**/*.test.ts",
"**/*.spec.ts"
]
}
@@ -1,435 +0,0 @@
# This file is generated by running "yarn install" inside your project.
# Manual changes might be lost - proceed with caution!
__metadata:
version: 8
cacheKey: 10c0
"@types/node-fetch@npm:^2.6.4":
version: 2.6.13
resolution: "@types/node-fetch@npm:2.6.13"
dependencies:
"@types/node": "npm:*"
form-data: "npm:^4.0.4"
checksum: 10c0/6313c89f62c50bd0513a6839cdff0a06727ac5495ccbb2eeda51bb2bbbc4f3c0a76c0393a491b7610af703d3d2deb6cf60e37e59c81ceeca803ffde745dbf309
languageName: node
linkType: hard
"@types/node@npm:*, @types/node@npm:^24.7.2":
version: 24.9.2
resolution: "@types/node@npm:24.9.2"
dependencies:
undici-types: "npm:~7.16.0"
checksum: 10c0/7905d43f65cee72ef475fe76316e10bbf6ac5d08a7f0f6c38f2b6285d7ca3009e8fcafc8f8a1d2bf3f55889c9c278dbb203a9081fd0cf2d6d62161703924c6fa
languageName: node
linkType: hard
"@types/node@npm:^18.11.18":
version: 18.19.130
resolution: "@types/node@npm:18.19.130"
dependencies:
undici-types: "npm:~5.26.4"
checksum: 10c0/22ba2bc9f8863101a7e90a56aaeba1eb3ebdc51e847cef4a6d188967ab1acbce9b4f92251372fd0329ecb924bbf610509e122c3dfe346c04dbad04013d4ad7d0
languageName: node
linkType: hard
"abort-controller@npm:^3.0.0":
version: 3.0.0
resolution: "abort-controller@npm:3.0.0"
dependencies:
event-target-shim: "npm:^5.0.0"
checksum: 10c0/90ccc50f010250152509a344eb2e71977fbf8db0ab8f1061197e3275ddf6c61a41a6edfd7b9409c664513131dd96e962065415325ef23efa5db931b382d24ca5
languageName: node
linkType: hard
"agentkeepalive@npm:^4.2.1":
version: 4.6.0
resolution: "agentkeepalive@npm:4.6.0"
dependencies:
humanize-ms: "npm:^1.2.1"
checksum: 10c0/235c182432f75046835b05f239708107138a40103deee23b6a08caee5136873709155753b394ec212e49e60e94a378189562cb01347765515cff61b692c69187
languageName: node
linkType: hard
"ai-meeting-transcript@workspace:.":
version: 0.0.0-use.local
resolution: "ai-meeting-transcript@workspace:."
dependencies:
"@types/node": "npm:^24.7.2"
axios: "npm:^1.12.2"
openai: "npm:^4.28.0"
twenty-sdk: "npm:^0.0.2"
languageName: unknown
linkType: soft
"async-function@npm:^1.0.0":
version: 1.0.0
resolution: "async-function@npm:1.0.0"
checksum: 10c0/669a32c2cb7e45091330c680e92eaeb791bc1d4132d827591e499cd1f776ff5a873e77e5f92d0ce795a8d60f10761dec9ddfe7225a5de680f5d357f67b1aac73
languageName: node
linkType: hard
"async-generator-function@npm:^1.0.0":
version: 1.0.0
resolution: "async-generator-function@npm:1.0.0"
checksum: 10c0/2c50ef856c543ad500d8d8777d347e3c1ba623b93e99c9263ecc5f965c1b12d2a140e2ab6e43c3d0b85366110696f28114649411cbcd10b452a92a2318394186
languageName: node
linkType: hard
"asynckit@npm:^0.4.0":
version: 0.4.0
resolution: "asynckit@npm:0.4.0"
checksum: 10c0/d73e2ddf20c4eb9337e1b3df1a0f6159481050a5de457c55b14ea2e5cb6d90bb69e004c9af54737a5ee0917fcf2c9e25de67777bbe58261847846066ba75bc9d
languageName: node
linkType: hard
"axios@npm:^1.12.2":
version: 1.13.1
resolution: "axios@npm:1.13.1"
dependencies:
follow-redirects: "npm:^1.15.6"
form-data: "npm:^4.0.4"
proxy-from-env: "npm:^1.1.0"
checksum: 10c0/de9c3c6de43d3ee1146d3afe78645f19450cac6a5d7235bef8b8e8eeb705c2e47e2d231dea99cecaec4dae1897c521118ca9413b9d474063c719c4d94c5b9adc
languageName: node
linkType: hard
"call-bind-apply-helpers@npm:^1.0.1, call-bind-apply-helpers@npm:^1.0.2":
version: 1.0.2
resolution: "call-bind-apply-helpers@npm:1.0.2"
dependencies:
es-errors: "npm:^1.3.0"
function-bind: "npm:^1.1.2"
checksum: 10c0/47bd9901d57b857590431243fea704ff18078b16890a6b3e021e12d279bbf211d039155e27d7566b374d49ee1f8189344bac9833dec7a20cdec370506361c938
languageName: node
linkType: hard
"combined-stream@npm:^1.0.8":
version: 1.0.8
resolution: "combined-stream@npm:1.0.8"
dependencies:
delayed-stream: "npm:~1.0.0"
checksum: 10c0/0dbb829577e1b1e839fa82b40c07ffaf7de8a09b935cadd355a73652ae70a88b4320db322f6634a4ad93424292fa80973ac6480986247f1734a1137debf271d5
languageName: node
linkType: hard
"delayed-stream@npm:~1.0.0":
version: 1.0.0
resolution: "delayed-stream@npm:1.0.0"
checksum: 10c0/d758899da03392e6712f042bec80aa293bbe9e9ff1b2634baae6a360113e708b91326594c8a486d475c69d6259afb7efacdc3537bfcda1c6c648e390ce601b19
languageName: node
linkType: hard
"dunder-proto@npm:^1.0.1":
version: 1.0.1
resolution: "dunder-proto@npm:1.0.1"
dependencies:
call-bind-apply-helpers: "npm:^1.0.1"
es-errors: "npm:^1.3.0"
gopd: "npm:^1.2.0"
checksum: 10c0/199f2a0c1c16593ca0a145dbf76a962f8033ce3129f01284d48c45ed4e14fea9bbacd7b3610b6cdc33486cef20385ac054948fefc6272fcce645c09468f93031
languageName: node
linkType: hard
"es-define-property@npm:^1.0.1":
version: 1.0.1
resolution: "es-define-property@npm:1.0.1"
checksum: 10c0/3f54eb49c16c18707949ff25a1456728c883e81259f045003499efba399c08bad00deebf65cccde8c0e07908c1a225c9d472b7107e558f2a48e28d530e34527c
languageName: node
linkType: hard
"es-errors@npm:^1.3.0":
version: 1.3.0
resolution: "es-errors@npm:1.3.0"
checksum: 10c0/0a61325670072f98d8ae3b914edab3559b6caa980f08054a3b872052640d91da01d38df55df797fcc916389d77fc92b8d5906cf028f4db46d7e3003abecbca85
languageName: node
linkType: hard
"es-object-atoms@npm:^1.0.0, es-object-atoms@npm:^1.1.1":
version: 1.1.1
resolution: "es-object-atoms@npm:1.1.1"
dependencies:
es-errors: "npm:^1.3.0"
checksum: 10c0/65364812ca4daf48eb76e2a3b7a89b3f6a2e62a1c420766ce9f692665a29d94fe41fe88b65f24106f449859549711e4b40d9fb8002d862dfd7eb1c512d10be0c
languageName: node
linkType: hard
"es-set-tostringtag@npm:^2.1.0":
version: 2.1.0
resolution: "es-set-tostringtag@npm:2.1.0"
dependencies:
es-errors: "npm:^1.3.0"
get-intrinsic: "npm:^1.2.6"
has-tostringtag: "npm:^1.0.2"
hasown: "npm:^2.0.2"
checksum: 10c0/ef2ca9ce49afe3931cb32e35da4dcb6d86ab02592cfc2ce3e49ced199d9d0bb5085fc7e73e06312213765f5efa47cc1df553a6a5154584b21448e9fb8355b1af
languageName: node
linkType: hard
"event-target-shim@npm:^5.0.0":
version: 5.0.1
resolution: "event-target-shim@npm:5.0.1"
checksum: 10c0/0255d9f936215fd206156fd4caa9e8d35e62075d720dc7d847e89b417e5e62cf1ce6c9b4e0a1633a9256de0efefaf9f8d26924b1f3c8620cffb9db78e7d3076b
languageName: node
linkType: hard
"follow-redirects@npm:^1.15.6":
version: 1.15.11
resolution: "follow-redirects@npm:1.15.11"
peerDependenciesMeta:
debug:
optional: true
checksum: 10c0/d301f430542520a54058d4aeeb453233c564aaccac835d29d15e050beb33f339ad67d9bddbce01739c5dc46a6716dbe3d9d0d5134b1ca203effa11a7ef092343
languageName: node
linkType: hard
"form-data-encoder@npm:1.7.2":
version: 1.7.2
resolution: "form-data-encoder@npm:1.7.2"
checksum: 10c0/56553768037b6d55d9de524f97fe70555f0e415e781cb56fc457a68263de3d40fadea2304d4beef2d40b1a851269bd7854e42c362107071892cb5238debe9464
languageName: node
linkType: hard
"form-data@npm:^4.0.4":
version: 4.0.4
resolution: "form-data@npm:4.0.4"
dependencies:
asynckit: "npm:^0.4.0"
combined-stream: "npm:^1.0.8"
es-set-tostringtag: "npm:^2.1.0"
hasown: "npm:^2.0.2"
mime-types: "npm:^2.1.12"
checksum: 10c0/373525a9a034b9d57073e55eab79e501a714ffac02e7a9b01be1c820780652b16e4101819785e1e18f8d98f0aee866cc654d660a435c378e16a72f2e7cac9695
languageName: node
linkType: hard
"formdata-node@npm:^4.3.2":
version: 4.4.1
resolution: "formdata-node@npm:4.4.1"
dependencies:
node-domexception: "npm:1.0.0"
web-streams-polyfill: "npm:4.0.0-beta.3"
checksum: 10c0/74151e7b228ffb33b565cec69182694ad07cc3fdd9126a8240468bb70a8ba66e97e097072b60bcb08729b24c7ce3fd3e0bd7f1f80df6f9f662b9656786e76f6a
languageName: node
linkType: hard
"function-bind@npm:^1.1.2":
version: 1.1.2
resolution: "function-bind@npm:1.1.2"
checksum: 10c0/d8680ee1e5fcd4c197e4ac33b2b4dce03c71f4d91717292785703db200f5c21f977c568d28061226f9b5900cbcd2c84463646134fd5337e7925e0942bc3f46d5
languageName: node
linkType: hard
"generator-function@npm:^2.0.0":
version: 2.0.1
resolution: "generator-function@npm:2.0.1"
checksum: 10c0/8a9f59df0f01cfefafdb3b451b80555e5cf6d76487095db91ac461a0e682e4ff7a9dbce15f4ecec191e53586d59eece01949e05a4b4492879600bbbe8e28d6b8
languageName: node
linkType: hard
"get-intrinsic@npm:^1.2.6":
version: 1.3.1
resolution: "get-intrinsic@npm:1.3.1"
dependencies:
async-function: "npm:^1.0.0"
async-generator-function: "npm:^1.0.0"
call-bind-apply-helpers: "npm:^1.0.2"
es-define-property: "npm:^1.0.1"
es-errors: "npm:^1.3.0"
es-object-atoms: "npm:^1.1.1"
function-bind: "npm:^1.1.2"
generator-function: "npm:^2.0.0"
get-proto: "npm:^1.0.1"
gopd: "npm:^1.2.0"
has-symbols: "npm:^1.1.0"
hasown: "npm:^2.0.2"
math-intrinsics: "npm:^1.1.0"
checksum: 10c0/9f4ab0cf7efe0fd2c8185f52e6f637e708f3a112610c88869f8f041bb9ecc2ce44bf285dfdbdc6f4f7c277a5b88d8e94a432374d97cca22f3de7fc63795deb5d
languageName: node
linkType: hard
"get-proto@npm:^1.0.1":
version: 1.0.1
resolution: "get-proto@npm:1.0.1"
dependencies:
dunder-proto: "npm:^1.0.1"
es-object-atoms: "npm:^1.0.0"
checksum: 10c0/9224acb44603c5526955e83510b9da41baf6ae73f7398875fba50edc5e944223a89c4a72b070fcd78beb5f7bdda58ecb6294adc28f7acfc0da05f76a2399643c
languageName: node
linkType: hard
"gopd@npm:^1.2.0":
version: 1.2.0
resolution: "gopd@npm:1.2.0"
checksum: 10c0/50fff1e04ba2b7737c097358534eacadad1e68d24cccee3272e04e007bed008e68d2614f3987788428fd192a5ae3889d08fb2331417e4fc4a9ab366b2043cead
languageName: node
linkType: hard
"has-symbols@npm:^1.0.3, has-symbols@npm:^1.1.0":
version: 1.1.0
resolution: "has-symbols@npm:1.1.0"
checksum: 10c0/dde0a734b17ae51e84b10986e651c664379018d10b91b6b0e9b293eddb32f0f069688c841fb40f19e9611546130153e0a2a48fd7f512891fb000ddfa36f5a20e
languageName: node
linkType: hard
"has-tostringtag@npm:^1.0.2":
version: 1.0.2
resolution: "has-tostringtag@npm:1.0.2"
dependencies:
has-symbols: "npm:^1.0.3"
checksum: 10c0/a8b166462192bafe3d9b6e420a1d581d93dd867adb61be223a17a8d6dad147aa77a8be32c961bb2f27b3ef893cae8d36f564ab651f5e9b7938ae86f74027c48c
languageName: node
linkType: hard
"hasown@npm:^2.0.2":
version: 2.0.2
resolution: "hasown@npm:2.0.2"
dependencies:
function-bind: "npm:^1.1.2"
checksum: 10c0/3769d434703b8ac66b209a4cca0737519925bbdb61dd887f93a16372b14694c63ff4e797686d87c90f08168e81082248b9b028bad60d4da9e0d1148766f56eb9
languageName: node
linkType: hard
"humanize-ms@npm:^1.2.1":
version: 1.2.1
resolution: "humanize-ms@npm:1.2.1"
dependencies:
ms: "npm:^2.0.0"
checksum: 10c0/f34a2c20161d02303c2807badec2f3b49cbfbbb409abd4f95a07377ae01cfe6b59e3d15ac609cffcd8f2521f0eb37b7e1091acf65da99aa2a4f1ad63c21e7e7a
languageName: node
linkType: hard
"math-intrinsics@npm:^1.1.0":
version: 1.1.0
resolution: "math-intrinsics@npm:1.1.0"
checksum: 10c0/7579ff94e899e2f76ab64491d76cf606274c874d8f2af4a442c016bd85688927fcfca157ba6bf74b08e9439dc010b248ce05b96cc7c126a354c3bae7fcb48b7f
languageName: node
linkType: hard
"mime-db@npm:1.52.0":
version: 1.52.0
resolution: "mime-db@npm:1.52.0"
checksum: 10c0/0557a01deebf45ac5f5777fe7740b2a5c309c6d62d40ceab4e23da9f821899ce7a900b7ac8157d4548ddbb7beffe9abc621250e6d182b0397ec7f10c7b91a5aa
languageName: node
linkType: hard
"mime-types@npm:^2.1.12":
version: 2.1.35
resolution: "mime-types@npm:2.1.35"
dependencies:
mime-db: "npm:1.52.0"
checksum: 10c0/82fb07ec56d8ff1fc999a84f2f217aa46cb6ed1033fefaabd5785b9a974ed225c90dc72fff460259e66b95b73648596dbcc50d51ed69cdf464af2d237d3149b2
languageName: node
linkType: hard
"ms@npm:^2.0.0":
version: 2.1.3
resolution: "ms@npm:2.1.3"
checksum: 10c0/d924b57e7312b3b63ad21fc5b3dc0af5e78d61a1fc7cfb5457edaf26326bf62be5307cc87ffb6862ef1c2b33b0233cdb5d4f01c4c958cc0d660948b65a287a48
languageName: node
linkType: hard
"node-domexception@npm:1.0.0":
version: 1.0.0
resolution: "node-domexception@npm:1.0.0"
checksum: 10c0/5e5d63cda29856402df9472335af4bb13875e1927ad3be861dc5ebde38917aecbf9ae337923777af52a48c426b70148815e890a5d72760f1b4d758cc671b1a2b
languageName: node
linkType: hard
"node-fetch@npm:^2.6.7":
version: 2.7.0
resolution: "node-fetch@npm:2.7.0"
dependencies:
whatwg-url: "npm:^5.0.0"
peerDependencies:
encoding: ^0.1.0
peerDependenciesMeta:
encoding:
optional: true
checksum: 10c0/b55786b6028208e6fbe594ccccc213cab67a72899c9234eb59dba51062a299ea853210fcf526998eaa2867b0963ad72338824450905679ff0fa304b8c5093ae8
languageName: node
linkType: hard
"openai@npm:^4.28.0":
version: 4.104.0
resolution: "openai@npm:4.104.0"
dependencies:
"@types/node": "npm:^18.11.18"
"@types/node-fetch": "npm:^2.6.4"
abort-controller: "npm:^3.0.0"
agentkeepalive: "npm:^4.2.1"
form-data-encoder: "npm:1.7.2"
formdata-node: "npm:^4.3.2"
node-fetch: "npm:^2.6.7"
peerDependencies:
ws: ^8.18.0
zod: ^3.23.8
peerDependenciesMeta:
ws:
optional: true
zod:
optional: true
bin:
openai: bin/cli
checksum: 10c0/c4f2e837684ed96b8cec58c65a584646d667c69918f29052775e2e8c05ff5c860d8b58214a7770bc6895ca8602480420c1db6a5392dd250179eb0b91c2b19a2f
languageName: node
linkType: hard
"proxy-from-env@npm:^1.1.0":
version: 1.1.0
resolution: "proxy-from-env@npm:1.1.0"
checksum: 10c0/fe7dd8b1bdbbbea18d1459107729c3e4a2243ca870d26d34c2c1bcd3e4425b7bcc5112362df2d93cc7fb9746f6142b5e272fd1cc5c86ddf8580175186f6ad42b
languageName: node
linkType: hard
"tr46@npm:~0.0.3":
version: 0.0.3
resolution: "tr46@npm:0.0.3"
checksum: 10c0/047cb209a6b60c742f05c9d3ace8fa510bff609995c129a37ace03476a9b12db4dbf975e74600830ef0796e18882b2381fb5fb1f6b4f96b832c374de3ab91a11
languageName: node
linkType: hard
"twenty-sdk@npm:^0.0.2":
version: 0.0.2
resolution: "twenty-sdk@npm:0.0.2"
checksum: 10c0/99e6fe86059d847b548c1f03e0f0c59a4d540caf1d28dd4500f1f5f0094196985ded955801274de9e72ff03e3d1f41e9a509b4c2c5a02ffc8a027277b1e35d8e
languageName: node
linkType: hard
"undici-types@npm:~5.26.4":
version: 5.26.5
resolution: "undici-types@npm:5.26.5"
checksum: 10c0/bb673d7876c2d411b6eb6c560e0c571eef4a01c1c19925175d16e3a30c4c428181fb8d7ae802a261f283e4166a0ac435e2f505743aa9e45d893f9a3df017b501
languageName: node
linkType: hard
"undici-types@npm:~7.16.0":
version: 7.16.0
resolution: "undici-types@npm:7.16.0"
checksum: 10c0/3033e2f2b5c9f1504bdc5934646cb54e37ecaca0f9249c983f7b1fc2e87c6d18399ebb05dc7fd5419e02b2e915f734d872a65da2e3eeed1813951c427d33cc9a
languageName: node
linkType: hard
"web-streams-polyfill@npm:4.0.0-beta.3":
version: 4.0.0-beta.3
resolution: "web-streams-polyfill@npm:4.0.0-beta.3"
checksum: 10c0/a9596779db2766990117ed3a158e0b0e9f69b887a6d6ba0779940259e95f99dc3922e534acc3e5a117b5f5905300f527d6fbf8a9f0957faf1d8e585ce3452e8e
languageName: node
linkType: hard
"webidl-conversions@npm:^3.0.0":
version: 3.0.1
resolution: "webidl-conversions@npm:3.0.1"
checksum: 10c0/5612d5f3e54760a797052eb4927f0ddc01383550f542ccd33d5238cfd65aeed392a45ad38364970d0a0f4fea32e1f4d231b3d8dac4a3bdd385e5cf802ae097db
languageName: node
linkType: hard
"whatwg-url@npm:^5.0.0":
version: 5.0.0
resolution: "whatwg-url@npm:5.0.0"
dependencies:
tr46: "npm:~0.0.3"
webidl-conversions: "npm:^3.0.0"
checksum: 10c0/1588bed84d10b72d5eec1d0faa0722ba1962f1821e7539c535558fb5398d223b0c50d8acab950b8c488b4ba69043fd833cc2697056b167d8ad46fac3995a55d5
languageName: node
linkType: hard
@@ -1,109 +0,0 @@
# Fireflies Integration Environment Variables
# Copy this file to .env and fill in your actual values
# =============================================================================
# REQUIRED: Authentication & API Keys
# =============================================================================
# Secret key for HMAC signature verification of Fireflies webhooks
# This must match the secret configured in your Fireflies webhook settings
# Get this from: https://app.fireflies.ai/settings#DeveloperSettings
FIREFLIES_WEBHOOK_SECRET=your_webhook_secret_here
# Fireflies API key for fetching meeting data from GraphQL API
# Get this from: https://app.fireflies.ai/settings#DeveloperSettings
FIREFLIES_API_KEY=your_fireflies_api_key_here
# Fireflies plan level - affects which fields are available
# Options: free, pro, business, enterprise
# This controls which GraphQL fields are requested to avoid 403 errors
FIREFLIES_PLAN_LEVEL=pro
# Twenty CRM API key for authentication
# Generate this from your Twenty instance: Settings > Developers > API Keys
TWENTY_API_KEY=your_twenty_api_key_here
# =============================================================================
# Server Configuration
# =============================================================================
# Twenty CRM server URL
# Use http://localhost:3000 for local development
# Use your production URL for deployed instances
SERVER_URL=http://localhost:3000
# =============================================================================
# Contact Management
# =============================================================================
# Automatically create contacts for unknown participants (true/false)
# If true, new Person records will be created for meeting participants not found in CRM
# If false, only meetings with existing contacts will be fully processed
AUTO_CREATE_CONTACTS=true
# =============================================================================
# Summary Processing Configuration
# =============================================================================
# Strategy for handling async summary generation
# Options:
# - immediate_with_retry: Attempts immediate fetch with retry logic (RECOMMENDED)
# - delayed_polling: Schedules background polling for summaries
# - basic_only: Creates records without waiting for summaries
FIREFLIES_SUMMARY_STRATEGY=immediate_with_retry
# Number of retry attempts when fetching summary data
# Used with immediate_with_retry strategy
# Recommended: 3-5 attempts (summaries can take up to 10 minutes but rate limit is low)
FIREFLIES_RETRY_ATTEMPTS=5
# Delay in milliseconds between retry attempts (with exponential backoff)
# Each retry will wait: RETRY_DELAY * attempt_number
# Example: 120000ms means 2min, 4min, 6min... for extended backoff
# Total max time with 5 attempts: ~15 minutes
FIREFLIES_RETRY_DELAY=120000
# Polling interval in milliseconds for delayed_polling strategy
# How often to check if summary is ready
# Recommended: 60000 (60 seconds) for extended processing
FIREFLIES_POLL_INTERVAL=120000
# Maximum number of polling attempts for delayed_polling strategy
# Total max time = POLL_INTERVAL * MAX_POLLS
# Example: 2min * 5 = 10 minutes maximum
FIREFLIES_MAX_POLLS=5
# =============================================================================
# Debugging & Logging
# =============================================================================
# Log level: silent, error, warn, info, debug (default: error)
# Controls verbosity of console output
# - silent: No console output
# - error: Only errors (production default)
# - warn: Warnings and errors
# - info: Info, warnings, and errors
# - debug: All logs including detailed debugging
LOG_LEVEL=error
# =============================================================================
# Configuration Notes
# =============================================================================
#
# Webhook Setup:
# 1. Configure your Fireflies webhook at: https://app.fireflies.ai/settings#DeveloperSettings
# 2. Webhook URL: https://your-twenty-instance.com/s/webhook/fireflies
# 3. Event Type: "Transcription completed"
# 4. Secret: Same value as FIREFLIES_WEBHOOK_SECRET above, genereate it there
#
# Summary Strategy Guide:
# - immediate_with_retry: Best for most use cases - fast with reliability
# - delayed_polling: Use if your server is heavily loaded
# - basic_only: Use if you only need transcript links without AI summaries
#
# Performance Tuning:
# - Fireflies summaries can take 5-15 minutes to generate after transcription
# - Use 30+ retry attempts with 30s delay for 15-minute coverage
# - Consider delayed_polling strategy for heavily loaded servers
# - Monitor DEBUG_LOGS to tune timing for your Fireflies account
#
File diff suppressed because one or more lines are too long
@@ -1,3 +0,0 @@
yarnPath: .yarn/releases/yarn-4.9.2.cjs
nodeLinker: node-modules
@@ -1,96 +0,0 @@
# Changelog
## [0.2.2] - 2025-11-04
### Added
- **Enhanced logging system**: Introduced configurable `AppLogger` class with log level support (debug, info, warn, error, silent)
- Environment-based log level configuration via `LOG_LEVEL` environment variable
- Test environment detection to prevent log noise during testing
- Context-aware logging with proper prefixes for better debugging
- **Improved error handling**: Enhanced webhook signature verification with detailed debug logging
- **Better debugging capabilities**: Added comprehensive logging throughout webhook processing pipeline
### Enhanced
- **Webhook signature verification**: Improved signature validation with detailed logging for troubleshooting
- **Error messages**: More descriptive error logging for failed operations and security violations
- **Development experience**: Better debugging information for webhook processing and API interactions
## [0.2.1] - 2025-11-03
### Added
- **Import status tracking**: Added four new meeting fields to track import status and failure handling:
- `importStatus` (SELECT) - Tracks SUCCESS, FAILED, PENDING, RETRYING states
- `importError` (TEXT) - Stores error messages when imports fail
- `lastImportAttempt` (DATE_TIME) - Timestamp of the last import attempt
- `importAttempts` (NUMBER) - Counter for number of import attempts
- **Automatic failure tracking**: Enhanced webhook handler to automatically create failed meeting records when processing fails
- **Failed meeting formatter**: Added `toFailedMeetingCreateInput()` method to create standardized failed meeting records
### Enhanced
- **Meeting type definition**: Extended `MeetingCreateInput` type with import tracking fields
- **Success status tracking**: Successful meeting imports now automatically set `importStatus: 'SUCCESS'` and track timestamps
- **Error handling**: Webhook processing failures are now captured and stored as meeting records for visibility and potential retry
## [0.2.0] - 2025-11-03
### Changed
- **Major refactoring**: Split monolithic `receive-fireflies-notes.ts` into modular architecture:
- `fireflies-api-client.ts` - Fireflies GraphQL API integration with retry logic
- `twenty-crm-service.ts` - Twenty CRM operations (contacts, notes, meetings)
- `formatters.ts` - Meeting and note body formatting
- `webhook-handler.ts` - Main webhook orchestration
- `webhook-validator.ts` - HMAC signature verification
- `utils.ts` - Shared utility functions
- `types.ts` - Centralized type definitions
- **Schema update**: Changed Meeting `notes` field from `RICH_TEXT` to `RELATION` type linking to Note object
- Enhanced participant extraction from multiple Fireflies API data sources (participants, meeting_attendees, speakers, meeting_attendance)
- Improved organizer email matching with name-based heuristics
- Updated note creation to use `bodyV2.markdown` format instead of legacy `body` field
- Modernized Meeting object schema with proper link field types for transcriptUrl and recordingUrl
- Enhanced test suite with improved mocking for new modular structure
- **Configuration optimization**: Reduced default retry attempts from 30 to 5 with increased delay (120s) to better respect Fireflies API rate limits (50 requests/day for free/pro plans)
- Updated field setup script to support relation field creation with Note object
- Restructured exports: types now exported from `types.ts`, runtime functions from `index.ts`
- Updated import paths in action handlers to use centralized index exports
- Added TypeScript path mappings for `twenty-sdk` in workspace configuration
### Added
- `createNoteTarget` method for linking notes to multiple participants
- Support for extracting participants from extended Fireflies API response formats
- Better organizer identification logic matching email usernames to speaker names
- `axios` dependency for improved HTTP client capabilities
- API subscription plan documentation highlighting rate limit differences (50/day vs 60/minute)
- Enhanced README with rate limiting guidance and configuration documentation
- Relation field creation support in field provisioning script
### Fixed
- Note linking now properly associates a single note with multiple participants in 1:1 meetings
- Participant extraction handles missing email addresses gracefully
- Improved handling of various Fireflies participant data structures
- Test mocks updated to use string format for participants (`"Name <email>"`) matching Fireflies API response format
- Test assertions updated to validate `bodyV2.markdown` instead of deprecated `body` field
## [0.1.0] - 2025-11-02
### Added
- HMAC SHA-256 signature verification for incoming Fireflies webhooks
- Fireflies GraphQL client with retry logic, timeout handling, and summary readiness detection
- Summary-focused meeting processing that extracts action items, sentiment, keywords, and transcript/recording links
- Scripted custom field provisioning via `yarn setup:fields`
- Local webhook testing workflow via `yarn test:webhook`
- Comprehensive Jest suite (15 tests) covering authentication, API integration, summary strategies, and error handling
### Changed
- Replaced legacy JSON manifests with TypeScript configuration:
- `application.config.ts` now declares app metadata and configuration variables
- `src/objects/meeting.ts` defines the Meeting object via `@ObjectMetadata`
- `src/actions/receive-fireflies-notes.ts` exports the Fireflies webhook action plus its runtime config
- Updated documentation (README, Deployment Guide, Testing) to reflect the new project layout and workflows
- Switched utility scripts to `tsx` and aligned package management with the hello-world example
### Fixed
- Resolved real-world Fireflies payload mismatch by adopting the minimal webhook schema
- Replaced body-based secrets with header-driven HMAC verification
- Ensured graceful degradation when summaries are pending or Fireflies is temporarily unavailable
@@ -1,277 +0,0 @@
# Fireflies
Automatically captures meeting notes with AI-generated summaries and insights from Fireflies.ai into your Twenty CRM.
## Integration Overview
**Fireflies webhook → Fireflies API → Twenty CRM with summary-focused insights**
- **Summary-first approach** - Prioritizes action items, keywords, and sentiment over raw transcripts
- **HMAC signature verification** - Secure webhook authentication
- **Two-phase architecture** - Webhook notification → API data fetch → CRM record creation
- **Contact identification** - Matches participants to existing contacts or creates new ones
- **One-on-one meetings** (2 people) → Individual notes linked to each contact
- **Multi-party meetings** (3+ people) → Meeting records with all attendees
- **Business intelligence extraction** - Action items, sentiment scores, topics, meeting types
- **Smart retry logic** - Handles async summary generation with exponential backoff
- **Links transcripts and recordings** - Easy access to full Fireflies content
- **Duplicate prevention** - Checks for existing meetings by title
## API Access by Subscription Plan
Fireflies API access varies significantly by subscription tier:
| Feature | Free | Pro | Business | Enterprise |
|---------|------|-----|----------|------------|
| **API Rate Limit** | 50 requests/day | 50 requests/day | 60 requests/minute | 60 requests/minute |
| **Storage** | 800 mins/seat | 8,000 mins/seat | Unlimited | Unlimited |
| **AI Summaries** | Limited (20 credits) | Unlimited | Unlimited | Unlimited |
| **Video Upload** | 100MB max | 1.5GB max | 1.5GB max | 1.5GB max |
| **Advanced Features** | Basic transcription | AI apps, analytics | Team analytics, CI | Full API, SSO, compliance |
**Key Design Pattern:** Subscription-based API access uses **tiered rate limiting** rather than feature gating. Lower tiers get severely restricted throughput (50/day vs 60/minute = 1,700x difference), making production integrations effectively require Business+ plans.
**Pro Plan Limitation:** Despite "unlimited" AI summaries, the 50 requests/day limit severely constrains production usage for meeting-heavy organizations.
## What Gets Captured
### Summary & Insights
- **Action Items** - Concrete next steps and commitments
- **Keywords** - Key topics and themes discussed
- **Overview** - Executive summary of the meeting
- **Topics Discussed** - Main discussion points
- **Meeting Type** - Context (sales call, standup, demo, etc.)
### Analytics
- **Sentiment Analysis** - Positive/negative/neutral percentages for deal health
- **Engagement Metrics** - Participation levels (future)
### Resources
- **Transcript Link** - Quick access to full Fireflies transcript
- **Recording Link** - Video/audio recording when available
## Quick Start
### Installation
```bash
# Step 1: Authenticate with Twenty
npx twenty-cli auth login
# Step 2: Sync the app to create Meeting object
npx twenty-cli app sync packages/twenty-apps/fireflies
# Step 3: Install dependencies
yarn install
# Step 4: Add custom fields
yarn setup:fields
```
(TODO: change when fields setup internal support)
### Configuration
⚠️ **Important**: The integration uses **conservative retry settings** to respect Fireflies' 50 requests/day API limit with free/pro plans. You may increase for more reactivity with higher plans.
**Required Environment Variables:**
```bash
FIREFLIES_API_KEY=your_api_key # From Fireflies settings
TWENTY_API_KEY=your_api_key # From Twenty CRM settings
SERVER_URL=https://your-domain.twenty.com
```
**Optional (Recommended):**
```bash
FIREFLIES_WEBHOOK_SECRET=your_secret # For webhook security
```
📖 **For detailed configuration, troubleshooting, and rate limit management**, see [WEBHOOK_CONFIGURATION.md](./WEBHOOK_CONFIGURATION.md)
### What Gets Created
#### Basic Installation (Step 2)
The `app sync` command creates:
- ✅ Meeting object with basic `name` field
- ✅ Webhook endpoint at `/s/webhook/fireflies`
#### After Custom Fields Setup (Step 4)
The `setup:fields` script adds 13 custom fields to store rich Fireflies data:
| Field Name | Type | Label | Description |
|------------|------|-------|-------------|
| `notes` | RICH_TEXT | Meeting Notes | AI-generated summary with overview, topics, action items, and insights |
| `meetingDate` | DATE_TIME | Meeting Date | Date and time when the meeting occurred |
| `duration` | NUMBER | Duration (minutes) | Meeting duration in minutes |
| `meetingType` | TEXT | Meeting Type | Type of meeting (e.g., Sales Call, Sprint Planning, 1:1) |
| `keywords` | TEXT | Keywords | Key topics and themes discussed (comma-separated) |
| `sentimentScore` | NUMBER | Sentiment Score | Overall meeting sentiment (0-1 scale, 1 = most positive) |
| `positivePercent` | NUMBER | Positive % | Percentage of positive sentiment in conversation |
| `negativePercent` | NUMBER | Negative % | Percentage of negative sentiment in conversation |
| `actionItemsCount` | NUMBER | Action Items | Number of action items identified |
| `transcriptUrl` | LINKS | Transcript URL | Link to full transcript in Fireflies |
| `recordingUrl` | LINKS | Recording URL | Link to video/audio recording in Fireflies |
| `firefliesMeetingId` | TEXT | Fireflies Meeting ID | Unique identifier from Fireflies |
| `organizerEmail` | TEXT | Organizer Email | Email address of the meeting organizer |
Then re-sync:
```bash
npx twenty-cli app sync
```
**Note:** Without custom fields, meetings will be created with just the title. The rich summary data will only be stored in Notes for 1-on-1 meetings.
## Configuration
### Required Environment Variables
Check [.env.example](./.env.example)
### Summary Processing Strategies
| Strategy | Description | Use Case |
|----------|-------------|----------|
| `immediate_only` | Single fetch attempt, no retries | Fast processing, accept missing summaries if not ready |
| `immediate_with_retry` | Attempts immediate fetch, retries with backoff | **Recommended** - Balances speed and reliability |
| `delayed_polling` | Schedules background polling | For heavily loaded systems |
| `basic_only` | Creates records without waiting for summaries | For basic transcript archival only |
## Webhook Setup
### Step 1: Get Your Webhook URL
Your webhook endpoint will be:
```
https://your-twenty-instance.com/s/webhook/fireflies
```
### Step 2: Configure Fireflies Webhook
1. Log into Fireflies.ai
2. https://app.fireflies.ai/settings#DeveloperSettings
4. Enter your webhook URL
5. Set **Secret**: Generate from there and set value of `FIREFLIES_WEBHOOK_SECRET`
6. Save configuration
### Step 3: Verify Webhook
The integration uses **HMAC SHA-256 signature verification**:
- Fireflies sends `x-hub-signature` header
- Twenty verifies signature using your webhook secret
- Invalid signatures are rejected immediately
## Development
```bash
# Run tests
npm test
# Run tests in watch mode
npm run test -- --watch
# Development mode with live sync
npx twenty-cli app dev
# Type checking
npx tsc --noEmit
```
## Testing
The integration includes comprehensive test coverage:
```bash
# Run all tests
npm test
# Run specific test suite
npm test -- fireflies-webhook.spec.ts
# Run with coverage
npm test -- --coverage
```
### Test Coverage
- HMAC signature verification
- Fireflies GraphQL API integration
- Summary processing with retry logic
- Summary-focused CRM record creation
- One-on-one vs multi-party meeting detection
- Contact matching and creation
- Duplicate prevention
- Error handling and resilience
## CRM Record Structure
### One-on-One Meeting Note Example
```markdown
# Meeting: Product Demo with Client (Sales Call)
**Date:** Monday, November 2, 2024, 02:00 PM
**Duration:** 30 minutes
**Participants:** Sarah Sales, John Client
## Overview
Successful product demonstration with positive client feedback.
Client expressed strong interest in the enterprise plan.
## Key Topics
- product features
- pricing discussion
- integration capabilities
- support options
## Action Items
- Follow up with pricing proposal by Friday
- Schedule technical deep-dive next week
- Share case studies from similar clients
## Insights
**Keywords:** product demo, pricing, technical requirements, integration
**Sentiment:** 75% positive, 10% negative, 15% neutral
**Meeting Type:** Sales Call
## Resources
[View Full Transcript](https://app.fireflies.ai/transcript/xxx)
[Watch Recording](https://app.fireflies.ai/recording/xxx)
```
### Multi-Party Meeting Record
- Meeting object with title, date, and all attendees
- Summary stored as meeting notes (structure same as above)
- Action items potentially converted to separate tasks (future)
- Keywords as tags/categories (future)
## Future Implementation Opportunities
### Past Meetings Retrieval
- **New trigger to retrieve past meetings from a contact** - Enable users to fetch historical meeting data from Fireflies for specific contacts, allowing retrospective capture and analysis of past interactions.
Next iteration would enhance the **intelligence layer** to:
### AI-Powered Insights
- **Extract pain points, objections & buying signals** automatically from transcripts
- **Calculate deal health scores** based on conversation sentiment trends
- **Auto-create contextualized tasks** with AI-suggested next steps and priorities
- **Proactively flag at-risk deals** when negative signals appear
- **Track conversation patterns** that correlate with deal success
### Enhanced Analytics
- **Action item completion tracking** across deals
- **Sentiment trend analysis** over time for account health
- **Speaking time analysis** for meeting engagement insights
- **Topic clustering** for product/feature interest patterns
### Workflow Automation
- **Auto-assign follow-up tasks** based on action items
- **Smart notifications** for urgent follow-ups
- **Deal stage progression** based on meeting outcomes
- **Competitive intelligence** extraction from conversations
**Integration**: Fireflies webhook → AI processing layer → Enhanced Twenty records
*This would require the current MVP to be stabilized and discussions about intelligence layer architecture and data privacy considerations.*
@@ -1,68 +0,0 @@
import { type ApplicationConfig } from 'twenty-sdk/application';
const config: ApplicationConfig = {
universalIdentifier: 'a4df0c0f-c65e-44e5-8436-24814182d4ac',
displayName: 'Fireflies',
description: 'Sync Fireflies meeting summaries, sentiment, and action items into Twenty.',
icon: 'IconMicrophone',
applicationVariables: {
FIREFLIES_WEBHOOK_SECRET: {
universalIdentifier: 'f51f7646-be9f-4ba9-9b75-160dd288cd0c',
description: 'Secret key for verifying Fireflies webhook signatures',
isSecret: true,
},
FIREFLIES_API_KEY: {
universalIdentifier: 'faa41f07-b28e-4500-b1c0-ce4b3d27924c',
description: 'Fireflies GraphQL API key used to fetch meeting summaries',
isSecret: true,
},
TWENTY_API_KEY: {
universalIdentifier: '02756551-5bf7-4fb2-8e08-1f622008d305',
description: 'Twenty API key used when running scripts locally',
isSecret: true,
},
SERVER_URL: {
universalIdentifier: '9b3a5e8e-5973-4e6b-a059-2966075652aa',
description: 'Base URL for the Twenty workspace (default: http://localhost:3000)',
value: 'http://localhost:3000',
},
AUTO_CREATE_CONTACTS: {
universalIdentifier: 'c4fa946e-e06b-4d54-afb6-288b0ac75bdf',
description: 'Whether to auto-create contacts for unknown participants',
value: 'true',
},
LOG_LEVEL: {
universalIdentifier: '2b019cf1-d198-48dd-943e-110571aa541e',
description: 'Log level: silent, error, warn, info, debug (default: error)',
value: 'error',
},
FIREFLIES_SUMMARY_STRATEGY: {
universalIdentifier: '562b43d9-cd47-4ec1-ae16-5cc7ebc9729b',
description: 'Summary fetch strategy: immediate_only, immediate_with_retry, delayed_polling, or basic_only',
value: 'immediate_with_retry',
},
FIREFLIES_RETRY_ATTEMPTS: {
universalIdentifier: '670ca203-01ce-4ae8-8294-eb38b29434f2',
description: 'Number of retry attempts when fetching summaries',
value: '3',
},
FIREFLIES_RETRY_DELAY: {
universalIdentifier: '2e8ccb82-9390-47ba-b628-ca2726931bce',
description: 'Delay in milliseconds between retry attempts',
value: '5000',
},
FIREFLIES_POLL_INTERVAL: {
universalIdentifier: '904538f7-7bec-4ee6-9bac-5d43c619b667',
description: 'Polling interval (ms) when using delayed polling strategy',
value: '30000',
},
FIREFLIES_MAX_POLLS: {
universalIdentifier: '84d54c97-5572-4c01-9039-764ab3aa87b8',
description: 'Maximum number of polling attempts when waiting for summaries',
value: '10',
},
},
};
export default config;
@@ -1,23 +0,0 @@
const jestConfig = {
displayName: 'fireflies',
preset: 'ts-jest',
testEnvironment: 'node',
moduleFileExtensions: ['ts', 'js'],
transform: {
'^.+\\.ts$': 'ts-jest',
},
testMatch: [
'<rootDir>/src/**/__tests__/**/*.(test|spec).{js,ts}',
'<rootDir>/src/**/?(*.)(test|spec).{js,ts}',
],
setupFilesAfterEnv: [
'<rootDir>/src/__tests__/setup.ts'
],
collectCoverageFrom: [
'src/**/*.{ts,js}',
'!src/**/*.d.ts',
],
coverageDirectory: './coverage',
};
export default jestConfig;
@@ -1,29 +0,0 @@
{
"name": "fireflies",
"version": "0.2.2",
"license": "MIT",
"engines": {
"node": "^24.5.0",
"npm": "please-use-yarn",
"yarn": ">=4.0.2"
},
"packageManager": "yarn@4.9.2",
"scripts": {
"test": "jest",
"setup:fields": "tsx scripts/add-meeting-fields.ts",
"test:webhook": "tsx scripts/test-webhook.ts"
},
"dependencies": {
"axios": "^1.13.1",
"dotenv": "^16.3.1",
"twenty-sdk": "0.0.3"
},
"devDependencies": {
"@types/jest": "^29.5.5",
"@types/node": "^24.9.2",
"jest": "^29.7.0",
"ts-jest": "^29.1.1",
"tsx": "^4.19.3",
"typescript": "^5.9.3"
}
}
@@ -1,49 +0,0 @@
{
"name": "fireflies",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "packages/twenty-apps/fireflies/src",
"projectType": "application",
"tags": [
"scope:apps"
],
"targets": {
"test": {
"executor": "@nx/jest:jest",
"outputs": [
"{workspaceRoot}/coverage/{projectRoot}"
],
"options": {
"jestConfig": "packages/twenty-apps/fireflies/jest.config.mjs",
"passWithNoTests": true
},
"configurations": {
"ci": {
"ci": true,
"coverageReporters": ["text"]
}
}
},
"typecheck": {
"executor": "nx:run-commands",
"options": {
"command": "tsc --noEmit --project {projectRoot}/tsconfig.json"
}
},
"lint": {
"executor": "@nx/eslint:lint",
"outputs": [
"{options.outputFile}"
],
"options": {
"lintFilePatterns": [
"packages/twenty-apps/fireflies/**/*.{ts,tsx,js,jsx}"
]
},
"configurations": {
"fix": {
"fix": true
}
}
}
}
}
@@ -1,437 +0,0 @@
/**
* Migration script to add custom fields to the Meeting object
* Run this after: npx twenty-cli app sync packages/twenty-apps/fireflies
*
* Usage: yarn setup:fields
*/
/* eslint-disable no-console */
import * as dotenv from 'dotenv';
import * as path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Load environment variables
dotenv.config({ path: path.join(__dirname, '../.env') });
const SERVER_URL = process.env.SERVER_URL || 'http://localhost:3000';
const API_KEY = process.env.TWENTY_API_KEY;
if (!API_KEY) {
console.error('❌ Error: TWENTY_API_KEY not found in .env file');
process.exit(1);
}
interface RelationCreationPayload {
targetObjectMetadataId: string;
targetFieldLabel: string;
targetFieldIcon: string;
type: 'ONE_TO_MANY' | 'MANY_TO_ONE';
}
interface FieldOption {
value: string;
label: string;
position: number;
color: string;
}
interface FieldDefinition {
type: string;
name: string;
label: string;
description: string;
icon?: string;
isNullable?: boolean;
relationCreationPayload?: RelationCreationPayload;
options?: FieldOption[];
}
const MEETING_FIELDS: FieldDefinition[] = [
{
type: 'RELATION',
name: 'note',
label: 'Meeting Note',
description: 'Related note with detailed meeting content',
icon: 'IconNotes',
isNullable: true,
},
{
type: 'DATE_TIME',
name: 'meetingDate',
label: 'Meeting Date',
description: 'Date and time when the meeting occurred',
icon: 'IconCalendar',
isNullable: true,
},
{
type: 'NUMBER',
name: 'duration',
label: 'Duration (minutes)',
description: 'Meeting duration in minutes',
icon: 'IconClock',
isNullable: true,
},
{
type: 'TEXT',
name: 'meetingType',
label: 'Meeting Type',
description: 'Type of meeting (e.g., Sales Call, Sprint Planning, 1:1)',
icon: 'IconTag',
isNullable: true,
},
{
type: 'TEXT',
name: 'keywords',
label: 'Keywords',
description: 'Key topics and themes discussed (comma-separated)',
icon: 'IconTags',
isNullable: true,
},
{
type: 'NUMBER',
name: 'sentimentScore',
label: 'Sentiment Score',
description: 'Overall meeting sentiment (0-1 scale, where 1 is most positive)',
icon: 'IconMoodSmile',
isNullable: true,
},
{
type: 'NUMBER',
name: 'positivePercent',
label: 'Positive %',
description: 'Percentage of positive sentiment in conversation',
icon: 'IconThumbUp',
isNullable: true,
},
{
type: 'NUMBER',
name: 'negativePercent',
label: 'Negative %',
description: 'Percentage of negative sentiment in conversation',
icon: 'IconThumbDown',
isNullable: true,
},
{
type: 'NUMBER',
name: 'actionItemsCount',
label: 'Action Items',
description: 'Number of action items identified',
icon: 'IconCheckbox',
isNullable: true,
},
{
type: 'LINKS',
name: 'transcriptUrl',
label: 'Transcript URL',
description: 'Link to full transcript in Fireflies',
icon: 'IconFileText',
isNullable: true,
},
{
type: 'LINKS',
name: 'recordingUrl',
label: 'Recording URL',
description: 'Link to video/audio recording in Fireflies',
icon: 'IconVideo',
isNullable: true,
},
{
type: 'TEXT',
name: 'firefliesMeetingId',
label: 'Fireflies Meeting ID',
description: 'Unique identifier from Fireflies',
icon: 'IconKey',
isNullable: true,
},
{
type: 'TEXT',
name: 'organizerEmail',
label: 'Organizer Email',
description: 'Email address of the meeting organizer',
icon: 'IconMail',
isNullable: true,
},
{
type: 'SELECT',
name: 'importStatus',
label: 'Import Status',
description: 'Status of the meeting import from Fireflies',
icon: 'IconCheck',
isNullable: true,
options: [
{ value: 'SUCCESS', label: 'Success', position: 0, color: 'green' },
{ value: 'FAILED', label: 'Failed', position: 1, color: 'red' },
{ value: 'PENDING', label: 'Pending', position: 2, color: 'yellow' },
{ value: 'RETRYING', label: 'Retrying', position: 3, color: 'orange' },
],
},
{
type: 'TEXT',
name: 'importError',
label: 'Import Error',
description: 'Error message if meeting import failed',
icon: 'IconAlertTriangle',
isNullable: true,
},
{
type: 'DATE_TIME',
name: 'lastImportAttempt',
label: 'Last Import Attempt',
description: 'Date and time of the last import attempt',
icon: 'IconClock',
isNullable: true,
},
{
type: 'NUMBER',
name: 'importAttempts',
label: 'Import Attempts',
description: 'Number of times import has been attempted',
icon: 'IconRepeat',
isNullable: true,
},
];
const graphqlRequest = async (query: string, variables: Record<string, unknown> = {}) => {
const response = await fetch(`${SERVER_URL}/metadata`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`,
},
body: JSON.stringify({ query, variables }),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`GraphQL request failed (${response.status}): ${errorText}`);
}
const json = await response.json();
if (json.errors) {
throw new Error(`GraphQL errors: ${JSON.stringify(json.errors, null, 2)}`);
}
return json.data;
};
const findMeetingObject = async () => {
const query = `
query FindMeetingObject {
objects(paging: { first: 200 }) {
edges {
node {
id
nameSingular
labelSingular
labelPlural
fields {
edges {
node {
id
name
label
type
}
}
}
}
}
}
}
`;
const data = await graphqlRequest(query);
const edges = data.objects?.edges || [];
const meetingEdge = edges.find(
(edge: any) => edge?.node?.nameSingular === 'meeting',
);
if (!meetingEdge) {
throw new Error('Meeting object not found. Please run "npx twenty-cli app sync" first.');
}
return meetingEdge.node;
};
const findNoteObject = async () => {
const query = `
query FindObjects {
objects(paging: { first: 100 }) {
edges {
node {
id
nameSingular
labelSingular
}
}
}
}
`;
const data = await graphqlRequest(query);
const edges = data.objects?.edges || [];
const noteEdge = edges.find(
(edge: any) => edge?.node?.nameSingular === 'note',
);
if (!noteEdge) {
throw new Error('Note object not found.');
}
return noteEdge.node;
};
const createField = async (objectId: string, field: FieldDefinition) => {
const mutation = `
mutation CreateField($input: CreateOneFieldMetadataInput!) {
createOneField(input: $input) {
id
name
label
type
description
}
}
`;
const input = {
field: {
type: field.type,
name: field.name,
label: field.label,
description: field.description,
icon: field.icon || 'IconAbc',
isNullable: field.isNullable !== false,
isActive: true,
isCustom: true,
objectMetadataId: objectId,
...(field.relationCreationPayload && {
relationCreationPayload: field.relationCreationPayload,
}),
...(field.options && {
options: field.options,
}),
},
};
try {
const data = await graphqlRequest(mutation, { input });
return data.createOneField;
} catch (error) {
if (error instanceof Error) {
const message = error.message;
if (
message.includes('already exists') ||
message.includes('not available') ||
message.includes('Duplicating')
) {
return null;
}
}
throw error;
}
};
const main = async () => {
console.log('🚀 Adding custom fields to Meeting object...\n');
try {
// Step 1: Find Meeting and Note objects
console.log('📋 Finding Meeting object...');
const meetingObject = await findMeetingObject();
console.log(`✅ Found Meeting object: ${meetingObject.labelSingular ?? meetingObject.nameSingular ?? 'Meeting'} (ID: ${meetingObject.id})\n`);
console.log('📋 Finding Note object...');
const noteObject = await findNoteObject();
console.log(`✅ Found Note object: ${noteObject.labelSingular ?? noteObject.nameSingular ?? 'Note'} (ID: ${noteObject.id})\n`);
// Step 2: Update note field with relationCreationPayload
const fieldsToCreate = MEETING_FIELDS.map(field => {
if (field.name === 'note' && field.type === 'RELATION') {
return {
...field,
relationCreationPayload: {
targetObjectMetadataId: noteObject.id,
targetFieldLabel: 'Meeting',
targetFieldIcon: 'IconCalendarEvent',
type: 'MANY_TO_ONE' as const,
},
};
}
return field;
});
// Step 3: Check existing fields
const existingFields = meetingObject.fields?.edges?.map((edge: any) => edge.node.name) || [];
console.log(`📌 Existing fields: ${existingFields.join(', ')}\n`);
// Step 4: Create custom fields
console.log(' Creating custom fields...\n');
let createdCount = 0;
let failedCount = 0;
let skippedCount = 0;
for (const field of fieldsToCreate) {
try {
if (existingFields.includes(field.name)) {
console.log(` ⏭️ ${field.name} - already exists`);
skippedCount++;
continue;
}
const result = await createField(meetingObject.id, field);
if (result) {
console.log(`${field.name} - created successfully`);
createdCount++;
} else {
console.log(` ⏭️ ${field.name} - skipped (already exists)`);
skippedCount++;
}
} catch (error) {
console.error(`${field.name} - failed: ${error instanceof Error ? error.message : String(error)}`);
failedCount++;
}
}
// Step 4: Summary
console.log('\n' + '='.repeat(60));
console.log('📊 Summary:');
console.log(` ✅ Created: ${createdCount} fields`);
console.log(` ⏭️ Skipped: ${skippedCount} fields`);
console.log(` ❌ Failed: ${failedCount} fields`);
console.log('='.repeat(60));
if (failedCount > 0) {
console.log('\n⚠️ Some fields failed to create. Please check the errors above.');
process.exit(1);
}
if (createdCount === 0 && skippedCount === MEETING_FIELDS.length) {
console.log('\n✨ All fields already exist. Nothing to do!');
} else if (createdCount > 0) {
console.log('\n✨ Custom fields added successfully!');
console.log('\n📝 Next steps:');
console.log(' 1. Re-sync your app: npx twenty-cli app sync');
console.log(' 2. Update the createMeetingRecord function to use these fields');
console.log(' 3. Test the integration with a real meeting');
}
} catch (error) {
console.error('\n❌ Error:', error instanceof Error ? error.message : String(error));
process.exit(1);
}
}
// Run the script
main().catch((error) => {
console.error('Fatal error:', error);
process.exit(1);
});
@@ -1,208 +0,0 @@
/* eslint-disable no-console */
/**
* Test script for Fireflies webhook against local Twenty instance
*
* Usage:
* yarn test:webhook
* # or
* npx tsx scripts/test-webhook.ts
*
* Prerequisites:
* 1. Twenty server running on http://localhost:3000
* 2. Fireflies app synced: npx twenty-cli app sync
* 3. Custom fields created: yarn setup:fields
* 4. API key configured (get from Settings > Developers > API Keys)
* 5. Environment variables set (copy .env.example to .env and fill values)
*/
import * as crypto from 'crypto';
import * as dotenv from 'dotenv';
import { existsSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
// Get __dirname equivalent for ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Load environment variables
const envPath = join(__dirname, '..', '.env');
if (existsSync(envPath)) {
dotenv.config({ path: envPath });
} else {
console.warn('⚠️ .env file not found, using environment variables');
}
// Configuration
const SERVER_URL = process.env.SERVER_URL || 'http://localhost:3000';
const TWENTY_API_KEY = process.env.TWENTY_API_KEY;
const FIREFLIES_WEBHOOK_SECRET = process.env.FIREFLIES_WEBHOOK_SECRET || 'test_secret';
const _FIREFLIES_API_KEY = process.env.FIREFLIES_API_KEY || 'test_api_key';
// Test meeting data (simulating Fireflies API response)
const TEST_MEETING_ID = 'test-meeting-local-' + Date.now();
const TEST_WEBHOOK_PAYLOAD = {
meetingId: TEST_MEETING_ID,
eventType: 'Transcription completed',
clientReferenceId: 'test-client-ref',
};
// Mock Fireflies GraphQL API response
const MOCK_FIREFLIES_RESPONSE = {
data: {
meeting: {
id: TEST_MEETING_ID,
title: 'Local Test Meeting',
date: new Date().toISOString(),
duration: 1800, // 30 minutes
participants: [
{ email: 'test1@example.com', name: 'Test User One' },
{ email: 'test2@example.com', name: 'Test User Two' },
],
organizer_email: 'organizer@example.com',
summary: {
action_items: ['Complete integration testing', 'Review webhook logs'],
keywords: ['testing', 'integration', 'webhook'],
overview: 'This is a test meeting to verify the Fireflies webhook integration.',
gist: 'Quick test summary',
topics_discussed: ['Webhook testing', 'Integration verification'],
meeting_type: 'Test',
},
analytics: {
sentiments: {
positive_pct: 75,
negative_pct: 5,
neutral_pct: 20,
},
},
transcript_url: 'https://app.fireflies.ai/transcript/' + TEST_MEETING_ID,
recording_url: 'https://app.fireflies.ai/recording/' + TEST_MEETING_ID,
summary_status: 'ready',
},
},
};
// Generate HMAC signature
const generateHMACSignature = (body: string, secret: string): string => {
const signature = crypto
.createHmac('sha256', secret)
.update(body, 'utf8')
.digest('hex');
return `sha256=${signature}`;
};
// Mock Fireflies API fetch (currently unused but kept for reference)
// In production, you'd need to mock this at the network level
const _mockFirefliesFetch = async (url: string, options?: RequestInit) => {
if (url.includes('graphql.fireflies.ai')) {
// Return mock Fireflies API response
return new Response(JSON.stringify(MOCK_FIREFLIES_RESPONSE), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}
// For Twenty API calls, use real fetch
return fetch(url, options);
};
const main = async () => {
console.log('🧪 Testing Fireflies Webhook Against Local Twenty Instance\n');
console.log(`📍 Server URL: ${SERVER_URL}`);
console.log(`🔑 API Key: ${TWENTY_API_KEY ? '✅ Configured' : '❌ Missing'}`);
console.log(`🔐 Webhook Secret: ${FIREFLIES_WEBHOOK_SECRET ? '✅ Configured' : '⚠️ Using test secret'}\n`);
// Validation
if (!TWENTY_API_KEY) {
console.error('❌ Error: TWENTY_API_KEY is required');
console.error(' Get your API key from: Settings > Developers > API Keys');
process.exit(1);
}
// Prepare webhook payload
const body = JSON.stringify(TEST_WEBHOOK_PAYLOAD);
const signature = generateHMACSignature(body, FIREFLIES_WEBHOOK_SECRET);
console.log('📤 Sending webhook payload:');
console.log(JSON.stringify(TEST_WEBHOOK_PAYLOAD, null, 2));
console.log(`\n🔐 HMAC Signature: ${signature}\n`);
// Check if server is reachable
try {
const healthCheck = await fetch(`${SERVER_URL}/api/health`);
if (!healthCheck.ok) {
throw new Error(`Server health check failed: ${healthCheck.status}`);
}
console.log('✅ Server is reachable\n');
} catch {
console.error(`❌ Cannot reach server at ${SERVER_URL}`);
console.error(' Make sure Twenty is running: cd twenty && yarn dev');
process.exit(1);
}
// Note: In a real test, we'd intercept fetch calls
// For now, we'll make a direct request to the webhook endpoint
// The actual serverless function will call Fireflies API
// This test validates the endpoint is accessible
// Webhook endpoint: The route path from manifest is /webhook/fireflies
// Routes are matched after removing /s/ prefix
// So /s/webhook/fireflies should match the route /webhook/fireflies
const webhookUrl = `${SERVER_URL}/s/webhook/fireflies`;
console.log(`📡 Calling webhook endpoint: ${webhookUrl}\n`);
try {
// Note: This will fail because the serverless function needs to call
// Fireflies API, which we can't easily mock at the endpoint level.
// In development, you might want to set FIREFLIES_API_KEY to a test value
// and mock the Fireflies API endpoint separately.
const response = await fetch(webhookUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${TWENTY_API_KEY}`,
'x-hub-signature': signature,
},
body: body,
});
const responseText = await response.text();
let responseData;
try {
responseData = JSON.parse(responseText);
} catch {
responseData = responseText;
}
console.log(`📥 Response Status: ${response.status} ${response.statusText}`);
console.log('📥 Response Body:');
console.log(JSON.stringify(responseData, null, 2));
if (response.ok) {
console.log('\n✅ Webhook test completed successfully!');
console.log('\n📋 Next steps:');
console.log(' 1. Check Twenty CRM for new Meeting/Note records');
console.log(' 2. Verify custom fields are populated');
console.log(' 3. Check server logs for any errors');
} else {
console.log('\n⚠️ Webhook returned an error status');
console.log(' This might be expected if Fireflies API key is not configured');
console.log(' or if the meeting data fetch fails.');
}
} catch (error) {
console.error('\n❌ Error calling webhook:');
console.error(error instanceof Error ? error.message : String(error));
console.error('\n💡 Troubleshooting:');
console.error(' 1. Ensure Twenty server is running');
console.error(' 2. Ensure app is synced: npx twenty-cli app sync');
console.error(' 3. Check API key is valid');
console.error(' 4. Verify webhook endpoint exists');
process.exit(1);
}
};
main().catch((error) => {
console.error('Fatal error:', error);
process.exit(1);
});
@@ -1,426 +0,0 @@
import { createLogger } from './logger';
import type { FirefliesMeetingData, FirefliesParticipant, SummaryFetchConfig } from './types';
const logger = createLogger('fireflies-api');
export class FirefliesApiClient {
private apiKey: string;
constructor(apiKey: string) {
if (!apiKey) {
logger.critical('FIREFLIES_API_KEY is required but not provided - this is a critical configuration error');
throw new Error('FIREFLIES_API_KEY is required');
}
this.apiKey = apiKey;
}
async fetchMeetingData(
meetingId: string,
options?: { timeout?: number }
): Promise<FirefliesMeetingData> {
const query = `
query GetTranscript($transcriptId: String!) {
transcript(id: $transcriptId) {
id
title
date
duration
participants
organizer_email
meeting_attendees {
displayName
email
phoneNumber
name
location
}
meeting_attendance {
name
join_time
leave_time
}
speakers {
name
}
summary {
action_items
overview
}
transcript_url
}
}
`;
const controller = new AbortController();
const timeoutId = options?.timeout
? setTimeout(() => controller.abort(), options.timeout)
: null;
try {
const response = await fetch('https://api.fireflies.ai/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`,
},
body: JSON.stringify({
query,
variables: { transcriptId: meetingId },
}),
signal: controller.signal,
});
if (timeoutId) clearTimeout(timeoutId);
if (!response.ok) {
let errorDetails = `Fireflies API request failed with status ${response.status}`;
try {
const errorBody = await response.text();
if (errorBody) {
errorDetails += `: ${errorBody}`;
}
} catch {
// Ignore if we can't read the response body
}
throw new Error(errorDetails);
}
const json = await response.json() as {
data?: { transcript?: any };
errors?: Array<{ message?: string }>;
};
if (json.errors && json.errors.length > 0) {
throw new Error(`Fireflies API error: ${json.errors[0]?.message || 'Unknown error'}`);
}
const transcript = json.data?.transcript;
if (!transcript) {
throw new Error('Invalid response from Fireflies API: missing transcript data');
}
return this.transformMeetingData(transcript, meetingId);
} catch (error) {
if (timeoutId) clearTimeout(timeoutId);
throw error;
}
}
async fetchMeetingDataWithRetry(
meetingId: string,
config: SummaryFetchConfig
): Promise<{ data: FirefliesMeetingData; summaryReady: boolean }> {
// immediate_only: single attempt, no retries
if (config.strategy === 'immediate_only') {
logger.debug(`fetching meeting ${meetingId} (strategy: immediate_only)`);
const meetingData = await this.fetchMeetingData(meetingId, { timeout: 10000 });
const ready = this.isSummaryReady(meetingData);
logger.debug(`summary ready: ${ready}`);
return { data: meetingData, summaryReady: ready };
}
// immediate_with_retry: retry with exponential backoff
logger.debug(`fetching meeting ${meetingId} (strategy: immediate_with_retry, maxAttempts: ${config.retryAttempts})`);
for (let attempt = 1; attempt <= config.retryAttempts; attempt++) {
try {
const meetingData = await this.fetchMeetingData(meetingId, { timeout: 10000 });
const ready = this.isSummaryReady(meetingData);
logger.debug(`attempt ${attempt}/${config.retryAttempts}: summary ready=${ready}`);
if (ready) {
return { data: meetingData, summaryReady: true };
}
if (attempt < config.retryAttempts) {
const delayMs = config.retryDelay * attempt;
logger.debug(`summary not ready, waiting ${delayMs}ms before retry ${attempt + 1}`);
await new Promise(resolve => setTimeout(resolve, delayMs));
} else {
logger.debug(`max retries reached, returning partial data`);
return { data: meetingData, summaryReady: false };
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
logger.error(`attempt ${attempt}/${config.retryAttempts} failed: ${errorMsg}`);
if (attempt === config.retryAttempts) {
throw error;
}
const delayMs = config.retryDelay * attempt;
logger.debug(`retrying in ${delayMs}ms...`);
await new Promise(resolve => setTimeout(resolve, delayMs));
}
}
throw new Error('Failed to fetch meeting data after retries');
}
private isSummaryReady(meetingData: FirefliesMeetingData): boolean {
return (
(meetingData.summary?.action_items?.length > 0) ||
(meetingData.summary?.overview?.length > 0) ||
meetingData.summary_status === 'completed'
);
}
private extractAllParticipants(transcript: any): FirefliesParticipant[] {
const participantsWithEmails: FirefliesParticipant[] = [];
const participantsNameOnly: FirefliesParticipant[] = [];
logger.debug('=== PARTICIPANT EXTRACTION DEBUG ===');
logger.debug('participants field:', JSON.stringify(transcript.participants));
logger.debug('meeting_attendees field:', JSON.stringify(transcript.meeting_attendees));
logger.debug('speakers field:', transcript.speakers?.map((s: any) => s.name));
logger.debug('meeting_attendance field:', transcript.meeting_attendance?.map((a: any) => a.name));
logger.debug('organizer_email:', transcript.organizer_email);
// Helper function to check if a string is an email
const isEmail = (str: string): boolean => {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str.trim());
};
// Helper function to check if already exists
const isDuplicate = (name: string, email: string): boolean => {
const nameLower = name.toLowerCase().trim();
const emailLower = email.toLowerCase().trim();
return participantsWithEmails.some(p =>
p.name.toLowerCase().trim() === nameLower ||
(email && p.email.toLowerCase() === emailLower)
) || participantsNameOnly.some(p =>
p.name.toLowerCase().trim() === nameLower
);
};
// 1. Extract from legacy participants field (with emails)
if (transcript.participants && Array.isArray(transcript.participants)) {
transcript.participants.forEach((participant: string) => {
// Handle comma-separated emails or names
const parts = participant.split(',').map(p => p.trim());
parts.forEach(part => {
const emailMatch = part.match(/<([^>]+)>/);
const email = emailMatch ? emailMatch[1] : '';
// Extract name properly: if there's an email in angle brackets, get the part before it
const name = emailMatch
? part.substring(0, part.indexOf('<')).trim()
: part.trim();
// Skip if the "name" is actually an email address
if (isEmail(name)) {
logger.debug(`Skipping participant with email as name: "${name}"`);
return;
}
// Skip if empty name
if (!name) {
return;
}
// Skip duplicates
if (isDuplicate(name, email)) {
logger.debug(`Skipping duplicate participant: "${name}" <${email}>`);
return;
}
if (name && email) {
participantsWithEmails.push({ name, email });
} else if (name) {
participantsNameOnly.push({ name, email: '' });
}
});
});
}
// 2. Extract from meeting_attendees field (structured)
if (transcript.meeting_attendees && Array.isArray(transcript.meeting_attendees)) {
transcript.meeting_attendees.forEach((attendee: any) => {
const name = attendee.displayName || attendee.name || '';
const email = attendee.email || '';
// Skip if name is actually an email
if (isEmail(name)) {
logger.debug(`Skipping attendee with email as name: "${name}"`);
return;
}
if (name && !isDuplicate(name, email)) {
if (email) {
participantsWithEmails.push({ name, email });
} else {
participantsNameOnly.push({ name, email: '' });
}
}
});
}
// 3. Extract from speakers field (name only)
if (transcript.speakers && Array.isArray(transcript.speakers)) {
transcript.speakers.forEach((speaker: any) => {
const name = speaker.name || '';
// Skip if name is actually an email
if (isEmail(name)) {
logger.debug(`Skipping speaker with email as name: "${name}"`);
return;
}
if (name && !isDuplicate(name, '')) {
participantsNameOnly.push({ name, email: '' });
}
});
}
// 4. Extract from meeting_attendance field (name only)
if (transcript.meeting_attendance && Array.isArray(transcript.meeting_attendance)) {
transcript.meeting_attendance.forEach((attendance: any) => {
const name = attendance.name || '';
// Skip if name is actually an email or contains comma-separated emails
if (isEmail(name) || name.includes(',')) {
logger.debug(`Skipping attendance with email/list as name: "${name}"`);
return;
}
if (name && !isDuplicate(name, '')) {
participantsNameOnly.push({ name, email: '' });
}
});
}
// 5. Add organizer email if available and not already included
const organizerEmail = transcript.organizer_email;
if (organizerEmail) {
// Check if organizer email is already in the participants
const existsWithEmail = participantsWithEmails.some(p =>
p.email.toLowerCase() === organizerEmail.toLowerCase()
);
if (!existsWithEmail) {
// Try to find organizer name from speakers/attendance and match with email
let organizerName = '';
// Extract username from organizer email for matching
const emailUsername = organizerEmail.split('@')[0].toLowerCase();
const emailNameVariations = [emailUsername];
// Add common name variations based on email username
if (emailUsername === 'alex') {
emailNameVariations.push('alexander', 'alexandre', 'alex');
}
// Look for organizer in speakers by matching email username to speaker names
if (transcript.speakers && Array.isArray(transcript.speakers)) {
const potentialOrganizerSpeaker = transcript.speakers.find((speaker: any) => {
const name = (speaker.name || '').toLowerCase();
return emailNameVariations.some(variation =>
name.includes(variation) || variation.includes(name)
);
});
if (potentialOrganizerSpeaker) {
organizerName = potentialOrganizerSpeaker.name;
}
}
// Look for organizer in attendance
if (!organizerName && transcript.meeting_attendance && Array.isArray(transcript.meeting_attendance)) {
const potentialOrganizerAttendance = transcript.meeting_attendance.find((attendance: any) => {
const name = (attendance.name || '').toLowerCase();
return emailNameVariations.some(variation =>
name.includes(variation) || variation.includes(name)
);
});
if (potentialOrganizerAttendance) {
organizerName = potentialOrganizerAttendance.name;
}
}
// If we found a name match, add as participant with email
if (organizerName) {
participantsWithEmails.push({ name: organizerName, email: organizerEmail });
// Remove from name-only participants to avoid duplicates
const nameIndex = participantsNameOnly.findIndex(p =>
p.name.toLowerCase().includes(organizerName.toLowerCase()) ||
organizerName.toLowerCase().includes(p.name.toLowerCase())
);
if (nameIndex !== -1) {
participantsNameOnly.splice(nameIndex, 1);
}
} else {
// If no name found, add with generic organizer name
participantsWithEmails.push({ name: 'Meeting Organizer', email: organizerEmail });
}
}
}
// Return participants with emails first, then name-only participants
const allParticipants = [...participantsWithEmails, ...participantsNameOnly];
logger.debug('=== EXTRACTED PARTICIPANTS ===');
logger.debug('With emails:', participantsWithEmails.length, JSON.stringify(participantsWithEmails));
logger.debug('Name only:', participantsNameOnly.length, JSON.stringify(participantsNameOnly));
logger.debug('Total:', allParticipants.length);
return allParticipants;
}
private transformMeetingData(transcript: any, meetingId: string): FirefliesMeetingData {
// Convert date to ISO string - handle both timestamp and ISO string formats
let dateString: string;
if (transcript.date) {
if (typeof transcript.date === 'number') {
// Unix timestamp in milliseconds
dateString = new Date(transcript.date).toISOString();
} else if (typeof transcript.date === 'string') {
// Could be ISO string or timestamp string
const parsed = Number(transcript.date);
if (!isNaN(parsed)) {
// It's a numeric string (timestamp)
dateString = new Date(parsed).toISOString();
} else {
// It's already an ISO string
dateString = transcript.date;
}
} else {
dateString = new Date().toISOString();
}
} else {
dateString = new Date().toISOString();
}
return {
id: transcript.id || meetingId,
title: transcript.title || 'Untitled Meeting',
date: dateString,
duration: transcript.duration || 0,
participants: this.extractAllParticipants(transcript),
organizer_email: transcript.organizer_email,
summary: {
action_items: Array.isArray(transcript.summary?.action_items)
? transcript.summary.action_items
: (typeof transcript.summary?.action_items === 'string'
? [transcript.summary.action_items]
: []),
overview: transcript.summary?.overview || '',
keywords: transcript.summary?.keywords,
topics_discussed: transcript.summary?.topics_discussed,
meeting_type: transcript.summary?.meeting_type,
},
analytics: transcript.sentiments ? {
sentiments: {
positive_pct: transcript.sentiments.positive_pct || 0,
negative_pct: transcript.sentiments.negative_pct || 0,
neutral_pct: transcript.sentiments.neutral_pct || 0,
}
} : undefined,
transcript_url: transcript.transcript_url || `https://app.fireflies.ai/view/${meetingId}`,
recording_url: transcript.video_url || undefined,
summary_status: transcript.summary_status,
};
}
}
@@ -1,227 +0,0 @@
import type { FirefliesMeetingData, MeetingCreateInput } from './types';
export class MeetingFormatter {
static formatNoteBody(meetingData: FirefliesMeetingData): string {
const meetingDate = new Date(meetingData.date);
const formattedDate = meetingDate.toLocaleString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
const durationMinutes = Math.round(meetingData.duration);
let noteBody = `**Date:** ${formattedDate}\n`;
noteBody += `**Duration:** ${durationMinutes} minutes\n`;
if (meetingData.participants.length > 0) {
const participantNames = meetingData.participants.map(p => p.name).join(', ');
noteBody += `**Participants:** ${participantNames}\n`;
}
// Overview section
if (meetingData.summary?.overview) {
noteBody += `\n## Overview\n${meetingData.summary.overview}\n`;
}
// Key topics
if (meetingData.summary?.topics_discussed && Array.isArray(meetingData.summary.topics_discussed) && meetingData.summary.topics_discussed.length > 0) {
noteBody += `\n## Key Topics\n`;
meetingData.summary.topics_discussed.forEach(topic => {
noteBody += `- ${topic}\n`;
});
}
// Action items
if (meetingData.summary?.action_items && Array.isArray(meetingData.summary.action_items) && meetingData.summary.action_items.length > 0) {
noteBody += `\n## Action Items\n`;
meetingData.summary.action_items.forEach(item => {
noteBody += `- ${item}\n`;
});
}
// Insights section
noteBody += `\n## Insights\n`;
if (meetingData.summary?.keywords && Array.isArray(meetingData.summary.keywords) && meetingData.summary.keywords.length > 0) {
noteBody += `**Keywords:** ${meetingData.summary.keywords.join(', ')}\n`;
}
if (meetingData.analytics?.sentiments) {
const sentiments = meetingData.analytics.sentiments;
noteBody += `**Sentiment:** ${sentiments.positive_pct}% positive, ${sentiments.negative_pct}% negative, ${sentiments.neutral_pct}% neutral\n`;
}
if (meetingData.summary?.meeting_type) {
noteBody += `**Meeting Type:** ${meetingData.summary.meeting_type}\n`;
}
// Resources section
noteBody += `\n## Resources\n`;
noteBody += `[View Full Transcript](${meetingData.transcript_url})\n`;
if (meetingData.recording_url) {
noteBody += `[Watch Recording](${meetingData.recording_url})\n`;
}
return noteBody;
}
static formatMeetingNotes(meetingData: FirefliesMeetingData): string {
const meetingDate = new Date(meetingData.date);
const formattedDate = meetingDate.toLocaleString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
const durationMinutes = Math.round(meetingData.duration);
let meetingNotes = `**Date:** ${formattedDate}\n`;
meetingNotes += `**Duration:** ${durationMinutes} minutes\n`;
if (meetingData.participants.length > 0) {
const participantNames = meetingData.participants.map(p => p.name).join(', ');
meetingNotes += `**Participants:** ${participantNames}\n`;
}
// Overview section
if (meetingData.summary?.overview) {
meetingNotes += `\n## Overview\n${meetingData.summary.overview}\n`;
}
// Key topics
if (meetingData.summary?.topics_discussed && Array.isArray(meetingData.summary.topics_discussed) && meetingData.summary.topics_discussed.length > 0) {
meetingNotes += `\n## Key Topics\n`;
meetingData.summary.topics_discussed.forEach(topic => {
meetingNotes += `- ${topic}\n`;
});
}
// Action items
if (meetingData.summary?.action_items && Array.isArray(meetingData.summary.action_items) && meetingData.summary.action_items.length > 0) {
meetingNotes += `\n## Action Items\n`;
meetingData.summary.action_items.forEach(item => {
meetingNotes += `- ${item}\n`;
});
}
// Insights section
meetingNotes += `\n## Insights\n`;
if (meetingData.summary?.keywords && Array.isArray(meetingData.summary.keywords) && meetingData.summary.keywords.length > 0) {
meetingNotes += `**Keywords:** ${meetingData.summary.keywords.join(', ')}\n`;
}
if (meetingData.analytics?.sentiments) {
const sentiments = meetingData.analytics.sentiments;
meetingNotes += `**Sentiment:** ${sentiments.positive_pct}% positive, ${sentiments.negative_pct}% negative, ${sentiments.neutral_pct}% neutral\n`;
}
if (meetingData.summary?.meeting_type) {
meetingNotes += `**Meeting Type:** ${meetingData.summary.meeting_type}\n`;
}
// Resources section
meetingNotes += `\n## Resources\n`;
meetingNotes += `[View Full Transcript](${meetingData.transcript_url})\n`;
if (meetingData.recording_url) {
meetingNotes += `[Watch Recording](${meetingData.recording_url})\n`;
}
return meetingNotes;
}
static toMeetingCreateInput(
meetingData: FirefliesMeetingData,
noteId?: string
): MeetingCreateInput {
const durationMinutes = Math.round(meetingData.duration);
// Build input object with only defined values (omit null fields)
const input: MeetingCreateInput = {
name: meetingData.title,
meetingDate: meetingData.date,
duration: durationMinutes,
actionItemsCount: meetingData.summary?.action_items?.length || 0,
firefliesMeetingId: meetingData.id,
};
// Add direct relationship to note if noteId is provided
if (noteId) {
input.noteId = noteId;
}
// Only add optional fields if they have values
if (meetingData.summary?.meeting_type) {
input.meetingType = meetingData.summary.meeting_type;
}
if (meetingData.summary?.keywords && Array.isArray(meetingData.summary.keywords) && meetingData.summary.keywords.length > 0) {
input.keywords = meetingData.summary.keywords.join(', ');
}
if (meetingData.analytics?.sentiments?.positive_pct) {
input.sentimentScore = meetingData.analytics.sentiments.positive_pct / 100;
input.positivePercent = meetingData.analytics.sentiments.positive_pct;
}
if (meetingData.analytics?.sentiments?.negative_pct) {
input.negativePercent = meetingData.analytics.sentiments.negative_pct;
}
// Only add URLs if they are valid (not empty strings)
if (meetingData.transcript_url && meetingData.transcript_url.trim()) {
input.transcriptUrl = {
primaryLinkUrl: meetingData.transcript_url,
primaryLinkLabel: 'View Transcript'
};
}
if (meetingData.recording_url && meetingData.recording_url.trim()) {
input.recordingUrl = {
primaryLinkUrl: meetingData.recording_url,
primaryLinkLabel: 'Watch Recording'
};
}
if (meetingData.organizer_email) {
input.organizerEmail = meetingData.organizer_email;
}
// Set success status and timestamps
input.importStatus = 'SUCCESS';
input.lastImportAttempt = new Date().toISOString();
input.importAttempts = 1;
return input;
}
static toFailedMeetingCreateInput(
meetingId: string,
title: string,
error: string,
attempts: number = 1
): MeetingCreateInput {
const currentDate = new Date().toISOString();
return {
name: title || `Failed Meeting Import - ${meetingId}`,
meetingDate: currentDate,
duration: 0,
actionItemsCount: 0,
firefliesMeetingId: meetingId,
importStatus: 'FAILED',
importError: error,
lastImportAttempt: currentDate,
importAttempts: attempts,
};
}
}
@@ -1,10 +0,0 @@
export { config, main } from './receive-fireflies-notes';
export type {
FirefliesMeetingData,
FirefliesParticipant,
FirefliesWebhookPayload,
ProcessResult,
SummaryFetchConfig,
SummaryStrategy
} from './types';
@@ -1,95 +0,0 @@
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
export interface LoggerConfig {
logLevel: LogLevel;
isTestEnvironment: boolean;
}
const LOG_LEVELS: Record<LogLevel, number> = {
debug: 0,
info: 1,
warn: 2,
error: 3,
silent: 4,
};
/**
* App-level Fireflies application logger with configurable log levels.
*/
export class AppLogger {
private config: LoggerConfig;
private context: string;
constructor(context: string) {
this.context = context;
this.config = {
logLevel: this.parseLogLevel(process.env.LOG_LEVEL || 'error'),
isTestEnvironment: process.env.NODE_ENV === 'test' || process.env.JEST_WORKER_ID !== undefined,
};
}
private parseLogLevel(level: string): LogLevel {
const normalizedLevel = level.toLowerCase() as LogLevel;
return Object.keys(LOG_LEVELS).includes(normalizedLevel) ? normalizedLevel : 'error';
}
private shouldLog(level: LogLevel): boolean {
return LOG_LEVELS[level] >= LOG_LEVELS[this.config.logLevel];
}
/**
* Log debug information (LOG_LEVEL=debug)
*/
debug(message: string, ...args: any[]): void {
if (this.shouldLog('debug')) {
// eslint-disable-next-line no-console
console.log(`[${this.context}] ${message}`, ...args);
}
}
/**
* Log informational messages (LOG_LEVEL=info or lower)
*/
info(message: string, ...args: any[]): void {
if (this.shouldLog('info')) {
// eslint-disable-next-line no-console
console.log(`[${this.context}] ${message}`, ...args);
}
}
/**
* Log warnings (LOG_LEVEL=warn or lower)
*/
warn(message: string, ...args: any[]): void {
if (this.shouldLog('warn')) {
// eslint-disable-next-line no-console
console.warn(`[${this.context}] ${message}`, ...args);
}
}
/**
* Log errors (LOG_LEVEL=error or lower)
*/
error(message: string, ...args: any[]): void {
if (this.shouldLog('error')) {
// eslint-disable-next-line no-console
console.error(`[${this.context}] ${message}`, ...args);
}
}
/**
* Log critical errors that should ALWAYS be visible regardless of log level
* Use sparingly - only for fatal errors, security issues, or data corruption
*/
critical(message: string, ...args: any[]): void {
// eslint-disable-next-line no-console
console.error(`[${this.context}] CRITICAL: ${message}`, ...args);
}
}
/**
* Factory function to create loggers with automatic context detection
*/
export const createLogger = (context: string): AppLogger => {
return new AppLogger(context);
};
@@ -1,28 +0,0 @@
import { type ServerlessFunctionConfig } from 'twenty-sdk/application';
import type { ProcessResult } from './types';
import { WebhookHandler } from './webhook-handler';
export const main = async (
params: unknown,
headers?: Record<string, string>
): Promise<ProcessResult> => {
const handler = new WebhookHandler();
return handler.handle(params, headers);
};
export const config: ServerlessFunctionConfig = {
universalIdentifier: '2d3ea303-667c-4bbe-9e3d-db6ffb9d6c74',
name: 'receive-fireflies-notes',
description:
'Receives Fireflies webhooks, fetches meeting summaries, and stores them in Twenty.',
timeoutSeconds: 30,
triggers: [
{
universalIdentifier: 'a2117dc1-7674-4c7e-9d70-9feb9820e9e8',
type: 'route',
path: '/webhook/fireflies',
httpMethod: 'POST',
isAuthRequired: true,
},
],
};
@@ -1,570 +0,0 @@
import { createLogger } from './logger';
import type {
Contact,
CreateMeetingResponse,
CreateNoteResponse,
CreatePersonResponse,
FindMeetingResponse,
FindPeopleResponse,
FirefliesParticipant,
GraphQLResponse,
IdNode,
MeetingCreateInput,
} from './types';
const logger = createLogger('20 CRM Service');
export class TwentyCrmService {
private apiKey: string;
private apiUrl: string;
private isTestEnvironment: boolean;
constructor(apiKey: string, apiUrl: string) {
if (!apiKey) {
logger.critical('TWENTY_API_KEY is required but not provided - this is a critical configuration error');
throw new Error('TWENTY_API_KEY is required');
}
this.apiKey = apiKey;
this.apiUrl = apiUrl;
this.isTestEnvironment = process.env.NODE_ENV === 'test' || process.env.JEST_WORKER_ID !== undefined;
}
async findExistingMeeting(title: string): Promise<IdNode | undefined> {
const query = `
query FindMeeting($title: String!) {
meetings(filter: { name: { eq: $title } }) {
edges { node { id } }
}
}
`;
const variables = { title };
const response = await this.gqlRequest<FindMeetingResponse>(query, variables);
return response.data?.meetings?.edges?.[0]?.node;
}
async matchParticipantsToContacts(
participants: FirefliesParticipant[],
): Promise<{
matchedContacts: Contact[];
unmatchedParticipants: FirefliesParticipant[];
}> {
if (participants.length === 0) {
return { matchedContacts: [], unmatchedParticipants: [] };
}
// Split participants into those with emails and those with names only
const participantsWithEmails = participants.filter(p => p.email && p.email.trim());
const participantsNameOnly = participants.filter(p => !p.email || !p.email.trim());
let matchedContacts: Contact[] = [];
let unmatchedParticipants: FirefliesParticipant[] = [];
// 1. Match by email first
if (participantsWithEmails.length > 0) {
const emailMatches = await this.matchByEmail(participantsWithEmails);
matchedContacts.push(...emailMatches.matchedContacts);
unmatchedParticipants.push(...emailMatches.unmatchedParticipants);
}
// 2. For participants without emails, try name-based matching
if (participantsNameOnly.length > 0) {
const nameMatches = await this.matchByName(participantsNameOnly, matchedContacts);
matchedContacts.push(...nameMatches.matchedContacts);
unmatchedParticipants.push(...nameMatches.unmatchedParticipants);
}
return { matchedContacts, unmatchedParticipants };
}
private async matchByEmail(participants: FirefliesParticipant[]): Promise<{
matchedContacts: Contact[];
unmatchedParticipants: FirefliesParticipant[];
}> {
const emails = participants.map(({ email }) => email).filter(Boolean);
const query = `
query FindPeople($emails: [String!]!) {
people(filter: { emails: { primaryEmail: { in: $emails } } }) {
edges { node { id emails { primaryEmail } } }
}
}
`;
const variables = { emails };
const response = await this.gqlRequest<FindPeopleResponse>(query, variables);
const people = response.data?.people;
if (!people?.edges) {
return { matchedContacts: [], unmatchedParticipants: participants };
}
const matchedContacts = people.edges.map(({ node }) => ({
id: node.id,
email: node.emails?.primaryEmail || ''
}));
const matchedEmails = new Set(
matchedContacts
.map(({ email }) => email)
.filter((email) => Boolean(email)),
);
const unmatchedParticipants = participants.filter(
({ email }) => !matchedEmails.has(email)
);
return { matchedContacts, unmatchedParticipants };
}
private async matchByName(
participants: FirefliesParticipant[],
alreadyMatchedContacts: Contact[]
): Promise<{
matchedContacts: Contact[];
unmatchedParticipants: FirefliesParticipant[];
}> {
const matchedContacts: Contact[] = [];
const unmatchedParticipants: FirefliesParticipant[] = [];
// Get set of already matched contact IDs to avoid duplicates
const alreadyMatchedIds = new Set(alreadyMatchedContacts.map(c => c.id));
for (const participant of participants) {
const nameMatch = await this.findContactByName(participant.name);
if (nameMatch && !alreadyMatchedIds.has(nameMatch.id)) {
matchedContacts.push(nameMatch);
alreadyMatchedIds.add(nameMatch.id);
} else {
unmatchedParticipants.push(participant);
}
}
return { matchedContacts, unmatchedParticipants };
}
private async findContactByName(name: string): Promise<Contact | null> {
if (!name || !name.trim()) {
return null;
}
const nameParts = name.trim().split(/\s+/);
const firstName = nameParts[0];
const lastName = nameParts.slice(1).join(' ');
// Try exact name match first
let query = `
query FindPeopleByName($firstName: String!, $lastName: String) {
people(filter: {
and: [
{ name: { firstName: { eq: $firstName } } }
${lastName ? '{ name: { lastName: { eq: $lastName } } }' : ''}
]
}) {
edges { node { id emails { primaryEmail } name { firstName lastName } } }
}
}
`;
let variables: any = { firstName };
if (lastName) {
variables.lastName = lastName;
}
try {
const response = await this.gqlRequest<any>(query, variables);
const people = response.data?.people?.edges;
if (people && people.length > 0) {
const person = people[0].node;
return {
id: person.id,
email: person.emails?.primaryEmail || ''
};
}
// If no exact match and we have a last name, try fuzzy matching
if (lastName) {
query = `
query FindPeopleByNameFuzzy($firstName: String!) {
people(filter: { name: { firstName: { ilike: $firstName } } }) {
edges { node { id emails { primaryEmail } name { firstName lastName } } }
}
}
`;
const fuzzyResponse = await this.gqlRequest<any>(query, { firstName: `%${firstName}%` });
const fuzzyPeople = fuzzyResponse.data?.people?.edges;
if (fuzzyPeople && fuzzyPeople.length > 0) {
// Find best match by checking if last name contains our target
const bestMatch = fuzzyPeople.find((edge: any) => {
const personLastName = edge.node.name?.lastName || '';
return personLastName.toLowerCase().includes(lastName.toLowerCase());
});
if (bestMatch) {
const person = bestMatch.node;
return {
id: person.id,
email: person.emails?.primaryEmail || ''
};
}
}
}
return null;
} catch {
// Silently fail - don't break the entire process for a single contact lookup
return null;
}
}
async createContactsForUnmatched(
participants: FirefliesParticipant[],
): Promise<string[]> {
const newContactIds: string[] = [];
// Split participants into those with emails and those with names only
const participantsWithEmails = participants.filter(p => p.email && p.email.trim());
const participantsNameOnly = participants.filter(p => !p.email || !p.email.trim());
// Process participants with emails
if (participantsWithEmails.length > 0) {
const emailContactIds = await this.createContactsWithEmails(participantsWithEmails);
newContactIds.push(...emailContactIds);
}
// Process participants with names only
if (participantsNameOnly.length > 0) {
const nameContactIds = await this.createContactsNameOnly(participantsNameOnly);
newContactIds.push(...nameContactIds);
}
return newContactIds;
}
private async createContactsWithEmails(participants: FirefliesParticipant[]): Promise<string[]> {
const newContactIds: string[] = [];
// Deduplicate participants by email to prevent duplicate contact creation
const uniqueParticipants = participants.reduce<FirefliesParticipant[]>((unique, participant) => {
const existing = unique.find(p => p.email === participant.email);
if (!existing) {
unique.push(participant);
} else {
logger.warn(`Duplicate participant email detected: ${participant.email}. Using first occurrence.`);
}
return unique;
}, []);
for (const participant of uniqueParticipants) {
const [firstName, ...lastNameParts] = participant.name.trim().split(/\s+/);
const lastName = lastNameParts.join(' ');
const mutation = `
mutation CreatePerson($data: PersonCreateInput!) {
createPerson(data: $data) { id }
}
`;
const variables = {
data: {
name: { firstName, lastName },
emails: { primaryEmail: participant.email },
},
};
try {
const response = await this.gqlRequest<CreatePersonResponse>(mutation, variables);
if (!response.data?.createPerson?.id) {
throw new Error(`Failed to create contact for ${participant.email}`);
}
newContactIds.push(response.data.createPerson.id);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
if (errorMessage.includes('Duplicate Emails') || errorMessage.includes('BAD_USER_INPUT')) {
logger.warn(`Skipping contact creation for ${participant.email} due to duplicate email constraint: ${errorMessage}`);
continue;
}
throw error;
}
}
return newContactIds;
}
private async createContactsNameOnly(participants: FirefliesParticipant[]): Promise<string[]> {
const newContactIds: string[] = [];
// Deduplicate participants by name to prevent duplicate contact creation
const uniqueParticipants = participants.reduce<FirefliesParticipant[]>((unique, participant) => {
const existing = unique.find(p =>
p.name.toLowerCase().trim() === participant.name.toLowerCase().trim()
);
if (!existing) {
unique.push(participant);
} else {
logger.warn(`Duplicate participant name detected: ${participant.name}. Using first occurrence.`);
}
return unique;
}, []);
for (const participant of uniqueParticipants) {
// Check if we already have a contact with this exact name to avoid duplicates
const existingContact = await this.findContactByName(participant.name);
if (existingContact) {
logger.warn(`Contact with name "${participant.name}" already exists. Skipping creation.`);
continue;
}
const [firstName, ...lastNameParts] = participant.name.trim().split(/\s+/);
const lastName = lastNameParts.join(' ');
const mutation = `
mutation CreatePerson($data: PersonCreateInput!) {
createPerson(data: $data) { id }
}
`;
const variables = {
data: {
name: { firstName, lastName },
// Note: We don't set emails for name-only participants
// This will create a contact without an email address
},
};
try {
const response = await this.gqlRequest<CreatePersonResponse>(mutation, variables);
if (!response.data?.createPerson?.id) {
throw new Error(`Failed to create contact for ${participant.name}`);
}
newContactIds.push(response.data.createPerson.id);
logger.debug(`Created contact for name-only participant: ${participant.name}`);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
logger.warn(`Failed to create contact for ${participant.name}: ${errorMessage}`);
// Continue processing other participants instead of failing completely
continue;
}
}
return newContactIds;
}
async createNote(
contactId: string,
title: string,
body: string
): Promise<string> {
const noteId = await this.createNoteOnly(title, body);
await this.createNoteTarget(noteId, contactId);
return noteId;
}
async createNoteOnly(
title: string,
body: string
): Promise<string> {
const mutation = `
mutation CreateNote($data: NoteCreateInput!) {
createNote(data: $data) { id }
}
`;
const variables = {
data: {
title,
bodyV2: {
markdown: body.trim()
},
},
};
const response = await this.gqlRequest<CreateNoteResponse>(mutation, variables);
if (!response.data?.createNote?.id) {
throw new Error(`Failed to create note`);
}
return response.data.createNote.id;
}
async createNoteTarget(noteId: string, contactId: string): Promise<void> {
const mutation = `
mutation CreateNoteTarget($data: NoteTargetCreateInput!) {
createNoteTarget(data: $data) {
id
noteId
personId
}
}
`;
const variables = {
data: {
noteId,
personId: contactId,
},
};
await this.gqlRequest<any>(mutation, variables);
}
async createMeetingTarget(meetingId: string, contactId: string): Promise<void> {
const mutation = `
mutation CreateMeetingTarget($data: NoteTargetCreateInput!) {
createNoteTarget(data: $data) {
id
meetingId
personId
}
}
`;
const variables = {
data: {
meetingId,
personId: contactId,
},
};
await this.gqlRequest<any>(mutation, variables);
}
async createMeeting(meetingData: MeetingCreateInput): Promise<string> {
const mutation = `
mutation CreateMeeting($data: MeetingCreateInput!) {
createMeeting(data: $data) { id }
}
`;
const variables = { data: meetingData };
// Debug: log the variables being sent
if (!this.isTestEnvironment) {
logger.debug('createMeeting variables:', JSON.stringify(variables, null, 2));
}
const response = await this.gqlRequest<CreateMeetingResponse>(mutation, variables);
if (!response.data?.createMeeting?.id) {
throw new Error('Failed to create meeting: Invalid response from server');
}
return response.data.createMeeting.id;
}
private async gqlRequest<T>(
query: string,
variables?: Record<string, unknown>
): Promise<GraphQLResponse<T>> {
const url = `${this.apiUrl}/graphql`;
try {
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify({ query, variables }),
});
if (!res.ok) {
let errorMessage = `GraphQL request failed with status ${res.status}`;
try {
const errorText = await res.text();
if (errorText) {
errorMessage += `: ${errorText}`;
}
} catch {
// Ignore error when reading response body
}
throw new Error(errorMessage);
}
const json = await res.json() as GraphQLResponse<T> & {
errors?: Array<{ message?: string; extensions?: Record<string, unknown> }>
};
if (json?.errors && Array.isArray(json.errors) && json.errors.length > 0) {
const firstError = json.errors[0];
const errorMessage = firstError?.message || 'GraphQL error';
const errorCode = firstError?.extensions?.code as string | undefined;
if (errorCode) {
throw new Error(`${errorMessage} (Code: ${errorCode})`);
}
throw new Error(errorMessage);
}
return json;
} catch (error) {
logger.error('GraphQL request error:', error);
throw error;
}
}
async createFailedMeeting(meetingData: MeetingCreateInput): Promise<string> {
const mutation = `
mutation CreateMeeting($data: MeetingCreateInput!) {
createMeeting(data: $data) { id }
}
`;
const variables = { data: meetingData };
if (!this.isTestEnvironment) {
logger.debug('createFailedMeeting variables:', JSON.stringify(variables, null, 2));
}
const response = await this.gqlRequest<CreateMeetingResponse>(mutation, variables);
if (!response.data?.createMeeting?.id) {
throw new Error('Failed to create failed meeting record: Invalid response from server');
}
return response.data.createMeeting.id;
}
async findFailedMeetings(): Promise<any[]> {
const query = `
query FindFailedMeetings {
meetings(filter: { importStatus: { eq: "FAILED" } }) {
edges {
node {
id
name
firefliesMeetingId
importError
lastImportAttempt
importAttempts
createdAt
}
}
}
}
`;
const response = await this.gqlRequest<any>(query);
return response.data?.meetings?.edges?.map((edge: any) => edge.node) || [];
}
async retryFailedMeeting(meetingId: string, updatedData: Partial<MeetingCreateInput>): Promise<void> {
const mutation = `
mutation UpdateMeeting($where: MeetingWhereUniqueInput!, $data: MeetingUpdateInput!) {
updateMeeting(where: $where, data: $data) { id }
}
`;
const variables = {
where: { id: meetingId },
data: {
...updatedData,
lastImportAttempt: new Date().toISOString(),
importAttempts: { increment: 1 }
}
};
await this.gqlRequest<any>(mutation, variables);
}
}
@@ -1,130 +0,0 @@
// Fireflies API Types
export type FirefliesParticipant = {
email: string;
name: string;
};
export type FirefliesWebhookPayload = {
meetingId: string;
eventType: string;
clientReferenceId?: string;
};
export type FirefliesMeetingData = {
id: string;
title: string;
date: string;
duration: number;
participants: FirefliesParticipant[];
organizer_email?: string;
summary: {
action_items: string[];
keywords?: string[];
overview: string;
gist?: string;
topics_discussed?: string[];
meeting_type?: string;
bullet_gist?: string;
};
analytics?: {
sentiments?: {
positive_pct: number;
negative_pct: number;
neutral_pct: number;
};
};
transcript_url: string;
recording_url?: string;
summary_status?: string;
};
// Configuration Types
export type SummaryStrategy = 'immediate_only' | 'immediate_with_retry' | 'delayed_polling' | 'basic_only';
export type SummaryFetchConfig = {
strategy: SummaryStrategy;
retryAttempts: number;
retryDelay: number;
pollInterval: number;
maxPolls: number;
};
export type WebhookConfig = {
secret: string;
apiUrl: string;
};
// Processing Result Types
export type ProcessResult = {
success: boolean;
meetingId?: string;
noteIds?: string[];
newContacts?: string[];
errors?: string[];
debug?: string[];
summaryReady?: boolean;
summaryPending?: boolean;
enhancementScheduled?: boolean;
actionItemsCount?: number;
sentimentScore?: number;
meetingType?: string;
keyTopics?: string[];
};
// Twenty CRM Types
export type GraphQLResponse<T> = {
data: T;
errors?: Array<{
message?: string;
extensions?: { code?: string }
}>;
};
export type IdNode = { id: string };
export type FindMeetingResponse = {
meetings: { edges: Array<{ node: IdNode }> };
};
export type FindPeopleResponse = {
people: { edges: Array<{ node: { id: string; emails: { primaryEmail: string } } }> };
};
export type CreatePersonResponse = {
createPerson: { id: string }
};
export type CreateNoteResponse = {
createNote: { id: string }
};
export type CreateMeetingResponse = {
createMeeting: { id: string }
};
export type Contact = {
id: string;
email: string;
};
export type MeetingCreateInput = {
name: string;
noteId?: string | null; // This is the relation field
meetingDate: string;
duration: number;
meetingType?: string | null;
keywords?: string | null;
sentimentScore?: number | null;
positivePercent?: number | null;
negativePercent?: number | null;
actionItemsCount: number;
transcriptUrl?: { primaryLinkUrl: string; primaryLinkLabel: string } | null;
recordingUrl?: { primaryLinkUrl: string; primaryLinkLabel: string } | null;
firefliesMeetingId: string;
organizerEmail?: string | null;
importStatus?: 'SUCCESS' | 'FAILED' | 'PENDING' | 'RETRYING' | null;
importError?: string | null;
lastImportAttempt?: string | null;
importAttempts?: number | null;
};
@@ -1,30 +0,0 @@
export const toBoolean = (value: string | undefined, defaultValue: boolean): boolean => {
if (value === undefined) return defaultValue;
const normalized = value.trim().toLowerCase();
return normalized === 'true' || normalized === '1' || normalized === 'yes';
};
import type { SummaryFetchConfig, SummaryStrategy } from './types';
export const getApiUrl = (): string => {
return process.env.SERVER_URL || 'http://localhost:3000';
};
export const getSummaryFetchConfig = (): SummaryFetchConfig => {
const strategy = (process.env.FIREFLIES_SUMMARY_STRATEGY as SummaryStrategy) || 'immediate_with_retry';
// Ultra-conservative defaults to respect 50 requests/day API limit
// With 3 attempts at 15-minute intervals, max 3 API calls per webhook (45 minutes total)
return {
strategy,
retryAttempts: parseInt(process.env.FIREFLIES_RETRY_ATTEMPTS || '3', 10),
retryDelay: parseInt(process.env.FIREFLIES_RETRY_DELAY || '120000', 10), // 2 minutes
pollInterval: parseInt(process.env.FIREFLIES_POLL_INTERVAL || '120000', 10), // 2 minutes
maxPolls: parseInt(process.env.FIREFLIES_MAX_POLLS || '3', 10),
};
};
export const shouldAutoCreateContacts = (): boolean => {
return toBoolean(process.env.AUTO_CREATE_CONTACTS, true);
};
@@ -1,345 +0,0 @@
import { FirefliesApiClient } from './fireflies-api-client';
import { MeetingFormatter } from './formatters';
import { createLogger } from './logger';
import { TwentyCrmService } from './twenty-crm-service';
import type { FirefliesWebhookPayload, ProcessResult } from './types';
import { getApiUrl, getSummaryFetchConfig, shouldAutoCreateContacts } from './utils';
import {
getWebhookSecretFingerprint,
isValidFirefliesPayload,
verifyWebhookSignature
} from './webhook-validator';
declare const process: { env: Record<string, string | undefined> };
const logger = createLogger('fireflies');
export class WebhookHandler {
private debug: string[] = [];
private isTestEnvironment: boolean;
constructor() {
this.isTestEnvironment = process.env.NODE_ENV === 'test' || process.env.JEST_WORKER_ID !== undefined;
}
async handle(params: unknown, headers?: Record<string, string>): Promise<ProcessResult> {
const result: ProcessResult = {
success: false,
noteIds: [],
newContacts: [],
errors: [],
};
try {
logger.debug('invoked');
logger.debug(`apiUrl=${getApiUrl()}`);
// 0) Validate environment configuration
const firefliesApiKey = process.env.FIREFLIES_API_KEY || '';
const twentyApiKey = process.env.TWENTY_API_KEY || '';
if (!firefliesApiKey) {
logger.critical('FIREFLIES_API_KEY not configured - this is a critical configuration error');
throw new Error('FIREFLIES_API_KEY environment variable is required');
}
if (!twentyApiKey) {
logger.critical('TWENTY_API_KEY not configured - this is a critical configuration error');
throw new Error('TWENTY_API_KEY environment variable is required');
}
// 1) Parse and validate webhook payload and extract headers if wrapped together
const { payload, extractedHeaders } = this.parsePayload(params);
const finalHeaders = extractedHeaders || headers;
logger.debug(`payload meetingId=${payload.meetingId} eventType="${payload.eventType}"`);
// 2) Verify webhook signature
const webhookSecret = process.env.FIREFLIES_WEBHOOK_SECRET || '';
const secretFingerprint = getWebhookSecretFingerprint(webhookSecret);
logger.debug(`webhook secret fingerprint=${secretFingerprint}`);
this.verifySignature(payload, finalHeaders, webhookSecret);
logger.debug('signature verification: ok');
// 3) Fetch meeting data from Fireflies
const summaryConfig = getSummaryFetchConfig();
logger.debug(`summary strategy: ${summaryConfig.strategy} (retryAttempts=${summaryConfig.retryAttempts}, retryDelay=${summaryConfig.retryDelay}ms)`);
logger.debug(`fetching meeting data from Fireflies API`);
const firefliesClient = new FirefliesApiClient(firefliesApiKey);
const { data: meetingData, summaryReady } = await firefliesClient.fetchMeetingDataWithRetry(
payload.meetingId,
summaryConfig
);
logger.debug(`meeting data fetched: title="${meetingData.title}" summaryReady=${summaryReady}`);
result.summaryReady = summaryReady;
result.summaryPending = !summaryReady;
// Extract business intelligence
if (summaryReady) {
result.actionItemsCount = meetingData.summary.action_items.length;
result.keyTopics = meetingData.summary.topics_discussed;
result.meetingType = meetingData.summary.meeting_type;
if (meetingData.analytics?.sentiments) {
const sentiments = meetingData.analytics.sentiments;
result.sentimentScore = sentiments.positive_pct / 100;
}
}
// 4) Check for duplicate meetings
const twentyService = new TwentyCrmService(
twentyApiKey,
getApiUrl()
);
const existingMeeting = await twentyService.findExistingMeeting(meetingData.title);
if (existingMeeting) {
logger.debug(`meeting already exists id=${existingMeeting.id}`);
result.success = true;
result.meetingId = existingMeeting.id;
result.debug = this.debug;
return result;
}
logger.debug('no existing meeting found, proceeding');
// 5) Match participants to existing contacts
logger.debug(`total participants from API: ${meetingData.participants.length}`);
meetingData.participants.forEach((p, idx) => {
logger.debug(`participant ${idx + 1}: name="${p.name}" email="${p.email || 'none'}"`);
});
const { matchedContacts, unmatchedParticipants } = await twentyService.matchParticipantsToContacts(
meetingData.participants
);
logger.debug(`matched=${matchedContacts.length} unmatched=${unmatchedParticipants.length}`);
unmatchedParticipants.forEach((p, idx) => {
logger.debug(`unmatched ${idx + 1}: name="${p.name}" email="${p.email || 'none'}"`);
});
// 6) Optionally create contacts
const autoCreate = shouldAutoCreateContacts();
const newContactIds = autoCreate
? await twentyService.createContactsForUnmatched(unmatchedParticipants)
: [];
result.newContacts = newContactIds;
logger.debug(`autoCreate=${autoCreate} createdContacts=${newContactIds.length}`);
// 7) Create note first (so we can link to it from the meeting)
const allContactIds = [...matchedContacts.map(({ id }) => id), ...newContactIds];
const noteBody = MeetingFormatter.formatNoteBody(meetingData);
const noteId = await twentyService.createNoteOnly(
`Meeting: ${meetingData.title}`,
noteBody
);
result.noteIds = [noteId];
logger.debug(`created note id=${noteId}`);
// 8) Create meeting with direct relationship to the note
const meetingInput = MeetingFormatter.toMeetingCreateInput(meetingData, noteId);
logger.debug(`meeting duration: ${meetingData.duration} min (raw from API) → ${meetingInput.duration} min (rounded)`);
result.meetingId = await twentyService.createMeeting(meetingInput);
logger.debug(`created meeting id=${result.meetingId} with noteId=${noteId}`);
// 9) Link note to participants (Meeting link is handled via the relation field)
await this.linkNoteToParticipants(
twentyService,
noteId,
allContactIds
);
logger.debug(`linked note to ${allContactIds.length} participants`);
result.success = true;
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
logger.error(`error: ${message}`);
result.errors?.push(message);
// Try to create a failed meeting record for tracking
await this.createFailedMeetingRecord(params, message);
}
result.debug = this.debug;
return result;
}
private parsePayload(params: unknown): { payload: FirefliesWebhookPayload; extractedHeaders?: Record<string, string> } {
let normalizedParams = params;
let extractedHeaders: Record<string, string> | undefined;
// Handle string-encoded params
if (typeof normalizedParams === 'string') {
logger.debug(`received params as string length=${normalizedParams.length}`);
try {
const parsed = JSON.parse(normalizedParams);
normalizedParams = parsed;
if (parsed && typeof parsed === 'object') {
const parsedKeys = Object.keys(parsed as Record<string, unknown>);
logger.debug(`parsed params keys: ${parsedKeys.join(',') || 'none'}`);
}
} catch (parseError) {
logger.error(`error parsing string params: ${String(parseError)}`);
throw new Error('Invalid or missing webhook payload');
}
}
// Handle wrapped payloads and extract headers if present
let payload: FirefliesWebhookPayload | undefined;
if (isValidFirefliesPayload(normalizedParams)) {
payload = normalizedParams as FirefliesWebhookPayload;
} else if (normalizedParams && typeof normalizedParams === 'object') {
const wrapper = normalizedParams as Record<string, unknown>;
// Extract headers if present in wrapper
if (wrapper.headers && typeof wrapper.headers === 'object' && !Array.isArray(wrapper.headers)) {
extractedHeaders = wrapper.headers as Record<string, string>;
const headerKeys = Object.keys(extractedHeaders);
logger.debug(`extracted headers from wrapper: ${headerKeys.join(',')}`);
}
const wrapperKeys = ['params', 'payload', 'body', 'data', 'event'];
for (const key of wrapperKeys) {
const candidate = wrapper[key];
if (isValidFirefliesPayload(candidate)) {
logger.debug(`detected payload under wrapper key "${key}"`);
payload = candidate as FirefliesWebhookPayload;
break;
}
}
}
if (!payload) {
logger.error('error: Invalid or missing webhook payload');
throw new Error('Invalid or missing webhook payload');
}
// Log payload keys for debugging
const payloadRecord = payload as Record<string, unknown>;
const payloadKeys = Object.keys(payloadRecord);
if (payloadKeys.length > 0) {
logger.debug(`payload keys: ${payloadKeys.join(',')}`);
}
return { payload, extractedHeaders };
}
private verifySignature(
payload: FirefliesWebhookPayload,
headers: Record<string, string> | undefined,
webhookSecret: string
): void {
// Extract headers
const normalizedHeaders = headers || {};
const headerKeys = Object.keys(normalizedHeaders);
if (headerKeys.length > 0) {
logger.debug(`header keys: ${headerKeys.join(',')}`);
}
const headerSignature = Object.entries(normalizedHeaders).find(
([key]) => key.toLowerCase() === 'x-hub-signature',
)?.[1];
const payloadRecord = payload as Record<string, unknown>;
const payloadSignature =
typeof payloadRecord['x-hub-signature'] === 'string'
? (payloadRecord['x-hub-signature'] as string)
: undefined;
if (payloadSignature) {
logger.debug('found signature inside payload');
}
const signature =
(typeof headerSignature === 'string' ? headerSignature : undefined) || payloadSignature;
const body = typeof normalizedHeaders['body'] === 'string'
? normalizedHeaders['body']
: JSON.stringify(payloadRecord);
const signatureCheck = verifyWebhookSignature(body, signature, webhookSecret);
if (!signatureCheck.isValid) {
logger.debug(
`signature check failed. headerPresent=${Boolean(
headerSignature,
)} payloadSignaturePresent=${Boolean(payloadSignature)}`,
);
if (signature) {
logger.debug(`provided signature=${signature}`);
} else {
logger.debug('provided signature=undefined');
}
logger.debug(
`computed signature=${signatureCheck.computedSignature ?? 'unavailable'}`,
);
logger.critical('Invalid webhook signature - potential security threat detected in production');
throw new Error('Invalid webhook signature');
}
}
private async linkNoteToParticipants(
twentyService: TwentyCrmService,
noteId: string,
contactIds: string[]
): Promise<void> {
// Create Note-Person links for each participant
for (const contactId of contactIds) {
try {
await twentyService.createNoteTarget(noteId, contactId);
logger.debug(`linked note ${noteId} to person ${contactId}`);
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
logger.error(`failed to link note to person ${contactId}: ${message}`);
// Continue with other participants
}
}
}
private async createFailedMeetingRecord(params: unknown, error: string): Promise<void> {
try {
const twentyApiKey = process.env.TWENTY_API_KEY || '';
if (!twentyApiKey) {
logger.debug('Cannot create failed meeting record: TWENTY_API_KEY not configured');
return;
}
// Try to extract meeting ID and title from the params
let meetingId = 'unknown';
let meetingTitle = 'Unknown Meeting';
const { payload } = this.parsePayload(params);
if (payload?.meetingId) {
meetingId = payload.meetingId;
// Try to get meeting title from Fireflies API if possible
const firefliesApiKey = process.env.FIREFLIES_API_KEY || '';
if (firefliesApiKey) {
try {
const firefliesClient = new FirefliesApiClient(firefliesApiKey);
const meetingData = await firefliesClient.fetchMeetingData(meetingId);
meetingTitle = meetingData.title || meetingTitle;
} catch (fetchError) {
logger.debug(`Could not fetch meeting title: ${fetchError instanceof Error ? fetchError.message : 'Unknown error'}`);
}
}
}
const twentyService = new TwentyCrmService(twentyApiKey, getApiUrl());
const failedMeetingData = MeetingFormatter.toFailedMeetingCreateInput(
meetingId,
meetingTitle,
error
);
const failedMeetingId = await twentyService.createFailedMeeting(failedMeetingData);
logger.debug(`Created failed meeting record: ${failedMeetingId}`);
} catch (recordError) {
// Don't throw here - we don't want to break the original error handling
logger.error(`Failed to create failed meeting record: ${recordError instanceof Error ? recordError.message : 'Unknown error'}`);
}
}
}
@@ -1,54 +0,0 @@
import { createHash, createHmac } from 'crypto';
import type { FirefliesWebhookPayload } from './types';
export type SignatureVerificationResult = {
isValid: boolean;
computedSignature?: string;
};
export const verifyWebhookSignature = (
body: string,
signature: string | undefined,
secret: string
): SignatureVerificationResult => {
if (!signature) {
return { isValid: false };
}
try {
const hmac = createHmac('sha256', secret);
hmac.update(body, 'utf8');
const computed = hmac.digest('hex');
const computedSignature = `sha256=${computed}`;
const isValid = signature === computedSignature;
return { isValid, computedSignature };
} catch {
return { isValid: false };
}
};
export const getWebhookSecretFingerprint = (secret: string): string => {
return createHash('sha256').update(secret).digest('hex').substring(0, 8);
};
export const isValidFirefliesPayload = (
params: unknown
): params is FirefliesWebhookPayload => {
if (!params || typeof params !== 'object') {
return false;
}
const payload = params as Record<string, unknown>;
return (
typeof payload['meetingId'] === 'string' &&
payload['meetingId'].length > 0 &&
typeof payload['eventType'] === 'string' &&
payload['eventType'].length > 0 &&
(payload['clientReferenceId'] === undefined ||
typeof payload['clientReferenceId'] === 'string')
);
};
@@ -1,712 +0,0 @@
import * as crypto from 'crypto';
import {
main,
type FirefliesMeetingData,
type FirefliesWebhookPayload,
} from '../actions/receive-fireflies-notes';
// Helper to generate HMAC signature
const generateHMACSignature = (body: string, secret: string): string => {
const signature = crypto
.createHmac('sha256', secret)
.update(body, 'utf8')
.digest('hex');
return `sha256=${signature}`;
};
// Mock raw Fireflies API response with full summary (before transformation)
const mockFirefliesApiResponseWithSummary = {
id: 'test-meeting-001',
title: 'Product Demo with Client',
date: '2024-11-02T14:00:00Z',
duration: 1800,
participants: [
'Sarah Sales <sales@company.com>',
'John Client <client@customer.com>',
],
organizer_email: 'sales@company.com',
summary: {
action_items: [
'Follow up with pricing proposal by Friday',
'Schedule technical deep-dive next week',
'Share case studies from similar clients',
],
keywords: ['product demo', 'pricing', 'technical requirements', 'integration'],
overview: 'Successful product demonstration with positive client feedback. Client expressed strong interest in the enterprise plan and requested technical documentation for their IT team.',
gist: 'Product demo went well, client interested in enterprise plan, next steps identified',
topics_discussed: ['product features', 'pricing discussion', 'integration capabilities', 'support options'],
meeting_type: 'Sales Call',
bullet_gist: '• Demonstrated core product features\n• Discussed enterprise pricing\n• Addressed integration questions',
},
sentiments: { // Note: Raw API has sentiments at top level, not in analytics
positive_pct: 75,
negative_pct: 10,
neutral_pct: 15,
},
transcript_url: 'https://app.fireflies.ai/transcript/test-001',
video_url: 'https://app.fireflies.ai/recording/test-001',
summary_status: 'completed',
};
// Transformed meeting data (after fetchFirefliesMeetingData processes it)
const mockMeetingWithFullSummary: FirefliesMeetingData = {
id: 'test-meeting-001',
title: 'Product Demo with Client',
date: '2024-11-02T14:00:00Z',
duration: 1800,
participants: [
{ email: 'sales@company.com', name: 'Sarah Sales' },
{ email: 'client@customer.com', name: 'John Client' },
],
organizer_email: 'sales@company.com',
summary: {
action_items: [
'Follow up with pricing proposal by Friday',
'Schedule technical deep-dive next week',
'Share case studies from similar clients',
],
keywords: ['product demo', 'pricing', 'technical requirements', 'integration'],
overview: 'Successful product demonstration with positive client feedback. Client expressed strong interest in the enterprise plan and requested technical documentation for their IT team.',
gist: 'Product demo went well, client interested in enterprise plan, next steps identified',
topics_discussed: ['product features', 'pricing discussion', 'integration capabilities', 'support options'],
meeting_type: 'Sales Call',
bullet_gist: '• Demonstrated core product features\n• Discussed enterprise pricing\n• Addressed integration questions',
},
analytics: {
sentiments: {
positive_pct: 75,
negative_pct: 10,
neutral_pct: 15,
},
},
transcript_url: 'https://app.fireflies.ai/transcript/test-001',
recording_url: 'https://app.fireflies.ai/recording/test-001',
summary_status: 'completed',
};
// Mock raw API response without summary (processing)
const mockFirefliesApiResponseWithoutSummary = {
id: 'test-meeting-002',
title: 'Team Standup',
date: '2024-11-02T15:00:00Z',
duration: 900,
participants: [
'Alice Developer <dev1@company.com>',
'Bob Developer <dev2@company.com>',
],
organizer_email: 'dev1@company.com',
summary: {
action_items: [],
keywords: [],
overview: '',
gist: '',
topics_discussed: [],
},
transcript_url: 'https://app.fireflies.ai/transcript/test-002',
summary_status: 'processing',
};
// Mock meeting data without summary (processing) - currently unused but kept for reference
const _mockMeetingWithoutSummary = {
id: 'test-meeting-002',
title: 'Team Standup',
date: '2024-11-02T15:00:00Z',
duration: 900,
participants: [
{ email: 'dev1@company.com', name: 'Alice Developer' },
{ email: 'dev2@company.com', name: 'Bob Developer' },
],
organizer_email: 'dev1@company.com',
summary: {
action_items: [],
keywords: [],
overview: '',
gist: '',
topics_discussed: [],
},
transcript_url: 'https://app.fireflies.ai/transcript/test-002',
summary_status: 'processing',
};
// Mock raw API response for team meeting
const mockFirefliesApiResponseTeamMeeting = {
...mockFirefliesApiResponseWithSummary,
id: 'test-team-003',
title: 'Sprint Planning',
participants: [
'Alice Scrum <scrum@company.com>',
'Bob Developer <dev1@company.com>',
'Carol Coder <dev2@company.com>',
'David QA <qa@company.com>',
],
summary: {
...mockFirefliesApiResponseWithSummary.summary,
meeting_type: 'Sprint Planning',
},
};
// Mock team meeting with multiple participants (transformed) - currently unused but kept for reference
const _mockTeamMeeting = {
...mockMeetingWithFullSummary,
id: 'test-team-003',
title: 'Sprint Planning',
participants: [
{ email: 'scrum@company.com', name: 'Alice Scrum' },
{ email: 'dev1@company.com', name: 'Bob Developer' },
{ email: 'dev2@company.com', name: 'Carol Coder' },
{ email: 'qa@company.com', name: 'David QA' },
],
summary: {
...mockMeetingWithFullSummary.summary,
meeting_type: 'Sprint Planning',
},
};
// Mock environment variables
const originalEnv = process.env;
beforeEach(() => {
process.env = {
...originalEnv,
FIREFLIES_WEBHOOK_SECRET: 'test_webhook_secret',
FIREFLIES_API_KEY: 'test_fireflies_api_key',
TWENTY_API_KEY: 'test_twenty_api_key',
SERVER_URL: 'http://localhost:3000',
AUTO_CREATE_CONTACTS: 'true',
DEBUG_LOGS: 'false',
FIREFLIES_SUMMARY_STRATEGY: 'immediate_with_retry',
FIREFLIES_RETRY_ATTEMPTS: '3',
FIREFLIES_RETRY_DELAY: '1000',
};
});
afterEach(() => {
process.env = originalEnv;
jest.clearAllMocks();
});
describe('Fireflies Webhook Integration v2', () => {
describe('Webhook Authentication', () => {
it('should verify HMAC SHA-256 signature from x-hub-signature header', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
// Mock Fireflies API
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
transcript: mockFirefliesApiResponseWithSummary, // Use raw API format
},
}),
});
}
// Twenty API mocks
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
createNote: { id: 'new-note-id' },
createMeeting: { id: 'new-meeting-id' },
},
}),
});
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(result.success).toBe(true);
});
it('should reject requests with invalid signature', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const invalidSignature = 'sha256=invalid_signature_here';
const result = await main(payload, { 'x-hub-signature': invalidSignature, body });
expect(result.success).toBe(false);
expect(result.errors).toContain('Invalid webhook signature');
});
it('should reject requests without signature header', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const result = await main(payload, {});
expect(result.success).toBe(false);
expect(result.errors).toContain('Invalid webhook signature');
});
it('should reject requests with missing webhook secret env var', async () => {
delete process.env.FIREFLIES_WEBHOOK_SECRET;
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const result = await main(payload, {});
expect(result.success).toBe(false);
});
});
describe('Fireflies GraphQL Integration', () => {
it('should fetch meeting data from Fireflies API', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
const firefliesApiMock = jest.fn();
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
firefliesApiMock();
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
transcript: mockFirefliesApiResponseWithSummary, // Use raw API format
},
}),
});
}
// Twenty API mocks
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
createNote: { id: 'new-note-id' },
createMeeting: { id: 'new-meeting-id' },
},
}),
});
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(firefliesApiMock).toHaveBeenCalled();
expect(result.success).toBe(true);
});
it('should handle Fireflies API fetch failures gracefully', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.reject(new Error('Fireflies API unavailable'));
}
return Promise.resolve({ ok: true, json: () => Promise.resolve({ data: {} }) });
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(result.success).toBe(false);
expect(result.errors?.[0]).toContain('Fireflies API');
});
it('should handle malformed GraphQL responses', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { malformed: 'response' },
}),
});
}
return Promise.resolve({ ok: true, json: () => Promise.resolve({ data: {} }) });
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(result.success).toBe(false);
expect(result.errors?.[0]).toContain('Invalid response from Fireflies API');
});
});
describe('Summary Processing', () => {
it('should create complete records when summary is ready', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { transcript: mockFirefliesApiResponseWithSummary }, // Use raw API format
}),
});
}
// Twenty API mocks
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
createNote: { id: 'new-note-id' },
createMeeting: { id: 'new-meeting-id' },
},
}),
});
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(result.success).toBe(true);
expect(result.summaryReady).toBe(true);
expect(result.actionItemsCount).toBe(3);
expect(result.sentimentScore).toBeCloseTo(0.75, 2); // Use toBeCloseTo for floating point comparison
expect(result.meetingType).toBe('Sales Call');
expect(result.keyTopics).toEqual(['product features', 'pricing discussion', 'integration capabilities', 'support options']);
});
it('should create basic records when summary is pending', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-002',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { transcript: mockFirefliesApiResponseWithoutSummary }, // Use raw API format
}),
});
}
// Twenty API mocks
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
createNote: { id: 'new-note-id' },
createMeeting: { id: 'new-meeting-id' },
},
}),
});
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(result.success).toBe(true);
expect(result.summaryPending).toBe(true);
expect(result.noteIds || result.meetingId).toBeDefined();
});
it('should retry summary fetch with exponential backoff', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-003',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
let attemptCount = 0;
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
attemptCount++;
// First two attempts return no summary, third returns full summary
if (attemptCount < 3) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { transcript: mockFirefliesApiResponseWithoutSummary }, // Use raw API format
}),
});
}
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { transcript: mockFirefliesApiResponseWithSummary }, // Use raw API format
}),
});
}
// Twenty API mocks
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
createNote: { id: 'new-note-id' },
createMeeting: { id: 'new-meeting-id' },
},
}),
});
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(attemptCount).toBe(3);
expect(result.success).toBe(true);
expect(result.summaryReady).toBe(true);
});
it('should handle immediate_only strategy with single fetch attempt', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-004',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
let fetchCount = 0;
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
fetchCount++;
// Return summary not ready
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { transcript: mockFirefliesApiResponseWithoutSummary },
}),
});
}
// Twenty API mocks
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
createNote: { id: 'new-note-id' },
createMeeting: { id: 'new-meeting-id' },
},
}),
});
});
// Override strategy for this test
process.env.FIREFLIES_SUMMARY_STRATEGY = 'immediate_only';
const result = await main(payload, { 'x-hub-signature': signature, body });
// Should only fetch once with immediate_only strategy
expect(fetchCount).toBe(1);
expect(result.success).toBe(true);
expect(result.summaryPending).toBe(true);
// Reset to default
process.env.FIREFLIES_SUMMARY_STRATEGY = 'immediate_with_retry';
});
});
describe('CRM Record Creation', () => {
it('should create summary-focused notes for 1-on-1 meetings', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
const createNoteMock = jest.fn();
global.fetch = jest.fn().mockImplementation((url: string, options?: any) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { transcript: mockFirefliesApiResponseWithSummary }, // Use raw API format
}),
});
}
// Twenty API
const body = options?.body ? JSON.parse(options.body) : {};
if (body.query?.includes('createNote')) {
createNoteMock(body.variables);
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { createNote: { id: 'new-note-id' } },
}),
});
}
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
createMeeting: { id: 'new-meeting-id' },
},
}),
});
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(result.success).toBe(true);
expect(createNoteMock).toHaveBeenCalled();
const noteData = createNoteMock.mock.calls[0][0];
expect(noteData.data.title).toContain('Meeting:');
expect(noteData.data.bodyV2.markdown).toContain('## Overview'); // Markdown header, not bold
expect(noteData.data.bodyV2.markdown).toContain('## Action Items'); // Markdown header, not bold
expect(noteData.data.bodyV2.markdown).toContain('**Sentiment:**'); // This is bold
expect(noteData.data.bodyV2.markdown).toContain('[View Full Transcript]');
});
it('should create meeting records for multi-party meetings', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-team-003',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
const createMeetingMock = jest.fn();
global.fetch = jest.fn().mockImplementation((url: string, options?: any) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { transcript: mockFirefliesApiResponseTeamMeeting }, // Use raw API format
}),
});
}
// Twenty API
const body = options?.body ? JSON.parse(options.body) : {};
if (body.query?.includes('createMeeting')) {
createMeetingMock(body.variables);
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { createMeeting: { id: 'new-meeting-id' } },
}),
});
}
if (body.query?.includes('createNote')) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { createNote: { id: 'new-note-id' } },
}),
});
}
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
},
}),
});
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(result.success).toBe(true);
expect(result.meetingId).toBeDefined();
expect(createMeetingMock).toHaveBeenCalled();
});
});
describe('Error Handling & Resilience', () => {
it('should never throw uncaught exceptions', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-critical-error',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
global.fetch = jest.fn().mockImplementation(() => {
throw new Error('Critical failure');
});
await expect(main(payload, { 'x-hub-signature': signature, body })).resolves.toEqual(
expect.objectContaining({ success: false, errors: expect.any(Array) })
);
});
it('should handle missing payload gracefully', async () => {
const result = await main(null as any, {});
expect(result.success).toBe(false);
expect(result.errors).toBeDefined();
});
it('should handle invalid payload structure', async () => {
const invalidPayload = { invalid: 'data' };
const result = await main(invalidPayload as any, {});
expect(result.success).toBe(false);
expect(result.errors).toBeDefined();
});
});
});
@@ -1,16 +0,0 @@
// Test setup for Fireflies app
// Mock global fetch for all tests
global.fetch = jest.fn();
// Setup test environment variables
process.env.FIREFLIES_WEBHOOK_SECRET = 'testsecret';
process.env.AUTO_CREATE_CONTACTS = 'true';
process.env.SERVER_URL = 'http://localhost:3000';
process.env.TWENTY_API_KEY = 'test-api-key';
process.env.LOG_LEVEL = 'silent';
// Reset mocks before each test
beforeEach(() => {
jest.clearAllMocks();
});
@@ -1,11 +0,0 @@
export {
config,
main,
type FirefliesMeetingData,
type FirefliesParticipant,
type FirefliesWebhookPayload,
type ProcessResult,
type SummaryFetchConfig,
type SummaryStrategy
} from '../../serverlessFunctions/receive-fireflies-notes/src/index';
@@ -1,14 +0,0 @@
import { ObjectMetadata } from 'twenty-sdk/application';
@ObjectMetadata({
universalIdentifier: 'd1831348-b4a4-4426-9c0b-0af19e7a9c27',
nameSingular: 'meeting',
namePlural: 'meetings',
labelSingular: 'Meeting',
labelPlural: 'Meetings',
description:
'Meetings imported from Fireflies with AI-generated summaries, sentiment, and action items.',
icon: 'IconVideo',
})
export class Meeting {}
@@ -1,26 +0,0 @@
{
"compileOnSave": false,
"compilerOptions": {
"sourceMap": true,
"declaration": true,
"outDir": "./dist",
"rootDir": ".",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"strict": true,
"target": "es2018",
"module": "esnext",
"lib": ["es2020", "dom"],
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"resolveJsonModule": true
},
"exclude": [
"node_modules",
"dist",
"**/*.test.ts",
"**/*.spec.ts"
]
}

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