Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(toggl-track): track time on Toggl Track and Toggl 2.0 from flows and AI agents (#16318)

Odai Ahmad75bb6dd6efe7
diff --git a/bun.lock b/bun.lock
index d90af3241ba..f8ac9be42a0 100644
--- a/bun.lock
+++ b/bun.lock
@@ -9242,7 +9242,7 @@
},
"packages/pieces/community/toggl-track": {
"name": "@activepieces/piece-toggl-track",
- "version": "0.1.9",
+ "version": "0.2.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -9251,6 +9251,7 @@
},
"devDependencies": {
"tslib": "^2.3.0",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/totalcms": {
diff --git a/packages/pieces/community/toggl-track/package.json b/packages/pieces/community/toggl-track/package.json
index 8bc59efdbde..0f59e590172 100644
--- a/packages/pieces/community/toggl-track/package.json
+++ b/packages/pieces/community/toggl-track/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-toggl-track",
- "version": "0.1.9",
+ "version": "0.2.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
@@ -11,11 +11,13 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "^2.3.0"
+ "tslib": "^2.3.0",
+ "vitest": "3.2.6"
},
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
}
}
diff --git a/packages/pieces/community/toggl-track/src/i18n/translation.json b/packages/pieces/community/toggl-track/src/i18n/translation.json
index fcb0ec730be..ae7dd507332 100644
--- a/packages/pieces/community/toggl-track/src/i18n/translation.json
+++ b/packages/pieces/community/toggl-track/src/i18n/translation.json
@@ -1,6 +1,5 @@
{
- "Toggl Track is a time tracking application that allows users to track their daily activities across different platforms.": "Toggl Track is a time tracking application that allows users to track their daily activities across different platforms.",
- "\n 1. Log in to your Toggl Track account.\n 2. Go to your **Profile settings**.\n 3. Find the **API Token** at the bottom of the page and copy it.\n ": "\n 1. Log in to your Toggl Track account.\n 2. Go to your **Profile settings**.\n 3. Find the **API Token** at the bottom of the page and copy it.\n ",
+ "Toggl Track is a time tracking application that allows users to track their daily activities across different platforms. Works with classic Toggl Track and Toggl 2.0 accounts.": "Toggl Track is a time tracking application that allows users to track their daily activities across different platforms. Works with classic Toggl Track and Toggl 2.0 accounts.",
"Create Client": "Create Client",
"Create Project": "Create Project",
"Create Task": "Create Task",
@@ -14,6 +13,29 @@
"Find Client": "Find Client",
"Find Tag": "Find Tag",
"Find Time Entry": "Find Time Entry",
+ "Log Time (Agent)": "Log Time (Agent)",
+ "Start Timer (Agent)": "Start Timer (Agent)",
+ "Time Summary (Agent)": "Time Summary (Agent)",
+ "Get Client": "Get Client",
+ "Update Client": "Update Client",
+ "Delete Client": "Delete Client",
+ "Get Project": "Get Project",
+ "Update Project": "Update Project",
+ "Update Tag": "Update Tag",
+ "Delete Tag": "Delete Tag",
+ "Get Time Entry": "Get Time Entry",
+ "Get Current Time Entry": "Get Current Time Entry",
+ "Update Time Entry": "Update Time Entry",
+ "Delete Time Entry": "Delete Time Entry",
+ "Search Detailed Report": "Search Detailed Report",
+ "List Workspaces": "List Workspaces",
+ "Get Workspace": "Get Workspace",
+ "List Organization Users": "List Organization Users",
+ "Invite User to Organization": "Invite User to Organization",
+ "Add User to Project": "Add User to Project",
+ "Create Group": "Create Group",
+ "Delete Group": "Delete Group",
+ "Custom API Call": "Custom API Call",
"Create a new client in a workspace.": "Create a new client in a workspace.",
"Create a new project in a workspace.": "Create a new project in a workspace.",
"Create a new task under a project.": "Create a new task under a project.",
@@ -27,6 +49,29 @@
"Find a client by name or status in a workspace.": "Find a client by name or status in a workspace.",
"Find a tag by name in a workspace.": "Find a tag by name in a workspace.",
"Find time entries by description.": "Find time entries by description.",
+ "Logs a completed time entry using a project name.": "Logs a completed time entry using a project name.",
+ "Starts a running timer using a project name.": "Starts a running timer using a project name.",
+ "Sums tracked time in a date range, grouped by project, user, or client.": "Sums tracked time in a date range, grouped by project, user, or client.",
+ "Get a client by its ID.": "Get a client by its ID.",
+ "Update the name, notes, or external reference of a client.": "Update the name, notes, or external reference of a client.",
+ "Permanently delete a client from a workspace.": "Permanently delete a client from a workspace.",
+ "Get a project by its ID.": "Get a project by its ID.",
+ "Update the settings of a project.": "Update the settings of a project.",
+ "Rename a tag.": "Rename a tag.",
+ "Permanently delete a tag from a workspace.": "Permanently delete a tag from a workspace.",
+ "Get a time entry by its ID.": "Get a time entry by its ID.",
+ "Get the time entry that is running right now, if any.": "Get the time entry that is running right now, if any.",
+ "Update a single time entry.": "Update a single time entry.",
+ "Delete a time entry.": "Delete a time entry.",
+ "Search all time entries of a workspace in a date range (detailed report).": "Search all time entries of a workspace in a date range (detailed report).",
+ "List the workspaces you belong to.": "List the workspaces you belong to.",
+ "Get the details of a workspace.": "Get the details of a workspace.",
+ "List the members of an organization.": "List the members of an organization.",
+ "Invite someone by email to an organization and workspace.": "Invite someone by email to an organization and workspace.",
+ "Add a workspace member to a project.": "Add a workspace member to a project.",
+ "Create a group (team) in an organization.": "Create a group (team) in an organization.",
+ "Delete a group (team) from an organization.": "Delete a group (team) from an organization.",
+ "Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Workspace": "Workspace",
"Client Name": "Client Name",
"External Reference": "External Reference",
@@ -73,40 +118,69 @@
"Since Timestamp": "Since Timestamp",
"Include Meta Data": "Include Meta Data",
"Include Sharing": "Include Sharing",
+ "Start": "Start",
+ "Duration (minutes)": "Duration (minutes)",
+ "Group By": "Group By",
+ "New Name": "New Name",
+ "Clear Notes": "Clear Notes",
+ "Tag": "Tag",
+ "Time Entry ID": "Time Entry ID",
+ "Clear Description": "Clear Description",
+ "Clear Tags": "Clear Tags",
+ "Project IDs": "Project IDs",
+ "User IDs": "User IDs",
+ "Client IDs": "Client IDs",
+ "Page Size": "Page Size",
+ "Next Page Cursor": "Next Page Cursor",
+ "Email": "Email",
+ "Workspace Admin": "Workspace Admin",
+ "User ID": "User ID",
+ "Project Manager": "Project Manager",
+ "Group Name": "Group Name",
+ "Member Organization User IDs": "Member Organization User IDs",
+ "Emoji": "Emoji",
+ "Group ID": "Group ID",
+ "Method": "Method",
+ "Headers": "Headers",
+ "Query Parameters": "Query Parameters",
+ "Body Type": "Body Type",
+ "Body": "Body",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
+ "Follow redirects": "Follow redirects",
"The workspace to operate in.": "The workspace to operate in.",
"The name of the new client.": "The name of the new client.",
- "External reference to link this client with external systems.": "External reference to link this client with external systems.",
- "Notes for the client.": "Notes for the client.",
+ "External system reference. Toggl Track (Classic) only.": "External system reference. Toggl Track (Classic) only.",
+ "Notes for the client. Toggl Track (Classic) only.": "Notes for the client. Toggl Track (Classic) only.",
"The name of the new project.": "The name of the new project.",
"The client to associate the project with.": "The client to associate the project with.",
"Whether the project is private or not.": "Whether the project is private or not.",
"Whether the project is billable. (Premium feature)": "Whether the project is billable. (Premium feature)",
"Whether the project is a template. (Premium feature)": "Whether the project is a template. (Premium feature)",
- "External reference to link this project with external systems.": "External reference to link this project with external systems.",
"Project color in hex format (e.g. #ff0000).": "Project color in hex format (e.g. #ff0000).",
- "Whether the project is active.": "Whether the project is active.",
+ "Whether the project is active. Toggl Track (Classic) only.": "Whether the project is active. Toggl Track (Classic) only.",
"Whether estimates are based on task hours. (Premium feature)": "Whether estimates are based on task hours. (Premium feature)",
"Estimated hours for the project. (Premium feature)": "Estimated hours for the project. (Premium feature)",
- "Hourly rate for the project. (Premium feature)": "Hourly rate for the project. (Premium feature)",
- "Project fixed fee. (Premium feature)": "Project fixed fee. (Premium feature)",
+ "Hourly rate. Premium feature, Toggl Track (Classic) only.": "Hourly rate. Premium feature, Toggl Track (Classic) only.",
+ "Project fixed fee, in the workspace currency. (Premium feature)": "Project fixed fee, in the workspace currency. (Premium feature)",
"Start date of project timeframe (YYYY-MM-DD).": "Start date of project timeframe (YYYY-MM-DD).",
"End date of project timeframe (YYYY-MM-DD).": "End date of project timeframe (YYYY-MM-DD).",
"The project to create the task under.": "The project to create the task under.",
"The name of the new task.": "The name of the new task.",
- "The estimated time for the task in seconds.": "The estimated time for the task in seconds.",
- "External reference to link this task with external systems.": "External reference to link this task with external systems.",
- "Whether the task is active. Use false to mark as done.": "Whether the task is active. Use false to mark as done.",
- "Creator ID, if omitted, will use requester user ID.": "Creator ID, if omitted, will use requester user ID.",
+ "Estimated time in seconds. Toggl 2.0 stores whole minutes.": "Estimated time in seconds. Toggl 2.0 stores whole minutes.",
+ "Uncheck to mark the task done. Toggl Track (Classic) only.": "Uncheck to mark the task done. Toggl Track (Classic) only.",
+ "Creator user ID, defaults to yours. Toggl 2.0 assigns them the task.": "Creator user ID, defaults to yours. Toggl 2.0 assigns them the task.",
"The name of the new tag.": "The name of the new tag.",
"The start time of the entry in UTC.": "The start time of the entry in UTC.",
"Duration of the time entry. Use a negative number (e.g., -1) to start a running timer.": "Duration of the time entry. Use a negative number (e.g., -1) to start a running timer.",
"The stop time of the entry in UTC. Can be omitted if still running.": "The stop time of the entry in UTC. Can be omitted if still running.",
"The task to select.": "The task to select.",
"The project to associate the time entry with.": "The project to associate the time entry with.",
- "Tags to associate with the time entry. You can create new tags by typing them.": "Tags to associate with the time entry. You can create new tags by typing them.",
+ "Tags to associate with the time entry. Tags that do not exist yet are created in the workspace.": "Tags to associate with the time entry. Tags that do not exist yet are created in the workspace.",
"Whether the time entry is marked as billable.": "Whether the time entry is marked as billable.",
"Time entry creator ID. If omitted, will use requester user ID.": "Time entry creator ID. If omitted, will use requester user ID.",
- "The organization to operate in.": "The organization to operate in.",
+ "The organization to operate in. For Toggl 2.0 this is the organization from the connection.": "The organization to operate in. For Toggl 2.0 this is the organization from the connection.",
"The name or email of the user to find.": "The name or email of the user to find.",
"Return only active users.": "Return only active users.",
"Page number for pagination.": "Page number for pagination.",
@@ -116,7 +190,7 @@
"Return only billable projects.": "Return only billable projects.",
"Get only projects assigned to the current user.": "Get only projects assigned to the current user.",
"Return only template projects.": "Return only template projects.",
- "Number of items per page (max 200).": "Number of items per page (max 200).",
+ "Number of items per page (max 200; Toggl 2.0: max 100).": "Number of items per page (max 200; Toggl 2.0: max 100).",
"Search by task name.": "Search by task name.",
"Filter by project ID.": "Filter by project ID.",
"Filter by active state.": "Filter by active state.",
@@ -128,13 +202,71 @@
"The name of the client to find (case-insensitive).": "The name of the client to find (case-insensitive).",
"Filter clients by their status.": "Filter clients by their status.",
"Search by tag name.": "Search by tag name.",
+ "Number of items per page (Toggl 2.0: max 100).": "Number of items per page (Toggl 2.0: max 100).",
+ "The workspace to search in. Toggl Track (Classic): leave empty to search all workspaces. Toggl 2.0: leave empty to use your current workspace.": "The workspace to search in. Toggl Track (Classic): leave empty to search all workspaces. Toggl 2.0: leave empty to use your current workspace.",
"Search for time entries containing this text in description.": "Search for time entries containing this text in description.",
"Get entries from start_date (YYYY-MM-DD or RFC3339 format).": "Get entries from start_date (YYYY-MM-DD or RFC3339 format).",
"Get entries until end_date (YYYY-MM-DD or RFC3339 format).": "Get entries until end_date (YYYY-MM-DD or RFC3339 format).",
"Get entries before given date (YYYY-MM-DD or RFC3339 format).": "Get entries before given date (YYYY-MM-DD or RFC3339 format).",
- "Get entries modified since this UNIX timestamp.": "Get entries modified since this UNIX timestamp.",
- "Should the response contain data for meta entities.": "Should the response contain data for meta entities.",
- "Include sharing details in the response.": "Include sharing details in the response.",
+ "Entries modified since this UNIX timestamp (range start on Toggl 2.0).": "Entries modified since this UNIX timestamp (range start on Toggl 2.0).",
+ "Include meta entity data. Toggl Track (Classic) only.": "Include meta entity data. Toggl Track (Classic) only.",
+ "Include sharing details in the response. Toggl Track (Classic) only.": "Include sharing details in the response. Toggl Track (Classic) only.",
+ "What the time was spent on.": "What the time was spent on.",
+ "Project name or ID. Leave empty for no project.": "Project name or ID. Leave empty for no project.",
+ "Start time: an ISO datetime, or \"now\".": "Start time: an ISO datetime, or \"now\".",
+ "How long the work took, in minutes.": "How long the work took, in minutes.",
+ "What the timer is for.": "What the timer is for.",
+ "First day of the range (YYYY-MM-DD).": "First day of the range (YYYY-MM-DD).",
+ "Last day of the range (YYYY-MM-DD, inclusive). Leave empty for today.": "Last day of the range (YYYY-MM-DD, inclusive). Leave empty for today.",
+ "\"project\" (default), \"user\", or \"client\".": "\"project\" (default), \"user\", or \"client\".",
+ "Project name or ID. Leave empty for all projects.": "Project name or ID. Leave empty for all projects.",
+ "The client to use. Agents can pass the client ID directly.": "The client to use. Agents can pass the client ID directly.",
+ "Leave empty to keep the current name.": "Leave empty to keep the current name.",
+ "Leave empty to keep the current notes. Toggl Track (Classic) only.": "Leave empty to keep the current notes. Toggl Track (Classic) only.",
+ "Remove the notes. Toggl Track (Classic) only.": "Remove the notes. Toggl Track (Classic) only.",
+ "Leave empty to keep the current value. Toggl Track (Classic) only.": "Leave empty to keep the current value. Toggl Track (Classic) only.",
+ "Whether the project is private. Leave empty to keep the current value.": "Whether the project is private. Leave empty to keep the current value.",
+ "Whether the project is billable. (Premium feature) Leave empty to keep the current value.": "Whether the project is billable. (Premium feature) Leave empty to keep the current value.",
+ "No archives the project, Yes restores it. Leave empty to keep the current value.": "No archives the project, Yes restores it. Leave empty to keep the current value.",
+ "Hex color like #ff0000. Leave empty to keep the current color.": "Hex color like #ff0000. Leave empty to keep the current color.",
+ "Leave empty to keep the current estimate. (Premium feature)": "Leave empty to keep the current estimate. (Premium feature)",
+ "Leave empty to keep it. Premium, Toggl Track (Classic) only.": "Leave empty to keep it. Premium, Toggl Track (Classic) only.",
+ "Start date of the project timeframe (YYYY-MM-DD).": "Start date of the project timeframe (YYYY-MM-DD).",
+ "End date of the project timeframe (YYYY-MM-DD).": "End date of the project timeframe (YYYY-MM-DD).",
+ "The tag to use. Agents can pass the tag ID directly.": "The tag to use. Agents can pass the tag ID directly.",
+ "The new name of the tag.": "The new name of the tag.",
+ "The ID of the time entry (from Find Time Entry or a trigger).": "The ID of the time entry (from Find Time Entry or a trigger).",
+ "The ID of the time entry to update.": "The ID of the time entry to update.",
+ "Leave empty to keep the current description.": "Leave empty to keep the current description.",
+ "Remove the description.": "Remove the description.",
+ "Remove every tag from the time entry.": "Remove every tag from the time entry.",
+ "New start time. Leave empty to keep the current start.": "New start time. Leave empty to keep the current start.",
+ "New stop time. Leave empty to keep the current stop.": "New stop time. Leave empty to keep the current stop.",
+ "New duration; ignored when Stop Time is given. Empty keeps current.": "New duration; ignored when Stop Time is given. Empty keeps current.",
+ "Whether the time entry is billable. Leave empty to keep the current value.": "Whether the time entry is billable. Leave empty to keep the current value.",
+ "The ID of the time entry to delete.": "The ID of the time entry to delete.",
+ "First day of the report (YYYY-MM-DD).": "First day of the report (YYYY-MM-DD).",
+ "Last day of the report (YYYY-MM-DD, inclusive). Leave empty for today.": "Last day of the report (YYYY-MM-DD, inclusive). Leave empty for today.",
+ "Comma-separated project IDs to include.": "Comma-separated project IDs to include.",
+ "Comma-separated user IDs to include.": "Comma-separated user IDs to include.",
+ "Comma-separated client IDs to include. Toggl Track (Classic) only.": "Comma-separated client IDs to include. Toggl Track (Classic) only.",
+ "Only entries whose description contains this text.": "Only entries whose description contains this text.",
+ "Rows per page (default 50, max 100 on Toggl 2.0).": "Rows per page (default 50, max 100 on Toggl 2.0).",
+ "Pass next_cursor from the last result; empty for the first page.": "Pass next_cursor from the last result; empty for the first page.",
+ "Only members whose name or email contains this text.": "Only members whose name or email contains this text.",
+ "The email address to invite.": "The email address to invite.",
+ "Make the invited user an admin of the workspace.": "Make the invited user an admin of the workspace.",
+ "The user_id of the member (from Find User).": "The user_id of the member (from Find User).",
+ "Make the user a manager of the project.": "Make the user a manager of the project.",
+ "Comma-separated IDs from List Organization Users.": "Comma-separated IDs from List Organization Users.",
+ "Group emoji. Toggl 2.0 only.": "Group emoji. Toggl 2.0 only.",
+ "The ID of the group to delete (group_id from Create Group).": "The ID of the group to delete (group_id from Create Group).",
+ "Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
+ "Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
"Inactive": "Inactive",
"Both": "Both",
"Name": "Name",
@@ -142,6 +274,14 @@
"Ascending": "Ascending",
"Descending": "Descending",
"Archived": "Archived",
+ "Yes": "Yes",
+ "No": "No",
+ "GET": "GET",
+ "POST": "POST",
+ "PATCH": "PATCH",
+ "PUT": "PUT",
+ "DELETE": "DELETE",
+ "HEAD": "HEAD",
"New Client": "New Client",
"New or Updated Workspace": "New or Updated Workspace",
"New Project": "New Project",
diff --git a/packages/pieces/community/toggl-track/src/index.ts b/packages/pieces/community/toggl-track/src/index.ts
index 8840972c1f4..b7bb5cfaff5 100644
--- a/packages/pieces/community/toggl-track/src/index.ts
+++ b/packages/pieces/community/toggl-track/src/index.ts
@@ -1,6 +1,7 @@
-import { PieceAuth, createPiece } from '@activepieces/pieces-framework';
-import { PieceCategory } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
+import { togglTrackAuth } from './lib/auth';
+import { togglApi } from './lib/common/client';
import { createClient } from './lib/actions/create-client';
import { createProject } from './lib/actions/create-project';
import { createTask } from './lib/actions/create-task';
@@ -14,6 +15,28 @@ import { findTask } from './lib/actions/find-task';
import { findClient } from './lib/actions/find-client';
import { findTag } from './lib/actions/find-tag';
import { findTimeEntry } from './lib/actions/find-time-entry';
+import { getClient } from './lib/actions/get-client';
+import { updateClient } from './lib/actions/update-client';
+import { deleteClient } from './lib/actions/delete-client';
+import { getProject } from './lib/actions/get-project';
+import { updateProject } from './lib/actions/update-project';
+import { updateTag } from './lib/actions/update-tag';
+import { deleteTag } from './lib/actions/delete-tag';
+import { getTimeEntry } from './lib/actions/get-time-entry';
+import { getCurrentTimeEntry } from './lib/actions/get-current-time-entry';
+import { updateTimeEntry } from './lib/actions/update-time-entry';
+import { deleteTimeEntry } from './lib/actions/delete-time-entry';
+import { searchDetailedReport } from './lib/actions/search-detailed-report';
+import { listWorkspaces } from './lib/actions/list-workspaces';
+import { getWorkspace } from './lib/actions/get-workspace';
+import { listOrganizationUsers } from './lib/actions/list-organization-users';
+import { inviteUser } from './lib/actions/invite-user';
+import { addUserToProject } from './lib/actions/add-user-to-project';
+import { createGroup } from './lib/actions/create-group';
+import { deleteGroup } from './lib/actions/delete-group';
+import { logTimeAi } from './lib/actions/log-time-ai';
+import { startTimerAi } from './lib/actions/start-timer-ai';
+import { timeSummaryAi } from './lib/actions/time-summary-ai';
import { newClient } from './lib/triggers/new-client';
import { newWorkspace } from './lib/triggers/new-workspace';
import { newProject } from './lib/triggers/new-project';
@@ -22,43 +45,10 @@ import { newTimeEntry } from './lib/triggers/new-time-entry';
import { newTimeEntryStarted } from './lib/triggers/new-time-entry-started';
import { newTag } from './lib/triggers/new-tag';
-const validateAuth = async ({ auth }: { auth: string }) => {
- try {
- await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: 'https://api.track.toggl.com/api/v9/me',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(`${auth}:api_token`).toString(
- 'base64'
- )}`,
- },
- });
- return {
- valid: true as const,
- };
- } catch (e) {
- return {
- valid: false as const,
- error: 'Invalid API token.',
- };
- }
-};
-
-export const togglTrackAuth = PieceAuth.SecretText({
- displayName: 'API Token',
- description: `
- 1. Log in to your Toggl Track account.
- 2. Go to your **Profile settings**.
- 3. Find the **API Token** at the bottom of the page and copy it.
- `,
- required: true,
- validate: validateAuth,
-});
-
export const togglTrack = createPiece({
displayName: 'Toggl Track',
- description: 'Toggl Track is a time tracking application that allows users to track their daily activities across different platforms.',
+ description:
+ 'Toggl Track is a time tracking application that allows users to track their daily activities across different platforms. Works with classic Toggl Track and Toggl 2.0 accounts.',
auth: togglTrackAuth,
minimumSupportedRelease: '0.36.1',
logoUrl: 'https://cdn.activepieces.com/pieces/toggl-track.png',
@@ -78,6 +68,35 @@ export const togglTrack = createPiece({
findClient,
findTag,
findTimeEntry,
+ logTimeAi,
+ startTimerAi,
+ timeSummaryAi,
+ getClient,
+ updateClient,
+ deleteClient,
+ getProject,
+ updateProject,
+ updateTag,
+ deleteTag,
+ getTimeEntry,
+ getCurrentTimeEntry,
+ updateTimeEntry,
+ deleteTimeEntry,
+ searchDetailedReport,
+ listWorkspaces,
+ getWorkspace,
+ listOrganizationUsers,
+ inviteUser,
+ addUserToProject,
+ createGroup,
+ deleteGroup,
+ createCustomApiCallAction({
+ auth: togglTrackAuth,
+ baseUrl: (auth) => (auth ? togglApi.baseUrl(auth) : ''),
+ authMapping: async (auth) => ({
+ Authorization: togglApi.authorizationHeader(auth),
+ }),
+ }),
],
triggers: [
newClient,
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/add-user-to-project.ts b/packages/pieces/community/toggl-track/src/lib/actions/add-user-to-project.ts
new file mode 100644
index 00000000000..cafbcda7947
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/add-user-to-project.ts
@@ -0,0 +1,65 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const addUserToProject = createAction({
+ auth: togglTrackAuth,
+ name: 'add_user_to_project',
+ classification: 'WRITE',
+ displayName: 'Add User to Project',
+ description: 'Add a workspace member to a project.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Adds a workspace member to a project by user ID, optionally as manager. Classic only. Returns the project membership; fails if they are already a member.',
+ idempotent: false,
+ },
+ props: {
+ workspace_id: togglCommon.workspace_id,
+ project_id: togglCommon.project_id,
+ user_id: Property.ShortText({
+ displayName: 'User ID',
+ description: 'The user_id of the member (from Find User).',
+ required: true,
+ }),
+ manager: Property.Checkbox({
+ displayName: 'Project Manager',
+ description: 'Make the user a manager of the project.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: togglOutputSchemas.projectUser,
+ async run(context) {
+ const auth = context.auth;
+ if (togglApi.isTwo(auth)) {
+ throw new Error(
+ 'Add User to Project is only available for Toggl Track (Classic) connections. On Toggl 2.0, add project members in the Toggl app.'
+ );
+ }
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const projectId = togglApi.requireId({
+ value: context.propsValue.project_id,
+ label: 'Project',
+ });
+ const userId = togglApi.requireId({
+ value: context.propsValue.user_id,
+ label: 'User ID',
+ });
+ return togglApi.request<Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: `/workspaces/${workspaceId}/project_users`,
+ body: {
+ project_id: projectId,
+ user_id: userId,
+ manager: context.propsValue.manager ?? false,
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/create-client.ts b/packages/pieces/community/toggl-track/src/lib/actions/create-client.ts
index a5eb6752ebb..0405900e5f8 100644
--- a/packages/pieces/community/toggl-track/src/lib/actions/create-client.ts
+++ b/packages/pieces/community/toggl-track/src/lib/actions/create-client.ts
@@ -1,7 +1,9 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import { togglTrackAuth } from '../auth';
import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoClient } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
export const createClient = createAction({
auth: togglTrackAuth,
@@ -10,7 +12,11 @@ export const createClient = createAction({
displayName: 'Create Client',
description: 'Create a new client in a workspace.',
audience: 'both',
- aiMetadata: { description: 'Creates a new client record in a Toggl Track workspace, given a workspace ID and client name (optional external reference and notes). Use when an agent needs to register a billable/organizational client before associating projects with it. Not idempotent: each call creates a new client even if the name already exists.', idempotent: false },
+ aiMetadata: {
+ description:
+ 'Creates a client in a workspace. Needs the workspace and a name; notes and external reference are saved on Classic only. Returns the new client. A retry creates a duplicate.',
+ idempotent: false,
+ },
props: {
workspace_id: togglCommon.workspace_id,
name: Property.ShortText({
@@ -21,36 +27,43 @@ export const createClient = createAction({
external_reference: Property.ShortText({
displayName: 'External Reference',
description:
- 'External reference to link this client with external systems.',
+ 'External system reference. Toggl Track (Classic) only.',
required: false,
}),
notes: Property.LongText({
displayName: 'Notes',
- description: 'Notes for the client.',
+ description: 'Notes for the client. Toggl Track (Classic) only.',
required: false,
}),
},
+ outputSchema: togglOutputSchemas.client,
async run(context) {
- const { workspace_id, name, external_reference, notes } =
- context.propsValue;
- const apiToken = context.auth;
+ const { name, external_reference, notes } = context.propsValue;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/clients`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(`${apiToken}:api_token`).toString(
- 'base64'
- )}`,
- },
+ if (togglApi.isTwo(auth)) {
+ const created = await togglApi.request<TwoClient>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: `/workspaces/${workspaceId}/clients`,
+ body: { name },
+ });
+ return togglModels.client(created);
+ }
+
+ return togglApi.request<Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: `/workspaces/${workspaceId}/clients`,
body: {
name,
external_reference,
notes,
},
});
-
- return response.body;
},
});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/create-group.ts b/packages/pieces/community/toggl-track/src/lib/actions/create-group.ts
new file mode 100644
index 00000000000..03674e656da
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/create-group.ts
@@ -0,0 +1,135 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const createGroup = createAction({
+ auth: togglTrackAuth,
+ name: 'create_group',
+ classification: 'WRITE',
+ displayName: 'Create Group',
+ description: 'Create a group (team) in an organization.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Creates a group (team) in the organization with optional members. Returns { group_id, name, workspace_ids, user_ids }. A retry creates a duplicate.',
+ idempotent: false,
+ },
+ props: {
+ organization_id: togglCommon.organization_id,
+ workspace_id: togglCommon.workspace_id,
+ name: Property.ShortText({
+ displayName: 'Group Name',
+ required: true,
+ }),
+ user_ids: Property.ShortText({
+ displayName: 'Member Organization User IDs',
+ description:
+ 'Comma-separated IDs from List Organization Users.',
+ required: false,
+ }),
+ emoji: Property.ShortText({
+ displayName: 'Emoji',
+ description: 'Group emoji. Toggl 2.0 only.',
+ required: false,
+ defaultValue: '👥',
+ }),
+ },
+ outputSchema: togglOutputSchemas.group,
+ async run(context) {
+ const auth = context.auth;
+ const name = context.propsValue.name.trim();
+ if (!name) {
+ throw new Error('Group Name is required.');
+ }
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const userIds = (context.propsValue.user_ids ?? '')
+ .split(',')
+ .map((part) => part.trim())
+ .filter((part) => part.length > 0)
+ .map((part) =>
+ togglApi.requireId({ value: part, label: 'Member Organization User IDs' })
+ );
+
+ if (togglApi.isTwo(auth)) {
+ const group = await togglApi.request<TwoGroup>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: `/organizations/${togglApi.twoOrganizationId(auth)}/groups`,
+ body: {
+ name,
+ emoji: context.propsValue.emoji?.trim() || '👥',
+ organization_users: userIds,
+ workspaces: [workspaceId],
+ },
+ });
+ return {
+ group_id: group.id,
+ name: group.name,
+ workspace_ids: idsOf({ items: group.workspaces, key: 'workspace_id' }),
+ user_ids: idsOf({ items: group.users, key: 'organization_user_id' }),
+ at: group.updated_at ?? group.created_at ?? null,
+ };
+ }
+
+ const organizationId = togglApi.requireId({
+ value: context.propsValue.organization_id,
+ label: 'Organization',
+ });
+ const group = await togglApi.request<ClassicGroup>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: `/organizations/${organizationId}/groups`,
+ body: { name, users: userIds, workspaces: [workspaceId] },
+ });
+ return {
+ group_id: group.group_id,
+ name: group.name,
+ workspace_ids: idsOf({ items: group.workspaces, key: 'workspace_id' }),
+ user_ids: idsOf({ items: group.users, key: 'user_id' }),
+ at: group.at ?? null,
+ };
+ },
+});
+
+function idsOf({
+ items,
+ key,
+}: {
+ items: unknown[] | null | undefined;
+ key: string;
+}): number[] {
+ return (items ?? [])
+ .map((item) => {
+ if (typeof item === 'number') {
+ return item;
+ }
+ if (typeof item === 'object' && item !== null && key in item) {
+ const value: unknown = Object.entries(item).find(([k]) => k === key)?.[1];
+ return typeof value === 'number' ? value : null;
+ }
+ return null;
+ })
+ .filter((id): id is number => id !== null);
+}
+
+type ClassicGroup = {
+ group_id: number;
+ name: string;
+ workspaces?: unknown[] | null;
+ users?: unknown[] | null;
+ at?: string;
+};
+
+type TwoGroup = {
+ id: number;
+ name: string;
+ workspaces?: unknown[] | null;
+ users?: unknown[] | null;
+ created_at?: string;
+ updated_at?: string;
+};
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/create-project.ts b/packages/pieces/community/toggl-track/src/lib/actions/create-project.ts
index 150629b551d..7b768e8550f 100644
--- a/packages/pieces/community/toggl-track/src/lib/actions/create-project.ts
+++ b/packages/pieces/community/toggl-track/src/lib/actions/create-project.ts
@@ -1,7 +1,13 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import {
+ createAction,
+ isNil,
+ Property,
+} from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoProject } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
export const createProject = createAction({
auth: togglTrackAuth,
@@ -10,7 +16,11 @@ export const createProject = createAction({
displayName: 'Create Project',
description: 'Create a new project in a workspace.',
audience: 'both',
- aiMetadata: { description: 'Creates a new project in a Toggl Track workspace, given a workspace ID and project name; optionally links a client and sets billing, rate, color, and timeframe (several rate/estimate options require a premium plan). Use when an agent needs to set up a project to track time against. Not idempotent: each call creates a new project regardless of name.', idempotent: false },
+ aiMetadata: {
+ description:
+ 'Creates a project in a workspace. Needs the workspace and a name; client, privacy, billable, color, estimate, fee, and dates are optional (hourly rate and external reference are Classic only). Returns the new project. A retry creates a duplicate.',
+ idempotent: false,
+ },
props: {
workspace_id: togglCommon.workspace_id,
name: Property.ShortText({
@@ -40,7 +50,7 @@ export const createProject = createAction({
external_reference: Property.ShortText({
displayName: 'External Reference',
description:
- 'External reference to link this project with external systems.',
+ 'External system reference. Toggl Track (Classic) only.',
required: false,
}),
color: Property.ShortText({
@@ -50,7 +60,7 @@ export const createProject = createAction({
}),
active: Property.Checkbox({
displayName: 'Active',
- description: 'Whether the project is active.',
+ description: 'Whether the project is active. Toggl Track (Classic) only.',
required: false,
defaultValue: true,
}),
@@ -68,12 +78,14 @@ export const createProject = createAction({
}),
rate: Property.Number({
displayName: 'Hourly Rate',
- description: 'Hourly rate for the project. (Premium feature)',
+ description:
+ 'Hourly rate. Premium feature, Toggl Track (Classic) only.',
required: false,
}),
fixed_fee: Property.Number({
displayName: 'Fixed Fee',
- description: 'Project fixed fee. (Premium feature)',
+ description:
+ 'Project fixed fee, in the workspace currency. (Premium feature)',
required: false,
}),
start_date: Property.ShortText({
@@ -87,11 +99,10 @@ export const createProject = createAction({
required: false,
}),
},
+ outputSchema: togglOutputSchemas.project,
async run(context) {
const {
- workspace_id,
name,
- client_id,
is_private,
billable,
template,
@@ -105,37 +116,75 @@ export const createProject = createAction({
start_date,
end_date,
} = context.propsValue;
- const apiToken = context.auth;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const clientId = togglApi.optionalId({
+ value: context.propsValue.client_id,
+ label: 'Client',
+ });
- const body = {
- name,
- is_private,
- billable,
- template,
- active,
- auto_estimates,
- ...(client_id && { client_id }),
- ...(external_reference && { external_reference }),
- ...(color && { color }),
- ...(estimated_hours && { estimated_hours }),
- ...(rate && { rate }),
- ...(fixed_fee && { fixed_fee }),
- ...(start_date && { start_date }),
- ...(end_date && { end_date }),
- };
+ if (togglApi.isTwo(auth)) {
+ const currency = isNil(fixed_fee)
+ ? undefined
+ : (
+ await togglApi.request<{ currency: string }>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/workspaces/${workspaceId}/currency`,
+ })
+ ).currency;
+ const created = await togglApi.request<TwoProject>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: togglApi.twoWorkspacePath({
+ auth,
+ workspaceId,
+ path: '/projects',
+ }),
+ body: {
+ name,
+ private: is_private,
+ billable,
+ is_template: template,
+ auto_compute_estimates: auto_estimates,
+ ...(isNil(clientId) ? {} : { client_id: clientId }),
+ ...(color ? { color } : {}),
+ ...(isNil(estimated_hours)
+ ? {}
+ : { estimated_mins: Math.round(estimated_hours * 60) }),
+ ...(isNil(fixed_fee) || isNil(currency)
+ ? {}
+ : { fixed_fee: { amount: fixed_fee, currency } }),
+ ...(start_date ? { start_date } : {}),
+ ...(end_date ? { end_date } : {}),
+ },
+ });
+ return togglModels.project(created);
+ }
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/projects`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(`${apiToken}:api_token`).toString(
- 'base64'
- )}`,
+ return togglApi.request<Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: `/workspaces/${workspaceId}/projects`,
+ body: {
+ name,
+ is_private,
+ billable,
+ template,
+ active,
+ auto_estimates,
+ ...(isNil(clientId) ? {} : { client_id: clientId }),
+ ...(external_reference ? { external_reference } : {}),
+ ...(color ? { color } : {}),
+ ...(isNil(estimated_hours) ? {} : { estimated_hours }),
+ ...(isNil(rate) ? {} : { rate }),
+ ...(isNil(fixed_fee) ? {} : { fixed_fee }),
+ ...(start_date ? { start_date } : {}),
+ ...(end_date ? { end_date } : {}),
},
- body,
});
-
- return response.body;
},
});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/create-tag.ts b/packages/pieces/community/toggl-track/src/lib/actions/create-tag.ts
index bac6701cafb..ff44f7c93b1 100644
--- a/packages/pieces/community/toggl-track/src/lib/actions/create-tag.ts
+++ b/packages/pieces/community/toggl-track/src/lib/actions/create-tag.ts
@@ -1,7 +1,9 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import { togglTrackAuth } from '../auth';
import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoTag } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
export const createTag = createAction({
auth: togglTrackAuth,
@@ -10,7 +12,11 @@ export const createTag = createAction({
displayName: 'Create Tag',
description: 'Create a new tag in the workspace.',
audience: 'both',
- aiMetadata: { description: 'Creates a new tag in a Toggl Track workspace, given a workspace ID and tag name. Use when an agent needs a label to later attach to time entries. Not idempotent: each call creates a new tag even if the name already exists.', idempotent: false },
+ aiMetadata: {
+ description:
+ 'Creates a tag in a workspace. Needs the workspace and a name. Returns the new tag. A retry creates a duplicate.',
+ idempotent: false,
+ },
props: {
workspace_id: togglCommon.workspace_id,
name: Property.ShortText({
@@ -19,24 +25,33 @@ export const createTag = createAction({
required: true,
}),
},
+ outputSchema: togglOutputSchemas.tag,
async run(context) {
- const { workspace_id, name } = context.propsValue;
- const apiToken = context.auth;
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/tags`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(`${apiToken}:api_token`).toString(
- 'base64'
- )}`,
- },
- body: {
- name,
- },
+ const { name } = context.propsValue;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
});
- return response.body;
+ if (togglApi.isTwo(auth)) {
+ const created = await togglApi.request<TwoTag>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: `/workspaces/${workspaceId}/tags`,
+ body: { name },
+ });
+ return togglModels.tag(created);
+ }
+
+ const created = await togglApi.request<
+ Record<string, unknown> | Record<string, unknown>[]
+ >({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: `/workspaces/${workspaceId}/tags`,
+ body: { name },
+ });
+ return Array.isArray(created) ? created[0] ?? null : created;
},
-});
\ No newline at end of file
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/create-task.ts b/packages/pieces/community/toggl-track/src/lib/actions/create-task.ts
index 366beedd360..638efacf5a1 100644
--- a/packages/pieces/community/toggl-track/src/lib/actions/create-task.ts
+++ b/packages/pieces/community/toggl-track/src/lib/actions/create-task.ts
@@ -1,7 +1,13 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import {
+ createAction,
+ isNil,
+ Property,
+} from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoTask } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
export const createTask = createAction({
auth: togglTrackAuth,
@@ -10,7 +16,11 @@ export const createTask = createAction({
displayName: 'Create Task',
description: 'Create a new task under a project.',
audience: 'both',
- aiMetadata: { description: 'Creates a new task under a specific project in a Toggl Track workspace, given workspace ID, project ID, and task name. Use when an agent needs a sub-item of a project to track time against. Not idempotent: each call creates a new task even if one with the same name exists.', idempotent: false },
+ aiMetadata: {
+ description:
+ 'Creates a task under a project. Needs the workspace, project, and a name; external reference and the Active flag are Classic only. Returns the new task. A retry creates a duplicate.',
+ idempotent: false,
+ },
props: {
workspace_id: togglCommon.workspace_id,
project_id: togglCommon.project_id,
@@ -21,57 +31,76 @@ export const createTask = createAction({
}),
estimated_seconds: Property.Number({
displayName: 'Estimated Seconds',
- description: 'The estimated time for the task in seconds.',
+ description:
+ 'Estimated time in seconds. Toggl 2.0 stores whole minutes.',
required: false,
}),
external_reference: Property.ShortText({
displayName: 'External Reference',
description:
- 'External reference to link this task with external systems.',
+ 'External system reference. Toggl Track (Classic) only.',
required: false,
}),
active: Property.Checkbox({
displayName: 'Active',
- description: 'Whether the task is active. Use false to mark as done.',
+ description:
+ 'Uncheck to mark the task done. Toggl Track (Classic) only.',
required: false,
defaultValue: true,
}),
user_id: Property.Number({
displayName: 'Creator User ID',
- description: 'Creator ID, if omitted, will use requester user ID.',
+ description:
+ 'Creator user ID, defaults to yours. Toggl 2.0 assigns them the task.',
required: false,
}),
},
+ outputSchema: togglOutputSchemas.task,
async run(context) {
- const {
- workspace_id,
- project_id,
- name,
- estimated_seconds,
- external_reference,
- active,
- user_id,
- } = context.propsValue;
- const apiToken = context.auth;
+ const { name, estimated_seconds, external_reference, active } =
+ context.propsValue;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const projectId = togglApi.requireId({
+ value: context.propsValue.project_id,
+ label: 'Project',
+ });
+ const userId = togglApi.optionalId({
+ value: context.propsValue.user_id,
+ label: 'Creator User ID',
+ });
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/projects/${project_id}/tasks`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(`${apiToken}:api_token`).toString(
- 'base64'
- )}`,
- },
+ if (togglApi.isTwo(auth)) {
+ const created = await togglApi.request<TwoTask>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: togglApi.twoWorkspacePath({ auth, workspaceId, path: '/tasks' }),
+ body: {
+ name,
+ project_id: projectId,
+ ...(isNil(estimated_seconds)
+ ? {}
+ : { estimated_mins: Math.round(estimated_seconds / 60) }),
+ ...(isNil(userId) ? {} : { assignee_user_ids: [userId] }),
+ },
+ });
+ return togglModels.task(created);
+ }
+
+ return togglApi.request<Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: `/workspaces/${workspaceId}/projects/${projectId}/tasks`,
body: {
name,
active,
- ...(estimated_seconds && { estimated_seconds }),
- ...(external_reference && { external_reference }),
- ...(user_id && { user_id }),
+ ...(isNil(estimated_seconds) ? {} : { estimated_seconds }),
+ ...(external_reference ? { external_reference } : {}),
+ ...(isNil(userId) ? {} : { user_id: userId }),
},
});
-
- return response.body;
},
});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/create-time-entry.ts b/packages/pieces/community/toggl-track/src/lib/actions/create-time-entry.ts
index 7caeeb860e9..df1cf9c0f69 100644
--- a/packages/pieces/community/toggl-track/src/lib/actions/create-time-entry.ts
+++ b/packages/pieces/community/toggl-track/src/lib/actions/create-time-entry.ts
@@ -1,7 +1,14 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import {
+ createAction,
+ isNil,
+ Property,
+} from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoTimeEntry } from '../common/models';
+import { togglTimeEntries } from '../common/time-entries';
+import { togglOutputSchemas } from '../output-schemas';
export const createTimeEntry = createAction({
auth: togglTrackAuth,
@@ -9,8 +16,12 @@ export const createTimeEntry = createAction({
classification: 'WRITE',
displayName: 'Create Time Entry',
description: 'Create a new time entry in a workspace.',
- audience: 'both',
- aiMetadata: { description: 'Creates a time entry in a Toggl Track workspace with a start time and duration in seconds; can record a completed entry (positive duration or explicit stop) or start a running timer (pass a negative duration such as -1). Optionally links project, task, tags, and billable flag. Use to log work after the fact or begin tracking. Not idempotent: each call creates a new entry.', idempotent: false },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Creates a time entry with a start time and a duration in seconds (a negative duration with no stop starts a running timer). Returns the created entry. A retry creates a duplicate.',
+ idempotent: false,
+ },
props: {
workspace_id: togglCommon.workspace_id,
description: Property.LongText({
@@ -50,45 +61,97 @@ export const createTimeEntry = createAction({
required: false,
}),
},
+ outputSchema: togglOutputSchemas.timeEntry,
async run(context) {
- const {
- workspace_id,
- description,
- start,
- duration,
- stop,
- project_id,
- task_id,
- tags,
- billable,
- user_id,
- } = context.propsValue;
- const apiToken = context.auth;
+ const { description, start, duration, stop, tags, billable } =
+ context.propsValue;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const projectId = togglApi.optionalId({
+ value: context.propsValue.project_id,
+ label: 'Project',
+ });
+ const taskId = togglApi.optionalId({
+ value: context.propsValue.task_id,
+ label: 'Task',
+ });
+ const userId = togglApi.optionalId({
+ value: context.propsValue.user_id,
+ label: 'Creator User ID',
+ });
+ const startIso = togglApi.toIsoDateTime({ value: start, label: 'Start Time' });
+ const stopIso = stop
+ ? togglApi.toIsoDateTime({ value: stop, label: 'Stop Time' })
+ : undefined;
+ if (stopIso && new Date(stopIso).getTime() < new Date(startIso).getTime()) {
+ throw new Error('Stop Time must be after Start Time.');
+ }
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/time_entries`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(`${apiToken}:api_token`).toString(
- 'base64'
- )}`,
- },
+ if (togglApi.isTwo(auth)) {
+ if (duration < 0 && !stopIso) {
+ return togglTimeEntries.twoStart({
+ auth,
+ workspaceId,
+ start: startIso,
+ description,
+ projectId,
+ taskId,
+ tags,
+ billable,
+ });
+ }
+ const seconds = stopIso
+ ? Math.round(
+ (new Date(stopIso).getTime() - new Date(startIso).getTime()) / 1000
+ )
+ : Math.round(duration);
+ const tagIds = await togglApi.resolveTwoTagIds({
+ auth,
+ workspaceId,
+ names: tags,
+ });
+ const created = await togglApi.request<TwoTimeEntry>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: togglApi.twoWorkspacePath({
+ auth,
+ workspaceId,
+ path: isNil(taskId) ? '/time-entries' : `/tasks/${taskId}/time-entries`,
+ }),
+ body: {
+ type: 'activity',
+ start: startIso,
+ duration: seconds,
+ ...(description ? { description } : {}),
+ ...(isNil(projectId) ? {} : { project_id: projectId }),
+ ...(isNil(tagIds) ? {} : { tag_ids: tagIds }),
+ ...(isNil(billable) ? {} : { billable }),
+ ...(isNil(userId) ? {} : { user_id: userId }),
+ },
+ });
+ return togglModels.timeEntry({ item: created, running: false });
+ }
+
+ return togglApi.request<Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: `/workspaces/${workspaceId}/time_entries`,
body: {
- workspace_id: Number(workspace_id),
+ workspace_id: workspaceId,
description,
- start: new Date(start).toISOString(),
+ start: startIso,
duration,
created_with: 'Activepieces',
billable,
- ...(stop && { stop: new Date(stop).toISOString() }),
- ...(project_id && { project_id }),
- ...(task_id && { task_id }),
- ...(tags && { tags }),
- ...(user_id && { user_id }),
+ ...(stopIso ? { stop: stopIso } : {}),
+ ...(projectId ? { project_id: projectId } : {}),
+ ...(taskId ? { task_id: taskId } : {}),
+ ...(tags ? { tags } : {}),
+ ...(userId ? { user_id: userId } : {}),
},
});
-
- return response.body;
},
});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/delete-client.ts b/packages/pieces/community/toggl-track/src/lib/actions/delete-client.ts
new file mode 100644
index 00000000000..5b98aed86e1
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/delete-client.ts
@@ -0,0 +1,44 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const deleteClient = createAction({
+ auth: togglTrackAuth,
+ name: 'delete_client',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Client',
+ description: 'Permanently delete a client from a workspace.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a client by ID. Returns { success, id }; a second call fails because it is already gone. Cannot be undone.',
+ idempotent: false,
+ },
+ props: {
+ workspace_id: togglCommon.workspace_id,
+ client_id: togglCommon.required_client_id,
+ },
+ outputSchema: togglOutputSchemas.deleted,
+ async run(context) {
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const clientId = togglApi.requireId({
+ value: context.propsValue.client_id,
+ label: 'Client',
+ });
+ await togglApi.withNotFound({
+ label: `Client ${clientId}`,
+ run: () =>
+ togglApi.request<unknown>({
+ auth: context.auth,
+ method: togglApi.HttpMethod.DELETE,
+ path: `/workspaces/${workspaceId}/clients/${clientId}`,
+ }),
+ });
+ return { success: true, id: clientId };
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/delete-group.ts b/packages/pieces/community/toggl-track/src/lib/actions/delete-group.ts
new file mode 100644
index 00000000000..5bbe63a03a4
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/delete-group.ts
@@ -0,0 +1,59 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const deleteGroup = createAction({
+ auth: togglTrackAuth,
+ name: 'delete_group',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Group',
+ description: 'Delete a group (team) from an organization.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a group by ID; members stay in the organization. Returns { success, id }; a second call fails because it is already gone. Cannot be undone.',
+ idempotent: false,
+ },
+ props: {
+ organization_id: togglCommon.organization_id,
+ workspace_id: togglCommon.workspace_id,
+ group_id: Property.ShortText({
+ displayName: 'Group ID',
+ description: 'The ID of the group to delete (group_id from Create Group).',
+ required: true,
+ }),
+ },
+ outputSchema: togglOutputSchemas.deleted,
+ async run(context) {
+ const auth = context.auth;
+ const groupId = togglApi.requireId({
+ value: context.propsValue.group_id,
+ label: 'Group ID',
+ });
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const organizationId = togglApi.isTwo(auth)
+ ? togglApi.twoOrganizationId(auth)
+ : togglApi.requireId({
+ value: context.propsValue.organization_id,
+ label: 'Organization',
+ });
+ await togglApi.withNotFound({
+ label: `Group ${groupId}`,
+ run: () =>
+ togglApi.request<unknown>({
+ auth,
+ method: togglApi.HttpMethod.DELETE,
+ path: `/organizations/${organizationId}/groups/${groupId}`,
+ queryParams: togglApi.isTwo(auth)
+ ? { workspace_id: String(workspaceId) }
+ : undefined,
+ }),
+ });
+ return { success: true, id: groupId };
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/delete-tag.ts b/packages/pieces/community/toggl-track/src/lib/actions/delete-tag.ts
new file mode 100644
index 00000000000..2d97f7df333
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/delete-tag.ts
@@ -0,0 +1,44 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const deleteTag = createAction({
+ auth: togglTrackAuth,
+ name: 'delete_tag',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Tag',
+ description: 'Permanently delete a tag from a workspace.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a tag by ID and removes it from every time entry. Returns { success, id }; a second call fails because it is already gone. Cannot be undone.',
+ idempotent: false,
+ },
+ props: {
+ workspace_id: togglCommon.workspace_id,
+ tag_id: togglCommon.tag_id,
+ },
+ outputSchema: togglOutputSchemas.deleted,
+ async run(context) {
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const tagId = togglApi.requireId({
+ value: context.propsValue.tag_id,
+ label: 'Tag',
+ });
+ await togglApi.withNotFound({
+ label: `Tag ${tagId}`,
+ run: () =>
+ togglApi.request<unknown>({
+ auth: context.auth,
+ method: togglApi.HttpMethod.DELETE,
+ path: `/workspaces/${workspaceId}/tags/${tagId}`,
+ }),
+ });
+ return { success: true, id: tagId };
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/delete-time-entry.ts b/packages/pieces/community/toggl-track/src/lib/actions/delete-time-entry.ts
new file mode 100644
index 00000000000..5b40ca410a3
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/delete-time-entry.ts
@@ -0,0 +1,55 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const deleteTimeEntry = createAction({
+ auth: togglTrackAuth,
+ name: 'delete_time_entry',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Time Entry',
+ description: 'Delete a time entry.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Deletes a time entry by ID. Returns { success, id }; a second call fails because it is already gone. Cannot be undone from Activepieces.',
+ idempotent: false,
+ },
+ props: {
+ workspace_id: togglCommon.workspace_id,
+ time_entry_id: Property.ShortText({
+ displayName: 'Time Entry ID',
+ description: 'The ID of the time entry to delete.',
+ required: true,
+ }),
+ },
+ outputSchema: togglOutputSchemas.deleted,
+ async run(context) {
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const timeEntryId = togglApi.requireId({
+ value: context.propsValue.time_entry_id,
+ label: 'Time Entry ID',
+ });
+ await togglApi.withNotFound({
+ label: `Time entry ${timeEntryId}`,
+ run: () =>
+ togglApi.request<unknown>({
+ auth,
+ method: togglApi.HttpMethod.DELETE,
+ path: togglApi.isTwo(auth)
+ ? togglApi.twoWorkspacePath({
+ auth,
+ workspaceId,
+ path: `/time-entries/${timeEntryId}`,
+ })
+ : `/workspaces/${workspaceId}/time_entries/${timeEntryId}`,
+ }),
+ });
+ return { success: true, id: timeEntryId };
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/find-client.ts b/packages/pieces/community/toggl-track/src/lib/actions/find-client.ts
index f52bc0153d4..096f9745ebf 100644
--- a/packages/pieces/community/toggl-track/src/lib/actions/find-client.ts
+++ b/packages/pieces/community/toggl-track/src/lib/actions/find-client.ts
@@ -1,7 +1,10 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient, QueryParams } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import { QueryParams } from '@activepieces/pieces-common';
+import { togglTrackAuth } from '../auth';
import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoClient } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
export const findClient = createAction({
auth: togglTrackAuth,
@@ -10,51 +13,72 @@ export const findClient = createAction({
displayName: 'Find Client',
description: 'Find a client by name or status in a workspace.',
audience: 'both',
- aiMetadata: { description: 'Lists clients in a Toggl Track workspace, optionally filtered by a case-insensitive name and by active/archived/both status; omitting both returns all clients. Use to resolve a client ID before linking it to a project. Read-only and idempotent.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Lists clients in a workspace, optionally filtered by name and active/archived status. Returns an array of clients. Read-only.',
+ idempotent: true,
+ },
props: {
workspace_id: togglCommon.workspace_id,
name: Property.ShortText({
- displayName: 'Client Name',
- description: 'The name of the client to find (case-insensitive).',
- required: false,
+ displayName: 'Client Name',
+ description: 'The name of the client to find (case-insensitive).',
+ required: false,
}),
status: Property.StaticDropdown({
- displayName: 'Status',
- description: 'Filter clients by their status.',
- required: false,
- options: {
- options: [
- { label: 'Active', value: 'active' },
- { label: 'Archived', value: 'archived' },
- { label: 'Both', value: 'both' },
- ]
- }
- })
+ displayName: 'Status',
+ description: 'Filter clients by their status.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Active', value: 'active' },
+ { label: 'Archived', value: 'archived' },
+ { label: 'Both', value: 'both' },
+ ],
+ },
+ }),
},
+ outputSchema: togglOutputSchemas.clientList,
async run(context) {
- const { workspace_id, name, status } = context.propsValue;
- const apiToken = context.auth;
+ const { name, status } = context.propsValue;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+
+ if (togglApi.isTwo(auth)) {
+ const clients = await togglApi.listTwoPages<TwoClient>({
+ auth,
+ path: `/workspaces/${workspaceId}/clients`,
+ queryParams: name ? { name } : {},
+ });
+ const search = name?.trim().toLowerCase();
+ return clients
+ .filter((client) =>
+ search ? client.name.toLowerCase().includes(search) : true
+ )
+ .filter((client) => {
+ if (status === 'active') return client.active;
+ if (status === 'archived') return !client.active;
+ return true;
+ })
+ .map(togglModels.client);
+ }
const queryParams: QueryParams = {};
if (name) {
- queryParams['name'] = name;
+ queryParams['name'] = name;
}
if (status) {
- queryParams['status'] = status;
+ queryParams['status'] = status;
}
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/clients`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(`${apiToken}:api_token`).toString(
- 'base64'
- )}`,
- },
- queryParams: queryParams
+ const clients = await togglApi.request<Record<string, unknown>[] | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/workspaces/${workspaceId}/clients`,
+ queryParams,
});
-
- return response.body;
+ return clients ?? [];
},
-});
\ No newline at end of file
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/find-project.ts b/packages/pieces/community/toggl-track/src/lib/actions/find-project.ts
index 381f3718e2d..f981f3a86b3 100644
--- a/packages/pieces/community/toggl-track/src/lib/actions/find-project.ts
+++ b/packages/pieces/community/toggl-track/src/lib/actions/find-project.ts
@@ -1,7 +1,10 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import { QueryParams } from '@activepieces/pieces-common';
+import { togglTrackAuth } from '../auth';
import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoProject } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
export const findProject = createAction({
auth: togglTrackAuth,
@@ -10,7 +13,11 @@ export const findProject = createAction({
displayName: 'Find Project',
description: 'Find a project in a workspace by its name.',
audience: 'both',
- aiMetadata: { description: 'Lists projects in a Toggl Track workspace, optionally filtered by name, active/inactive/both status, billable, ownership, or template flag; omitting the name returns all matching projects. Use to resolve a project ID before creating tasks or time entries against it. Read-only and idempotent.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Lists projects in a workspace, optionally filtered by name, status, billable, ownership, or template flag. On Toggl 2.0 "inactive" means archived. Returns an array of projects. Read-only.',
+ idempotent: true,
+ },
props: {
workspace_id: togglCommon.workspace_id,
name: Property.ShortText({
@@ -56,26 +63,46 @@ export const findProject = createAction({
}),
per_page: Property.Number({
displayName: 'Items Per Page',
- description: 'Number of items per page (max 200).',
+ description: 'Number of items per page (max 200; Toggl 2.0: max 100).',
required: false,
}),
},
+ outputSchema: togglOutputSchemas.projectList,
async run(context) {
- const {
- workspace_id,
- name,
- active,
- billable,
- only_me,
- only_templates,
- page,
- per_page,
- } = context.propsValue;
- const apiToken = context.auth;
+ const { name, active, billable, only_me, only_templates, page, per_page } =
+ context.propsValue;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+
+ if (togglApi.isTwo(auth)) {
+ const queryParams: QueryParams = {};
+ if (name) queryParams['name'] = name;
+ if (active === 'true') queryParams['archived'] = 'false';
+ if (active === 'false') queryParams['archived'] = 'true';
+ if (only_me) queryParams['only_me'] = 'true';
+ const projects = await togglApi.listTwoPageOrAll<TwoProject>({
+ auth,
+ path: togglApi.twoWorkspacePath({
+ auth,
+ workspaceId,
+ path: '/projects',
+ }),
+ queryParams,
+ page: page ?? undefined,
+ perPage: per_page ?? undefined,
+ });
+ return projects
+ .filter((project) => (billable ? project.billable : true))
+ .filter((project) => (only_templates ? project.is_template : true))
+ .map(togglModels.project);
+ }
- const queryParams: Record<string, string> = {};
+ const queryParams: QueryParams = {};
if (name) queryParams['name'] = name;
- if (active !== undefined) queryParams['active'] = active;
+ if (active !== undefined && active !== null) queryParams['active'] = active;
if (billable !== undefined) queryParams['billable'] = billable.toString();
if (only_me !== undefined) queryParams['only_me'] = only_me.toString();
if (only_templates !== undefined)
@@ -83,18 +110,12 @@ export const findProject = createAction({
if (page) queryParams['page'] = page.toString();
if (per_page) queryParams['per_page'] = per_page.toString();
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/projects`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(`${apiToken}:api_token`).toString(
- 'base64'
- )}`,
- },
+ const projects = await togglApi.request<Record<string, unknown>[] | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/workspaces/${workspaceId}/projects`,
queryParams,
});
-
- return response.body;
+ return projects ?? [];
},
});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/find-tag.ts b/packages/pieces/community/toggl-track/src/lib/actions/find-tag.ts
index fbeebf33ab1..f9fceaccfb7 100644
--- a/packages/pieces/community/toggl-track/src/lib/actions/find-tag.ts
+++ b/packages/pieces/community/toggl-track/src/lib/actions/find-tag.ts
@@ -1,11 +1,10 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import {
- HttpMethod,
- httpClient,
- QueryParams,
-} from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import { QueryParams } from '@activepieces/pieces-common';
+import { togglTrackAuth } from '../auth';
import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoTag } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
export const findTag = createAction({
auth: togglTrackAuth,
@@ -14,7 +13,11 @@ export const findTag = createAction({
displayName: 'Find Tag',
description: 'Find a tag by name in a workspace.',
audience: 'both',
- aiMetadata: { description: 'Lists tags in a Toggl Track workspace, optionally filtered by a name search with pagination; omitting the search returns all tags. Use to resolve a tag before attaching it to a time entry, or to check whether a tag already exists. Read-only and idempotent.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Lists tags in a workspace, optionally filtered by name. Returns an array of tags. Read-only.',
+ idempotent: true,
+ },
props: {
workspace_id: togglCommon.workspace_id,
search: Property.ShortText({
@@ -29,31 +32,40 @@ export const findTag = createAction({
}),
per_page: Property.Number({
displayName: 'Items Per Page',
- description: 'Number of items per page.',
+ description: 'Number of items per page (Toggl 2.0: max 100).',
required: false,
}),
},
+ outputSchema: togglOutputSchemas.tagList,
async run(context) {
- const { workspace_id, search, page, per_page } = context.propsValue;
- const apiToken = context.auth;
+ const { search, page, per_page } = context.propsValue;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+
+ if (togglApi.isTwo(auth)) {
+ const tags = await togglApi.listTwoPageOrAll<TwoTag>({
+ auth,
+ path: `/workspaces/${workspaceId}/tags`,
+ queryParams: search ? { name: search } : {},
+ page: page ?? undefined,
+ perPage: per_page ?? undefined,
+ });
+ return tags.map(togglModels.tag);
+ }
const queryParams: QueryParams = {};
if (search) queryParams['search'] = search;
if (page) queryParams['page'] = page.toString();
if (per_page) queryParams['per_page'] = per_page.toString();
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/tags`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(`${apiToken}:api_token`).toString(
- 'base64'
- )}`,
- },
- queryParams: queryParams,
+ const tags = await togglApi.request<Record<string, unknown>[] | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/workspaces/${workspaceId}/tags`,
+ queryParams,
});
-
- return response.body;
+ return tags ?? [];
},
});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/find-task.ts b/packages/pieces/community/toggl-track/src/lib/actions/find-task.ts
index af0d8d767ae..442710d59c1 100644
--- a/packages/pieces/community/toggl-track/src/lib/actions/find-task.ts
+++ b/packages/pieces/community/toggl-track/src/lib/actions/find-task.ts
@@ -1,11 +1,14 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
import {
- HttpMethod,
- httpClient,
- QueryParams,
-} from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+ createAction,
+ isNil,
+ Property,
+} from '@activepieces/pieces-framework';
+import { QueryParams } from '@activepieces/pieces-common';
+import { togglTrackAuth } from '../auth';
import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoTask } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
export const findTask = createAction({
auth: togglTrackAuth,
@@ -14,7 +17,11 @@ export const findTask = createAction({
displayName: 'Find Task',
description: 'Find a task by name and status.',
audience: 'both',
- aiMetadata: { description: 'Lists tasks in a Toggl Track workspace, optionally filtered by name, project ID, active/inactive/both status, and date range, with sorting and pagination; omitting filters returns all tasks. Use to resolve a task ID before logging time against it. Read-only and idempotent.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Lists tasks in a workspace, optionally filtered by name, project, status, and date range. Returns { total_count, page, per_page, data }. Read-only.',
+ idempotent: true,
+ },
props: {
workspace_id: togglCommon.workspace_id,
search: Property.ShortText({
@@ -85,9 +92,9 @@ export const findTask = createAction({
required: false,
}),
},
+ outputSchema: togglOutputSchemas.taskList,
async run(context) {
const {
- workspace_id,
search,
project_id,
active,
@@ -98,11 +105,47 @@ export const findTask = createAction({
start_date,
end_date,
} = context.propsValue;
- const apiToken = context.auth;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const projectId = togglApi.optionalId({
+ value: project_id,
+ label: 'Project ID',
+ });
+
+ if (togglApi.isTwo(auth)) {
+ const queryParams: QueryParams = {};
+ if (search) queryParams['name'] = search;
+ if (!isNil(projectId)) queryParams['project_id'] = String(projectId);
+ if (active === 'true') queryParams['archived'] = 'false';
+ if (active === 'false') queryParams['archived'] = 'true';
+ if (sort_field) {
+ queryParams['order_by'] = `${sort_order === 'DESC' ? '-' : ''}${sort_field}`;
+ }
+ if (start_date) queryParams['start_date'] = start_date;
+ if (end_date) queryParams['end_date'] = end_date;
+ const tasks = await togglApi.listTwoPageOrAll<TwoTask>({
+ auth,
+ path: togglApi.twoWorkspacePath({ auth, workspaceId, path: '/tasks' }),
+ queryParams,
+ page: page ?? undefined,
+ perPage: per_page ?? undefined,
+ });
+ return {
+ total_count: tasks.length,
+ page: page ?? 1,
+ per_page: isNil(page) ? tasks.length : Math.min(per_page ?? 100, 100),
+ sort_field: sort_field ?? null,
+ sort_order: sort_order ?? null,
+ data: tasks.map(togglModels.task),
+ };
+ }
const queryParams: QueryParams = {};
if (search) queryParams['search'] = search;
- if (project_id) queryParams['pid'] = project_id.toString();
+ if (!isNil(projectId)) queryParams['pid'] = String(projectId);
if (active) queryParams['active'] = active;
if (page) queryParams['page'] = page.toString();
if (per_page) queryParams['per_page'] = per_page.toString();
@@ -111,18 +154,15 @@ export const findTask = createAction({
if (start_date) queryParams['start_date'] = start_date;
if (end_date) queryParams['end_date'] = end_date;
- const response = await httpClient.sendRequest<{ data: unknown[] }>({
- method: HttpMethod.GET,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/tasks`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(`${apiToken}:api_token`).toString(
- 'base64'
- )}`,
- },
- queryParams: queryParams,
+ const response = await togglApi.request<{
+ data: unknown[] | null;
+ [key: string]: unknown;
+ }>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/workspaces/${workspaceId}/tasks`,
+ queryParams,
});
-
- return response.body;
+ return { ...response, data: response?.data ?? [] };
},
});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/find-time-entry.ts b/packages/pieces/community/toggl-track/src/lib/actions/find-time-entry.ts
index bbde957c885..7207879650f 100644
--- a/packages/pieces/community/toggl-track/src/lib/actions/find-time-entry.ts
+++ b/packages/pieces/community/toggl-track/src/lib/actions/find-time-entry.ts
@@ -1,10 +1,14 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
import {
- HttpMethod,
- httpClient,
- QueryParams,
-} from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+ createAction,
+ isNil,
+ Property,
+} from '@activepieces/pieces-framework';
+import { QueryParams } from '@activepieces/pieces-common';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoTimeEntry } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
export const findTimeEntry = createAction({
auth: togglTrackAuth,
@@ -13,8 +17,13 @@ export const findTimeEntry = createAction({
displayName: 'Find Time Entry',
description: 'Find time entries by description.',
audience: 'both',
- aiMetadata: { description: 'Retrieves the current user\'s time entries, optionally bounded by date range or modified-since timestamp; when a description text is provided it filters client-side to entries whose description contains that text (case-insensitive), otherwise all entries in range are returned. Use to locate existing entries before reporting or updating. Read-only and idempotent.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Lists the current user\'s time entries, optionally bounded by dates and filtered by description text. Agents: use Time Summary (Agent) for totals. On Toggl 2.0 the last 9 days are searched when no dates are given. Read-only.',
+ idempotent: true,
+ },
props: {
+ workspace_id: togglCommon.optional_workspace_id,
description: Property.ShortText({
displayName: 'Description Contains',
description:
@@ -40,22 +49,26 @@ export const findTimeEntry = createAction({
}),
since: Property.Number({
displayName: 'Since Timestamp',
- description: 'Get entries modified since this UNIX timestamp.',
+ description:
+ 'Entries modified since this UNIX timestamp (range start on Toggl 2.0).',
required: false,
}),
meta: Property.Checkbox({
displayName: 'Include Meta Data',
- description: 'Should the response contain data for meta entities.',
+ description:
+ 'Include meta entity data. Toggl Track (Classic) only.',
required: false,
defaultValue: false,
}),
include_sharing: Property.Checkbox({
displayName: 'Include Sharing',
- description: 'Include sharing details in the response.',
+ description:
+ 'Include sharing details in the response. Toggl Track (Classic) only.',
required: false,
defaultValue: false,
}),
},
+ outputSchema: togglOutputSchemas.timeEntryList,
async run(context) {
const {
description,
@@ -66,42 +79,91 @@ export const findTimeEntry = createAction({
meta,
include_sharing,
} = context.propsValue;
- const apiToken = context.auth;
+ const auth = context.auth;
+ const workspaceId = togglApi.optionalId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const search = description?.trim().toLowerCase();
+ const matches = (entryDescription: string | null | undefined) =>
+ search ? (entryDescription ?? '').toLowerCase().includes(search) : true;
+
+ if (togglApi.isTwo(auth)) {
+ const targetWorkspaceId =
+ workspaceId ?? (await togglApi.twoSettings(auth)).current_workspace_id;
+ const rangeEnd = end_date ?? before;
+ const dateTo = rangeEnd
+ ? togglApi.toIsoDateTime({
+ value: rangeEnd,
+ label: end_date ? 'End Date' : 'Before Date',
+ })
+ : new Date().toISOString();
+ const dateFrom = twoRangeStart({ start_date, since });
+ const [userAccountId, entries] = await Promise.all([
+ togglApi.twoCurrentUserAccountId(auth),
+ togglApi.listTwoPages<TwoTimeEntry>({
+ auth,
+ path: togglApi.twoWorkspacePath({
+ auth,
+ workspaceId: targetWorkspaceId,
+ path: '/time-entries',
+ }),
+ queryParams: {
+ date_from: dateFrom,
+ date_to: dateTo,
+ include_taskless: 'true',
+ },
+ }),
+ ]);
+ return entries
+ .filter(togglModels.isTracked)
+ .filter((entry) =>
+ isNil(userAccountId) ? true : entry.toggl_user_id === userAccountId
+ )
+ .filter((entry) => matches(entry.description))
+ .map((entry) => togglModels.timeEntry({ item: entry, running: false }));
+ }
const queryParams: QueryParams = {};
if (start_date) queryParams['start_date'] = start_date;
if (end_date) queryParams['end_date'] = end_date;
if (before) queryParams['before'] = before;
- if (since) queryParams['since'] = since.toString();
- if (meta !== undefined) queryParams['meta'] = meta.toString();
- if (include_sharing !== undefined)
+ if (!isNil(since)) queryParams['since'] = since.toString();
+ if (!isNil(meta)) queryParams['meta'] = meta.toString();
+ if (!isNil(include_sharing))
queryParams['include_sharing'] = include_sharing.toString();
- const response = await httpClient.sendRequest<{
- items: { id: number; description: string; [key: string]: unknown }[];
- }>({
- method: HttpMethod.GET,
- url: `https://api.track.toggl.com/api/v9/me/time_entries`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(`${apiToken}:api_token`).toString(
- 'base64'
- )}`,
- },
- queryParams: queryParams,
+ const response = await togglApi.request<
+ { id: number; workspace_id?: number; description: string | null }[] | null
+ >({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: '/me/time_entries',
+ queryParams,
});
-
- const timeEntries = response.body.items || [];
-
- if (description) {
- const matchingEntries = timeEntries.filter(
- (entry) =>
- entry.description &&
- entry.description.toLowerCase().includes(description.toLowerCase())
- );
- return { items: matchingEntries };
- }
-
- return response.body;
+ const timeEntries = Array.isArray(response) ? response : [];
+ return timeEntries
+ .filter((entry) =>
+ isNil(workspaceId) ? true : entry.workspace_id === workspaceId
+ )
+ .filter((entry) => matches(entry.description));
},
});
+
+const DEFAULT_TWO_RANGE_MS = 9 * 24 * 60 * 60 * 1000;
+
+function twoRangeStart({
+ start_date,
+ since,
+}: {
+ start_date: string | undefined;
+ since: number | undefined;
+}): string {
+ if (start_date) {
+ return togglApi.toIsoDateTime({ value: start_date, label: 'Start Date' });
+ }
+ if (!isNil(since)) {
+ return new Date(since * 1000).toISOString();
+ }
+ return new Date(Date.now() - DEFAULT_TWO_RANGE_MS).toISOString();
+}
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/find-user.ts b/packages/pieces/community/toggl-track/src/lib/actions/find-user.ts
index 930017811d4..02ad3de388a 100644
--- a/packages/pieces/community/toggl-track/src/lib/actions/find-user.ts
+++ b/packages/pieces/community/toggl-track/src/lib/actions/find-user.ts
@@ -1,7 +1,10 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import { QueryParams } from '@activepieces/pieces-common';
+import { togglTrackAuth } from '../auth';
import { togglCommon } from '../common';
+import { togglApi, TwoOrganizationUser } from '../common/client';
+import { togglModels } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
export const findUser = createAction({
auth: togglTrackAuth,
@@ -10,7 +13,11 @@ export const findUser = createAction({
displayName: 'Find User',
description: 'Find a user in a workspace by their name or email.',
audience: 'both',
- aiMetadata: { description: 'Looks up workspace members in a Toggl Track workspace, given organization ID and workspace ID; an empty search term returns all members, while a name or email filters to matches. Use to resolve a user before assigning work or attributing time. Read-only and idempotent.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Lists the members of a workspace, optionally filtered by name or email. Returns an array with id, user_id, name, email, and active. Read-only.',
+ idempotent: true,
+ },
props: {
workspace_id: togglCommon.workspace_id,
organization_id: togglCommon.organization_id,
@@ -36,35 +43,50 @@ export const findUser = createAction({
required: false,
}),
},
+ outputSchema: togglOutputSchemas.userList,
async run(context) {
- const {
- workspace_id,
- organization_id,
- search_term,
- active,
- page,
- per_page,
- } = context.propsValue;
- const apiToken = context.auth;
+ const { search_term, active, page, per_page } = context.propsValue;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+
+ if (togglApi.isTwo(auth)) {
+ const queryParams: QueryParams = { workspaces: String(workspaceId) };
+ if (search_term) queryParams['filter'] = search_term;
+ const users = await togglApi.listTwoPageOrAll<TwoOrganizationUser>({
+ auth,
+ path: `/organizations/${togglApi.twoOrganizationId(auth)}/users`,
+ queryParams,
+ page: page ?? undefined,
+ perPage: per_page ?? undefined,
+ });
+ return users
+ .filter((user) =>
+ user.workspaces.some((workspace) => workspace.id === workspaceId)
+ )
+ .filter((user) => (active ? user.active : true))
+ .map((user) => togglModels.user({ item: user, workspaceId }));
+ }
- const queryParams: Record<string, string> = {};
+ const organizationId = togglApi.requireId({
+ value: context.propsValue.organization_id,
+ label: 'Organization',
+ });
+ const queryParams: QueryParams = {};
if (search_term) queryParams['search'] = search_term;
- if (active !== undefined) queryParams['active'] = active.toString();
+ if (active !== undefined && active !== null)
+ queryParams['active'] = active.toString();
if (page) queryParams['page'] = page.toString();
if (per_page) queryParams['per_page'] = per_page.toString();
- const searchResponse = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `https://api.track.toggl.com/api/v9/organizations/${organization_id}/workspaces/${workspace_id}/workspace_users`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(`${apiToken}:api_token`).toString(
- 'base64'
- )}`,
- },
+ const users = await togglApi.request<Record<string, unknown>[] | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/organizations/${organizationId}/workspaces/${workspaceId}/workspace_users`,
queryParams,
});
-
- return searchResponse.body;
+ return users ?? [];
},
});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/get-client.ts b/packages/pieces/community/toggl-track/src/lib/actions/get-client.ts
new file mode 100644
index 00000000000..86a1d440496
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/get-client.ts
@@ -0,0 +1,54 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoClient } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const getClient = createAction({
+ auth: togglTrackAuth,
+ name: 'get_client',
+ classification: 'READ',
+ displayName: 'Get Client',
+ description: 'Get a client by its ID.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns one client by ID. Notes and external reference are null on Toggl 2.0. Fails clearly when it does not exist. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ workspace_id: togglCommon.workspace_id,
+ client_id: togglCommon.required_client_id,
+ },
+ outputSchema: togglOutputSchemas.client,
+ async run(context) {
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const clientId = togglApi.requireId({
+ value: context.propsValue.client_id,
+ label: 'Client',
+ });
+ return togglApi.withNotFound({
+ label: `Client ${clientId}`,
+ run: async () => {
+ if (togglApi.isTwo(auth)) {
+ const client = await togglApi.request<TwoClient>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/workspaces/${workspaceId}/clients/${clientId}`,
+ });
+ return togglModels.client(client);
+ }
+ return togglApi.request<Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/workspaces/${workspaceId}/clients/${clientId}`,
+ });
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/get-current-time-entry.ts b/packages/pieces/community/toggl-track/src/lib/actions/get-current-time-entry.ts
new file mode 100644
index 00000000000..be7dcb86018
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/get-current-time-entry.ts
@@ -0,0 +1,57 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglTimeEntries } from '../common/time-entries';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const getCurrentTimeEntry = createAction({
+ auth: togglTrackAuth,
+ name: 'get_current_time_entry',
+ classification: 'READ',
+ displayName: 'Get Current Time Entry',
+ description: 'Get the time entry that is running right now, if any.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns the running time entry with running = true, or { running: false } when no timer runs. On Toggl 2.0 only the given workspace is checked. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ workspace_id: togglCommon.optional_workspace_id,
+ },
+ outputSchema: togglOutputSchemas.currentTimeEntry,
+ async run(context) {
+ const auth = context.auth;
+ const workspaceId = togglApi.optionalId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+
+ if (togglApi.isTwo(auth)) {
+ const targetWorkspaceId =
+ workspaceId ?? (await togglApi.twoSettings(auth)).current_workspace_id;
+ const running = await togglTimeEntries.twoCurrent({
+ auth,
+ workspaceId: targetWorkspaceId,
+ });
+ return running ? { running: true, ...running } : { running: false };
+ }
+
+ const running = await togglApi.request<
+ ({ id: number; workspace_id?: number } & Record<string, unknown>) | null
+ >({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: '/me/time_entries/current',
+ });
+ if (
+ !running ||
+ typeof running.id !== 'number' ||
+ (workspaceId && running.workspace_id !== workspaceId)
+ ) {
+ return { running: false };
+ }
+ return { running: true, ...running };
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/get-project.ts b/packages/pieces/community/toggl-track/src/lib/actions/get-project.ts
new file mode 100644
index 00000000000..d9c6ef66874
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/get-project.ts
@@ -0,0 +1,58 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoProject } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const getProject = createAction({
+ auth: togglTrackAuth,
+ name: 'get_project',
+ classification: 'READ',
+ displayName: 'Get Project',
+ description: 'Get a project by its ID.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns one project by ID with status, flags, estimate, and tracked time. Fails clearly when it does not exist. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ workspace_id: togglCommon.workspace_id,
+ project_id: togglCommon.project_id,
+ },
+ outputSchema: togglOutputSchemas.project,
+ async run(context) {
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const projectId = togglApi.requireId({
+ value: context.propsValue.project_id,
+ label: 'Project',
+ });
+ return togglApi.withNotFound({
+ label: `Project ${projectId}`,
+ run: async () => {
+ if (togglApi.isTwo(auth)) {
+ const project = await togglApi.request<TwoProject>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: togglApi.twoWorkspacePath({
+ auth,
+ workspaceId,
+ path: `/projects/${projectId}`,
+ }),
+ });
+ return togglModels.project(project);
+ }
+ return togglApi.request<Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/workspaces/${workspaceId}/projects/${projectId}`,
+ });
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/get-time-entry.ts b/packages/pieces/community/toggl-track/src/lib/actions/get-time-entry.ts
new file mode 100644
index 00000000000..69869ac53b3
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/get-time-entry.ts
@@ -0,0 +1,74 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoTimeEntry } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const getTimeEntry = createAction({
+ auth: togglTrackAuth,
+ name: 'get_time_entry',
+ classification: 'READ',
+ displayName: 'Get Time Entry',
+ description: 'Get a time entry by its ID.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns one time entry by ID. A running entry has duration -1 and no stop. Fails clearly when it does not exist. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ workspace_id: togglCommon.optional_workspace_id,
+ time_entry_id: Property.ShortText({
+ displayName: 'Time Entry ID',
+ description: 'The ID of the time entry (from Find Time Entry or a trigger).',
+ required: true,
+ }),
+ },
+ outputSchema: togglOutputSchemas.timeEntry,
+ async run(context) {
+ const auth = context.auth;
+ const timeEntryId = togglApi.requireId({
+ value: context.propsValue.time_entry_id,
+ label: 'Time Entry ID',
+ });
+ const workspaceId = togglApi.optionalId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ return togglApi.withNotFound({
+ label: `Time entry ${timeEntryId}`,
+ run: async () => {
+ if (togglApi.isTwo(auth)) {
+ const targetWorkspaceId =
+ workspaceId ??
+ (await togglApi.twoSettings(auth)).current_workspace_id;
+ const entry = await togglApi.request<TwoTimeEntry>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: togglApi.twoWorkspacePath({
+ auth,
+ workspaceId: targetWorkspaceId,
+ path: `/time-entries/${timeEntryId}`,
+ }),
+ });
+ return togglModels.timeEntry({ item: entry, running: false });
+ }
+ const entry = await togglApi.request<{ workspace_id?: number } & Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/me/time_entries/${timeEntryId}`,
+ });
+ if (!entry) {
+ throw new Error(`Time entry ${timeEntryId} was not found.`);
+ }
+ if (workspaceId && entry.workspace_id !== workspaceId) {
+ throw new Error(
+ `Time entry ${timeEntryId} belongs to another workspace.`
+ );
+ }
+ return entry;
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/get-workspace.ts b/packages/pieces/community/toggl-track/src/lib/actions/get-workspace.ts
new file mode 100644
index 00000000000..781c27baec0
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/get-workspace.ts
@@ -0,0 +1,59 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const getWorkspace = createAction({
+ auth: togglTrackAuth,
+ name: 'get_workspace',
+ classification: 'READ',
+ displayName: 'Get Workspace',
+ description: 'Get the details of a workspace.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns one workspace by ID. On Toggl 2.0 only id, name, organization ID, and currency are filled. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ workspace_id: togglCommon.workspace_id,
+ },
+ outputSchema: togglOutputSchemas.workspace,
+ async run(context) {
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ return togglApi.withNotFound({
+ label: `Workspace ${workspaceId}`,
+ run: async () => {
+ if (togglApi.isTwo(auth)) {
+ const [workspaces, currency] = await Promise.all([
+ togglApi.twoWorkspaces(auth),
+ togglApi.request<{ currency?: string } | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/workspaces/${workspaceId}/currency`,
+ }),
+ ]);
+ const match = workspaces.find((workspace) => workspace.id === workspaceId);
+ return togglModels.twoWorkspace({
+ id: workspaceId,
+ name: match?.name ?? null,
+ organizationId: togglApi.twoOrganizationId(auth),
+ currency: currency?.currency ?? null,
+ });
+ }
+ const workspace = await togglApi.request<Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/workspaces/${workspaceId}`,
+ });
+ return togglModels.classicWorkspace(workspace);
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/invite-user.ts b/packages/pieces/community/toggl-track/src/lib/actions/invite-user.ts
new file mode 100644
index 00000000000..0931b67974b
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/invite-user.ts
@@ -0,0 +1,71 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const inviteUser = createAction({
+ auth: togglTrackAuth,
+ name: 'invite_user',
+ classification: 'WRITE',
+ displayName: 'Invite User to Organization',
+ description: 'Invite someone by email to an organization and workspace.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Sends a Toggl invitation email to one address for the given workspace. Classic only. Returns the created invitations and messages. A retry can send another email.',
+ idempotent: false,
+ },
+ props: {
+ organization_id: togglCommon.organization_id,
+ workspace_id: togglCommon.workspace_id,
+ email: Property.ShortText({
+ displayName: 'Email',
+ description: 'The email address to invite.',
+ required: true,
+ }),
+ admin: Property.Checkbox({
+ displayName: 'Workspace Admin',
+ description: 'Make the invited user an admin of the workspace.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: togglOutputSchemas.invitation,
+ async run(context) {
+ const auth = context.auth;
+ if (togglApi.isTwo(auth)) {
+ throw togglApi.classicOnlyError('Invite User to Organization');
+ }
+ const email = context.propsValue.email.trim();
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
+ throw new Error('Email must be a valid email address.');
+ }
+ const organizationId = togglApi.requireId({
+ value: context.propsValue.organization_id,
+ label: 'Organization',
+ });
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const result = await togglApi.request<{
+ invitations?: unknown[] | null;
+ messages?: unknown[] | null;
+ } | null>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: `/organizations/${organizationId}/invitations`,
+ body: {
+ emails: [email],
+ workspaces: [
+ { workspace_id: workspaceId, admin: context.propsValue.admin ?? false },
+ ],
+ },
+ });
+ return {
+ invitations: result?.invitations ?? [],
+ messages: result?.messages ?? [],
+ };
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/list-organization-users.ts b/packages/pieces/community/toggl-track/src/lib/actions/list-organization-users.ts
new file mode 100644
index 00000000000..ae16fbe469e
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/list-organization-users.ts
@@ -0,0 +1,112 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { QueryParams } from '@activepieces/pieces-common';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi, TwoOrganizationUser } from '../common/client';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const listOrganizationUsers = createAction({
+ auth: togglTrackAuth,
+ name: 'list_organization_users',
+ classification: 'SEARCH',
+ displayName: 'List Organization Users',
+ description: 'List the members of an organization.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists every member of the organization across its workspaces, optionally filtered by name or email. Use Find User for a single workspace. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ organization_id: togglCommon.organization_id,
+ search: Property.ShortText({
+ displayName: 'Name or Email',
+ description: 'Only members whose name or email contains this text.',
+ required: false,
+ }),
+ },
+ outputSchema: togglOutputSchemas.organizationUserList,
+ async run(context) {
+ const auth = context.auth;
+ const search = context.propsValue.search?.trim();
+ const filters: QueryParams = search ? { filter: search } : {};
+
+ if (togglApi.isTwo(auth)) {
+ const users = await togglApi.listTwoPages<TwoOrganizationUser>({
+ auth,
+ path: `/organizations/${togglApi.twoOrganizationId(auth)}/users`,
+ queryParams: filters,
+ });
+ return users.map((user) => ({
+ id: user.id,
+ user_id: user.user_account_id,
+ name: user.name,
+ email: user.email,
+ admin: null,
+ owner: user.owner ?? null,
+ inactive: !user.active,
+ joined: user.joined ?? null,
+ workspace_ids: user.workspaces.map((workspace) => workspace.id),
+ }));
+ }
+
+ const organizationId = togglApi.requireId({
+ value: context.propsValue.organization_id,
+ label: 'Organization',
+ });
+ const users = await listClassicPages({
+ auth,
+ path: `/organizations/${organizationId}/users`,
+ filters,
+ page: 1,
+ });
+ return users.map((user) => ({
+ ...user,
+ workspace_ids: (user.workspaces ?? []).map(
+ (workspace) => workspace.workspace_id
+ ),
+ }));
+ },
+});
+
+async function listClassicPages({
+ auth,
+ path,
+ filters,
+ page,
+}: {
+ auth: Parameters<typeof togglApi.request>[0]['auth'];
+ path: string;
+ filters: QueryParams;
+ page: number;
+}): Promise<ClassicOrgUser[]> {
+ if (page > MAX_PAGES) {
+ throw new Error(
+ `The organization has more than ${PAGE_SIZE * MAX_PAGES} members. Use the Name or Email filter.`
+ );
+ }
+ const users =
+ (await togglApi.request<ClassicOrgUser[] | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path,
+ queryParams: {
+ ...filters,
+ page: String(page),
+ per_page: String(PAGE_SIZE),
+ },
+ })) ?? [];
+ if (users.length < PAGE_SIZE) {
+ return users;
+ }
+ const rest = await listClassicPages({ auth, path, filters, page: page + 1 });
+ return [...users, ...rest];
+}
+
+const PAGE_SIZE = 200;
+const MAX_PAGES = 50;
+
+type ClassicOrgUser = {
+ workspaces?: { workspace_id: number }[] | null;
+ [key: string]: unknown;
+};
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/list-workspaces.ts b/packages/pieces/community/toggl-track/src/lib/actions/list-workspaces.ts
new file mode 100644
index 00000000000..fe0655a58f9
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/list-workspaces.ts
@@ -0,0 +1,42 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglApi } from '../common/client';
+import { togglModels } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const listWorkspaces = createAction({
+ auth: togglTrackAuth,
+ name: 'list_workspaces',
+ classification: 'SEARCH',
+ displayName: 'List Workspaces',
+ description: 'List the workspaces you belong to.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists the workspaces the connection can reach (id, name, organization ID). On Toggl 2.0 the other fields are null. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: togglOutputSchemas.workspaceList,
+ async run(context) {
+ const auth = context.auth;
+ if (togglApi.isTwo(auth)) {
+ const workspaces = await togglApi.twoWorkspaces(auth);
+ const organizationId = togglApi.twoOrganizationId(auth);
+ return workspaces.map((workspace) =>
+ togglModels.twoWorkspace({
+ id: workspace.id,
+ name: workspace.name,
+ organizationId,
+ currency: null,
+ })
+ );
+ }
+ const workspaces = await togglApi.request<Record<string, unknown>[] | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: '/me/workspaces',
+ });
+ return (workspaces ?? []).map(togglModels.classicWorkspace);
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/log-time-ai.ts b/packages/pieces/community/toggl-track/src/lib/actions/log-time-ai.ts
new file mode 100644
index 00000000000..cd8f36f7dbd
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/log-time-ai.ts
@@ -0,0 +1,92 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglAgent } from '../common/agent';
+import { togglApi } from '../common/client';
+import { togglModels, TwoTimeEntry } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const logTimeAi = createAction({
+ auth: togglTrackAuth,
+ name: 'log_time_ai',
+ classification: 'WRITE',
+ displayName: 'Log Time (Agent)',
+ description: 'Logs a completed time entry using a project name.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Logs a completed time entry. Agents: use this instead of Create Time Entry. Needs a description, a start ("now" or an ISO datetime) and a duration in minutes; the project is optional, by name or ID (ambiguous or unknown names fail with the candidates listed). Returns the created entry. Each call creates a new entry, so a retry makes a duplicate.',
+ idempotent: false,
+ },
+ props: {
+ description: Property.ShortText({
+ displayName: 'Description',
+ description: 'What the time was spent on.',
+ required: true,
+ }),
+ project: Property.ShortText({
+ displayName: 'Project',
+ description: 'Project name or ID. Leave empty for no project.',
+ required: false,
+ }),
+ start: Property.ShortText({
+ displayName: 'Start',
+ description: 'Start time: an ISO datetime, or "now".',
+ required: true,
+ }),
+ duration_minutes: Property.Number({
+ displayName: 'Duration (minutes)',
+ description: 'How long the work took, in minutes.',
+ required: true,
+ }),
+ },
+ outputSchema: togglOutputSchemas.timeEntry,
+ async run(context) {
+ const auth = context.auth;
+ const description = context.propsValue.description.trim();
+ if (!description) {
+ throw new Error('Description is required.');
+ }
+ const start = togglAgent.parseStart({ value: context.propsValue.start });
+ const seconds = togglAgent.durationSeconds({
+ minutes: context.propsValue.duration_minutes,
+ });
+ const { workspaceId, projectId } = await togglAgent.resolveTarget({
+ auth,
+ projectReference: context.propsValue.project,
+ });
+
+ if (togglApi.isTwo(auth)) {
+ const created = await togglApi.request<TwoTimeEntry>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: togglApi.twoWorkspacePath({
+ auth,
+ workspaceId,
+ path: '/time-entries',
+ }),
+ body: {
+ type: 'activity',
+ description,
+ start,
+ duration: seconds,
+ ...(projectId ? { project_id: projectId } : {}),
+ },
+ });
+ return togglModels.timeEntry({ item: created, running: false });
+ }
+
+ return togglApi.request<Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: `/workspaces/${workspaceId}/time_entries`,
+ body: {
+ workspace_id: workspaceId,
+ description,
+ start,
+ duration: seconds,
+ created_with: 'Activepieces',
+ ...(projectId ? { project_id: projectId } : {}),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/search-detailed-report.ts b/packages/pieces/community/toggl-track/src/lib/actions/search-detailed-report.ts
new file mode 100644
index 00000000000..f345d0110ff
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/search-detailed-report.ts
@@ -0,0 +1,241 @@
+import {
+ createAction,
+ isNil,
+ Property,
+} from '@activepieces/pieces-framework';
+import { QueryParams } from '@activepieces/pieces-common';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoTimeEntry } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const searchDetailedReport = createAction({
+ auth: togglTrackAuth,
+ name: 'search_detailed_report',
+ classification: 'SEARCH',
+ displayName: 'Search Detailed Report',
+ description:
+ 'Search all time entries of a workspace in a date range (detailed report).',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns one page of all members\' time entries between two dates, with project, user, client, and description filters (the client filter is Classic only). Agents: use Time Summary (Agent) for totals. Returns { rows, next_cursor, has_more }; pass next_cursor back for the next page. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ workspace_id: togglCommon.workspace_id,
+ start_date: Property.ShortText({
+ displayName: 'Start Date',
+ description: 'First day of the report (YYYY-MM-DD).',
+ required: true,
+ }),
+ end_date: Property.ShortText({
+ displayName: 'End Date',
+ description:
+ 'Last day of the report (YYYY-MM-DD, inclusive). Leave empty for today.',
+ required: false,
+ }),
+ project_ids: Property.ShortText({
+ displayName: 'Project IDs',
+ description: 'Comma-separated project IDs to include.',
+ required: false,
+ }),
+ user_ids: Property.ShortText({
+ displayName: 'User IDs',
+ description: 'Comma-separated user IDs to include.',
+ required: false,
+ }),
+ client_ids: Property.ShortText({
+ displayName: 'Client IDs',
+ description:
+ 'Comma-separated client IDs to include. Toggl Track (Classic) only.',
+ required: false,
+ }),
+ description: Property.ShortText({
+ displayName: 'Description Contains',
+ description: 'Only entries whose description contains this text.',
+ required: false,
+ }),
+ page_size: Property.Number({
+ displayName: 'Page Size',
+ description: 'Rows per page (default 50, max 100 on Toggl 2.0).',
+ required: false,
+ }),
+ cursor: Property.ShortText({
+ displayName: 'Next Page Cursor',
+ description:
+ 'Pass next_cursor from the last result; empty for the first page.',
+ required: false,
+ }),
+ },
+ outputSchema: togglOutputSchemas.detailedReport,
+ async run(context) {
+ const { description, cursor } = context.propsValue;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const startDate = requireDate({
+ value: context.propsValue.start_date,
+ label: 'Start Date',
+ });
+ const endDate = context.propsValue.end_date
+ ? requireDate({ value: context.propsValue.end_date, label: 'End Date' })
+ : new Date().toISOString().slice(0, 10);
+ if (endDate < startDate) {
+ throw new Error('End Date must not be before Start Date.');
+ }
+ const projectIds = parseIdList({
+ value: context.propsValue.project_ids,
+ label: 'Project IDs',
+ });
+ const userIds = parseIdList({
+ value: context.propsValue.user_ids,
+ label: 'User IDs',
+ });
+ const clientIds = parseIdList({
+ value: context.propsValue.client_ids,
+ label: 'Client IDs',
+ });
+ const pageSize = Math.min(
+ Math.max(Math.floor(context.propsValue.page_size ?? 50), 1),
+ togglApi.isTwo(auth) ? 100 : 1000
+ );
+
+ if (togglApi.isTwo(auth)) {
+ if (clientIds.length > 0) {
+ throw togglApi.classicOnlyError('Filtering the report by client');
+ }
+ const page = cursor ? Number(cursor) : 1;
+ if (!Number.isSafeInteger(page) || page < 1) {
+ throw new Error('Next Page Cursor is not valid for Toggl 2.0.');
+ }
+ const queryParams: QueryParams = {
+ date_from: new Date(`${startDate}T00:00:00Z`).toISOString(),
+ date_to: new Date(`${endDate}T23:59:59Z`).toISOString(),
+ include_taskless: 'true',
+ page: String(page),
+ per_page: String(pageSize),
+ ...(projectIds.length === 1 ? { project_id: String(projectIds[0]) } : {}),
+ };
+ const response = await togglApi.request<{ data: TwoTimeEntry[] | null }>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: togglApi.twoWorkspacePath({
+ auth,
+ workspaceId,
+ path: '/time-entries',
+ }),
+ queryParams,
+ });
+ const entries = response?.data ?? [];
+ const search = description?.trim().toLowerCase();
+ const rows = entries
+ .filter(togglModels.isTracked)
+ .filter((entry) =>
+ projectIds.length > 1
+ ? !isNil(entry.project_id) && projectIds.includes(entry.project_id)
+ : true
+ )
+ .filter((entry) =>
+ userIds.length > 0 ? userIds.includes(entry.toggl_user_id) : true
+ )
+ .filter((entry) =>
+ search
+ ? (entry.description ?? '').toLowerCase().includes(search)
+ : true
+ )
+ .map(togglModels.reportRow);
+ const hasMore = entries.length === pageSize;
+ return {
+ rows,
+ next_cursor: hasMore ? String(page + 1) : null,
+ has_more: hasMore,
+ };
+ }
+
+ const position = parseClassicCursor(cursor);
+ const { body, headers } = await togglApi.classicReportsRequest<
+ Record<string, unknown>[] | null
+ >({
+ auth,
+ workspaceId,
+ body: {
+ start_date: startDate,
+ end_date: endDate,
+ page_size: pageSize,
+ enrich_response: true,
+ order_by: 'date',
+ order_dir: 'ASC',
+ ...(projectIds.length > 0 ? { project_ids: projectIds } : {}),
+ ...(userIds.length > 0 ? { user_ids: userIds } : {}),
+ ...(clientIds.length > 0 ? { client_ids: clientIds } : {}),
+ ...(description ? { description } : {}),
+ ...position,
+ },
+ });
+ const nextCursor = classicNextCursor(headers);
+ return {
+ rows: body ?? [],
+ next_cursor: nextCursor,
+ has_more: !isNil(nextCursor),
+ };
+ },
+});
+
+function requireDate({
+ value,
+ label,
+}: {
+ value: string;
+ label: string;
+}): string {
+ const trimmed = value.trim();
+ if (
+ !/^\d{4}-\d{2}-\d{2}$/.test(trimmed) ||
+ Number.isNaN(new Date(`${trimmed}T00:00:00Z`).getTime())
+ ) {
+ throw new Error(`${label} must use the YYYY-MM-DD format.`);
+ }
+ return trimmed;
+}
+
+function parseIdList({
+ value,
+ label,
+}: {
+ value: string | undefined;
+ label: string;
+}): number[] {
+ if (!value || value.trim() === '') {
+ return [];
+ }
+ return value
+ .split(',')
+ .map((part) => part.trim())
+ .filter((part) => part.length > 0)
+ .map((part) => togglApi.requireId({ value: part, label }));
+}
+
+function parseClassicCursor(
+ cursor: string | undefined
+): Record<string, number> {
+ if (!cursor) {
+ return {};
+ }
+ const id = Number(cursor.split(':')[0]);
+ if (!Number.isSafeInteger(id) || id <= 0) {
+ throw new Error('Next Page Cursor is not valid for Toggl Track (Classic).');
+ }
+ return { first_id: id };
+}
+
+function classicNextCursor(headers: Record<string, unknown>): string | null {
+ const entry = Object.entries(headers).find(
+ ([key]) => key.toLowerCase() === 'x-next-id'
+ );
+ const value = Array.isArray(entry?.[1]) ? entry?.[1][0] : entry?.[1];
+ return typeof value === 'string' && value !== '' ? value : null;
+}
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/start-time-entry.ts b/packages/pieces/community/toggl-track/src/lib/actions/start-time-entry.ts
index e5bfcddd2ad..092980f5dbd 100644
--- a/packages/pieces/community/toggl-track/src/lib/actions/start-time-entry.ts
+++ b/packages/pieces/community/toggl-track/src/lib/actions/start-time-entry.ts
@@ -1,7 +1,9 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import { togglTrackAuth } from '../auth';
import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglTimeEntries } from '../common/time-entries';
+import { togglOutputSchemas } from '../output-schemas';
export const startTimeEntry = createAction({
auth: togglTrackAuth,
@@ -9,8 +11,12 @@ export const startTimeEntry = createAction({
classification: 'WRITE',
displayName: 'Start Time Entry',
description: 'Start a new time entry (live timer).',
- audience: 'both',
- aiMetadata: { description: 'Starts a live running timer in a Toggl Track workspace, beginning now with an open-ended duration; optionally links project, task, tags, and billable flag. Use to begin tracking time in real time (use Stop Time Entry to end it); prefer Create Time Entry to log a completed entry with an explicit start/stop. Not idempotent: each call starts a new running entry.', idempotent: false },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Starts a running timer now, optionally linked to a project, task, and tags. Returns the running entry; end it with Stop Time Entry. A retry starts another timer (on Toggl 2.0 it also stops the previous one).',
+ idempotent: false,
+ },
props: {
workspace_id: togglCommon.workspace_id,
description: Property.LongText({
@@ -27,33 +33,52 @@ export const startTimeEntry = createAction({
}),
task_id: togglCommon.optional_task_id,
},
+ outputSchema: togglOutputSchemas.timeEntry,
async run(context) {
- const { workspace_id, description, project_id, tags, billable, task_id } =
- context.propsValue;
- const apiToken = context.auth;
+ const { description, tags, billable } = context.propsValue;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const projectId = togglApi.optionalId({
+ value: context.propsValue.project_id,
+ label: 'Project',
+ });
+ const taskId = togglApi.optionalId({
+ value: context.propsValue.task_id,
+ label: 'Task',
+ });
+ const start = new Date().toISOString();
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/time_entries`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(`${apiToken}:api_token`).toString(
- 'base64'
- )}`,
- },
+ if (togglApi.isTwo(auth)) {
+ return togglTimeEntries.twoStart({
+ auth,
+ workspaceId,
+ start,
+ description,
+ projectId,
+ taskId,
+ tags,
+ billable,
+ });
+ }
+
+ return togglApi.request<Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: `/workspaces/${workspaceId}/time_entries`,
body: {
- workspace_id: Number(workspace_id),
+ workspace_id: workspaceId,
description,
- start: new Date().toISOString(),
+ start,
duration: -1,
created_with: 'Activepieces',
billable,
- ...(project_id && { project_id }),
- ...(task_id && { task_id }),
- ...(tags && { tags }),
+ ...(projectId ? { project_id: projectId } : {}),
+ ...(taskId ? { task_id: taskId } : {}),
+ ...(tags ? { tags } : {}),
},
});
-
- return response.body;
},
});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/start-timer-ai.ts b/packages/pieces/community/toggl-track/src/lib/actions/start-timer-ai.ts
new file mode 100644
index 00000000000..d56d5844600
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/start-timer-ai.ts
@@ -0,0 +1,72 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglAgent } from '../common/agent';
+import { togglApi } from '../common/client';
+import { togglTimeEntries } from '../common/time-entries';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const startTimerAi = createAction({
+ auth: togglTrackAuth,
+ name: 'start_timer_ai',
+ classification: 'WRITE',
+ displayName: 'Start Timer (Agent)',
+ description: 'Starts a running timer using a project name.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Starts a running timer now. Agents: use this instead of Start Time Entry, and Log Time (Agent) when the work is already done. Needs a description; the project is optional, by name or ID (ambiguous or unknown names fail with the candidates listed). Returns the running entry; stop it with Stop Time Entry. Each call starts a new timer (on Toggl 2.0 it also stops the previous one).',
+ idempotent: false,
+ },
+ props: {
+ description: Property.ShortText({
+ displayName: 'Description',
+ description: 'What the timer is for.',
+ required: true,
+ }),
+ project: Property.ShortText({
+ displayName: 'Project',
+ description: 'Project name or ID. Leave empty for no project.',
+ required: false,
+ }),
+ },
+ outputSchema: togglOutputSchemas.timeEntry,
+ async run(context) {
+ const auth = context.auth;
+ const description = context.propsValue.description.trim();
+ if (!description) {
+ throw new Error('Description is required.');
+ }
+ const { workspaceId, projectId } = await togglAgent.resolveTarget({
+ auth,
+ projectReference: context.propsValue.project,
+ });
+ const start = new Date().toISOString();
+
+ if (togglApi.isTwo(auth)) {
+ return togglTimeEntries.twoStart({
+ auth,
+ workspaceId,
+ start,
+ description,
+ projectId,
+ taskId: undefined,
+ tags: undefined,
+ billable: undefined,
+ });
+ }
+
+ return togglApi.request<Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: `/workspaces/${workspaceId}/time_entries`,
+ body: {
+ workspace_id: workspaceId,
+ description,
+ start,
+ duration: -1,
+ created_with: 'Activepieces',
+ ...(projectId ? { project_id: projectId } : {}),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/stop-time-entry.ts b/packages/pieces/community/toggl-track/src/lib/actions/stop-time-entry.ts
index 33169536c66..c8f94861ad9 100644
--- a/packages/pieces/community/toggl-track/src/lib/actions/stop-time-entry.ts
+++ b/packages/pieces/community/toggl-track/src/lib/actions/stop-time-entry.ts
@@ -1,7 +1,9 @@
import { createAction } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient, HttpError } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import { togglTrackAuth } from '../auth';
import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglTimeEntries } from '../common/time-entries';
+import { togglOutputSchemas } from '../output-schemas';
export const stopTimeEntry = createAction({
auth: togglTrackAuth,
@@ -10,48 +12,56 @@ export const stopTimeEntry = createAction({
displayName: 'Stop Time Entry',
description: 'Stops the currently running time entry.',
audience: 'both',
- aiMetadata: { description: 'Looks up the current user\'s running time entry and stops it, setting its stop time in the given workspace. Use to end an active timer started by Start Time Entry. Returns a no-op message if no entry is running; effectively idempotent once stopped, but treated as a state-mutating call.', idempotent: false },
+ aiMetadata: {
+ description:
+ 'Stops the current user\'s running time entry and returns the stopped entry, or { success: false, message } when nothing is running. On Toggl 2.0 only the given workspace is checked. Safe to retry once stopped.',
+ idempotent: false,
+ },
props: {
workspace_id: togglCommon.workspace_id,
},
+ outputSchema: togglOutputSchemas.stoppedTimeEntry,
async run(context) {
- const { workspace_id } = context.propsValue;
- const apiToken = context.auth;
- let runningEntryId: number;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
- try {
- const runningEntryResponse = await httpClient.sendRequest<{ id: number }>({
- method: HttpMethod.GET,
- url: `https://api.track.toggl.com/api/v9/me/time_entries/current`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(`${apiToken}:api_token`).toString(
- 'base64'
- )}`,
- },
- });
- runningEntryId = runningEntryResponse.body.id;
- } catch (e) {
-
- if (e instanceof HttpError && e.response.status === 404) {
- return { success: false, message: "No time entry is currently running." };
+ if (togglApi.isTwo(auth)) {
+ const running = await togglTimeEntries.twoCurrent({ auth, workspaceId });
+ if (!running) {
+ return NOT_RUNNING;
}
-
- throw e;
+ return togglTimeEntries.twoStop({ auth, workspaceId });
}
-
- const stopResponse = await httpClient.sendRequest({
- method: HttpMethod.PATCH,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/time_entries/${runningEntryId}/stop`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(`${apiToken}:api_token`).toString(
- 'base64'
- )}`,
- },
+ const running = await togglApi.request<{
+ id: number;
+ workspace_id?: number;
+ } | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: '/me/time_entries/current',
+ }).catch((error: unknown) => {
+ if (togglApi.httpStatusOf(error) === 404) {
+ return null;
+ }
+ throw error;
});
+ if (!running || typeof running.id !== 'number') {
+ return NOT_RUNNING;
+ }
- return stopResponse.body;
+ return togglApi.request<Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.PATCH,
+ path: `/workspaces/${running.workspace_id ?? workspaceId}/time_entries/${running.id}/stop`,
+ });
},
-});
\ No newline at end of file
+});
+
+const NOT_RUNNING = {
+ success: false,
+ message: 'No time entry is currently running.',
+};
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/time-summary-ai.ts b/packages/pieces/community/toggl-track/src/lib/actions/time-summary-ai.ts
new file mode 100644
index 00000000000..4ca1ffdb100
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/time-summary-ai.ts
@@ -0,0 +1,232 @@
+import {
+ createAction,
+ isNil,
+ Property,
+} from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { SummaryEntry, togglAgent } from '../common/agent';
+import { togglApi, TwoOrganizationUser } from '../common/client';
+import { togglModels, TwoProject, TwoTimeEntry } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const timeSummaryAi = createAction({
+ auth: togglTrackAuth,
+ name: 'time_summary_ai',
+ classification: 'SEARCH',
+ displayName: 'Time Summary (Agent)',
+ description: 'Sums tracked time in a date range, grouped by project, user, or client.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Sums the tracked time of a workspace between two dates (YYYY-MM-DD, inclusive), grouped by "project" (default), "user", or "client". Agents: use this for totals instead of paging through Search Detailed Report or Find Time Entry. An optional project name or ID narrows the summary to that project. Returns { total_hours, total_seconds, groups: [{ name, id, hours, seconds, entry_count }] }. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ start_date: Property.ShortText({
+ displayName: 'Start Date',
+ description: 'First day of the range (YYYY-MM-DD).',
+ required: true,
+ }),
+ end_date: Property.ShortText({
+ displayName: 'End Date',
+ description: 'Last day of the range (YYYY-MM-DD, inclusive). Leave empty for today.',
+ required: false,
+ }),
+ group_by: Property.ShortText({
+ displayName: 'Group By',
+ description: '"project" (default), "user", or "client".',
+ required: false,
+ }),
+ project: Property.ShortText({
+ displayName: 'Project',
+ description: 'Project name or ID. Leave empty for all projects.',
+ required: false,
+ }),
+ },
+ outputSchema: togglOutputSchemas.timeSummary,
+ async run(context) {
+ const auth = context.auth;
+ const startDate = requireDate({
+ value: context.propsValue.start_date,
+ label: 'Start Date',
+ });
+ const endDate = context.propsValue.end_date?.trim()
+ ? requireDate({ value: context.propsValue.end_date, label: 'End Date' })
+ : new Date().toISOString().slice(0, 10);
+ if (endDate < startDate) {
+ throw new Error('End Date must not be before Start Date.');
+ }
+ const groupBy = togglAgent.parseGroupBy(context.propsValue.group_by);
+ const { workspaceId, projectId } = await togglAgent.resolveTarget({
+ auth,
+ projectReference: context.propsValue.project,
+ includeArchived: true,
+ });
+
+ const entries = togglApi.isTwo(auth)
+ ? await twoEntries({ auth, workspaceId, projectId, startDate, endDate, groupBy })
+ : await classicEntries({ auth, workspaceId, projectId, startDate, endDate });
+
+ const summary = togglAgent.summarize({ entries, groupBy });
+ return {
+ start_date: startDate,
+ end_date: endDate,
+ group_by: groupBy,
+ ...summary,
+ };
+ },
+});
+
+async function classicEntries({
+ auth,
+ workspaceId,
+ projectId,
+ startDate,
+ endDate,
+}: {
+ auth: Parameters<typeof togglApi.request>[0]['auth'];
+ workspaceId: number;
+ projectId: number | undefined;
+ startDate: string;
+ endDate: string;
+}): Promise<SummaryEntry[]> {
+ const entries: SummaryEntry[] = [];
+ let firstId: number | undefined = undefined;
+ for (let page = 0; page < MAX_REPORT_PAGES; page += 1) {
+ const { body, headers } = await togglApi.classicReportsRequest<
+ ClassicReportRow[] | null
+ >({
+ auth,
+ workspaceId,
+ body: {
+ start_date: startDate,
+ end_date: endDate,
+ page_size: REPORT_PAGE_SIZE,
+ enrich_response: true,
+ order_by: 'date',
+ order_dir: 'ASC',
+ ...(projectId ? { project_ids: [projectId] } : {}),
+ ...(firstId ? { first_id: firstId } : {}),
+ },
+ });
+ for (const row of body ?? []) {
+ for (const item of row.time_entries ?? []) {
+ entries.push({
+ seconds: item.seconds ?? null,
+ projectId: row.project_id ?? null,
+ projectName: row.project_name ?? null,
+ userId: row.user_id ?? null,
+ userName: row.username ?? null,
+ clientId: null,
+ clientName: row.client_name ?? null,
+ });
+ }
+ }
+ const next = headerValue({ headers, name: 'x-next-id' });
+ if (!next) {
+ return entries;
+ }
+ firstId = Number(next);
+ }
+ throw new Error(
+ `The range has more than ${REPORT_PAGE_SIZE * MAX_REPORT_PAGES} report rows. Use a shorter date range.`
+ );
+}
+
+async function twoEntries({
+ auth,
+ workspaceId,
+ projectId,
+ startDate,
+ endDate,
+ groupBy,
+}: {
+ auth: Parameters<typeof togglApi.request>[0]['auth'];
+ workspaceId: number;
+ projectId: number | undefined;
+ startDate: string;
+ endDate: string;
+ groupBy: 'project' | 'user' | 'client';
+}): Promise<SummaryEntry[]> {
+ if (!togglApi.isTwo(auth)) {
+ return [];
+ }
+ const [rawEntries, projects, users] = await Promise.all([
+ togglApi.listTwoPages<TwoTimeEntry>({
+ auth,
+ path: togglApi.twoWorkspacePath({ auth, workspaceId, path: '/time-entries' }),
+ queryParams: {
+ date_from: new Date(`${startDate}T00:00:00Z`).toISOString(),
+ date_to: new Date(`${endDate}T23:59:59Z`).toISOString(),
+ include_taskless: 'true',
+ ...(projectId ? { project_id: String(projectId) } : {}),
+ },
+ }),
+ togglApi.listTwoPages<TwoProject>({
+ auth,
+ path: togglApi.twoWorkspacePath({ auth, workspaceId, path: '/projects' }),
+ }),
+ groupBy === 'user'
+ ? togglApi.listTwoPages<TwoOrganizationUser>({
+ auth,
+ path: `/organizations/${togglApi.twoOrganizationId(auth)}/users`,
+ })
+ : Promise.resolve<TwoOrganizationUser[]>([]),
+ ]);
+ const projectById = new Map(projects.map((project) => [project.id, project]));
+ const userById = new Map(
+ users.map((user) => [user.user_account_id, user.name])
+ );
+ return rawEntries.filter(togglModels.isTracked).map((entry) => {
+ const project = isNil(entry.project_id)
+ ? undefined
+ : projectById.get(entry.project_id);
+ return {
+ seconds:
+ isNil(entry.duration) || entry.duration < 0 ? null : entry.duration,
+ projectId: entry.project_id ?? null,
+ projectName: project?.name ?? null,
+ userId: entry.toggl_user_id,
+ userName: userById.get(entry.toggl_user_id) ?? null,
+ clientId: project?.client?.id ?? null,
+ clientName: project?.client?.name ?? null,
+ };
+ });
+}
+
+function requireDate({ value, label }: { value: string; label: string }): string {
+ const trimmed = value.trim();
+ if (
+ !/^\d{4}-\d{2}-\d{2}$/.test(trimmed) ||
+ Number.isNaN(new Date(`${trimmed}T00:00:00Z`).getTime())
+ ) {
+ throw new Error(`${label} must use the YYYY-MM-DD format.`);
+ }
+ return trimmed;
+}
+
+function headerValue({
+ headers,
+ name,
+}: {
+ headers: Record<string, unknown>;
+ name: string;
+}): string | null {
+ const entry = Object.entries(headers).find(
+ ([key]) => key.toLowerCase() === name
+ );
+ const value = Array.isArray(entry?.[1]) ? entry?.[1][0] : entry?.[1];
+ return typeof value === 'string' && value !== '' ? value : null;
+}
+
+const REPORT_PAGE_SIZE = 1000;
+const MAX_REPORT_PAGES = 20;
+
+type ClassicReportRow = {
+ user_id?: number | null;
+ username?: string | null;
+ project_id?: number | null;
+ project_name?: string | null;
+ client_name?: string | null;
+ time_entries?: { seconds?: number | null }[] | null;
+};
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/update-client.ts b/packages/pieces/community/toggl-track/src/lib/actions/update-client.ts
new file mode 100644
index 00000000000..ec2a10755b3
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/update-client.ts
@@ -0,0 +1,126 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoClient } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const updateClient = createAction({
+ auth: togglTrackAuth,
+ name: 'update_client',
+ classification: 'WRITE',
+ displayName: 'Update Client',
+ description: 'Update the name, notes, or external reference of a client.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Updates a client by ID; omitted fields keep their value, and Clear Notes empties the notes. Notes and external reference are Classic only. Returns the updated client. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ workspace_id: togglCommon.workspace_id,
+ client_id: togglCommon.required_client_id,
+ name: Property.ShortText({
+ displayName: 'New Name',
+ description: 'Leave empty to keep the current name.',
+ required: false,
+ }),
+ notes: Property.LongText({
+ displayName: 'Notes',
+ description:
+ 'Leave empty to keep the current notes. Toggl Track (Classic) only.',
+ required: false,
+ }),
+ clear_notes: Property.Checkbox({
+ displayName: 'Clear Notes',
+ description: 'Remove the notes. Toggl Track (Classic) only.',
+ required: false,
+ defaultValue: false,
+ }),
+ external_reference: Property.ShortText({
+ displayName: 'External Reference',
+ description:
+ 'Leave empty to keep the current value. Toggl Track (Classic) only.',
+ required: false,
+ }),
+ },
+ outputSchema: togglOutputSchemas.client,
+ async run(context) {
+ const { name, notes, clear_notes, external_reference } =
+ context.propsValue;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const clientId = togglApi.requireId({
+ value: context.propsValue.client_id,
+ label: 'Client',
+ });
+ const path = `/workspaces/${workspaceId}/clients/${clientId}`;
+ const hasNotes = notes !== undefined && notes !== null && notes !== '';
+ if (hasNotes && clear_notes) {
+ throw new Error('Set Notes or Clear Notes, not both.');
+ }
+
+ return togglApi.withNotFound({
+ label: `Client ${clientId}`,
+ run: async () => {
+ if (togglApi.isTwo(auth)) {
+ if (hasNotes || clear_notes || external_reference) {
+ throw togglApi.classicOnlyError(
+ 'Updating client notes or external reference'
+ );
+ }
+ if (!name) {
+ throw new Error('Provide a New Name to update.');
+ }
+ await togglApi.request<unknown>({
+ auth,
+ method: togglApi.HttpMethod.PUT,
+ path,
+ body: { name },
+ });
+ const updated = await togglApi.request<TwoClient>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path,
+ });
+ return togglModels.client(updated);
+ }
+
+ const body = {
+ ...(name ? { name } : {}),
+ ...(hasNotes ? { notes } : {}),
+ ...(clear_notes ? { notes: '' } : {}),
+ ...(external_reference ? { external_reference } : {}),
+ };
+ if (Object.keys(body).length === 0) {
+ throw new Error('Provide at least one field to update.');
+ }
+ const current = await togglApi.request<{
+ name: string;
+ notes?: string | null;
+ external_reference?: string | null;
+ }>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path,
+ });
+ return togglApi.request<Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.PUT,
+ path,
+ body: {
+ name: current.name,
+ ...(current.notes ? { notes: current.notes } : {}),
+ ...(current.external_reference
+ ? { external_reference: current.external_reference }
+ : {}),
+ ...body,
+ },
+ });
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/update-project.ts b/packages/pieces/community/toggl-track/src/lib/actions/update-project.ts
new file mode 100644
index 00000000000..136391b2dd9
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/update-project.ts
@@ -0,0 +1,176 @@
+import {
+ createAction,
+ isNil,
+ Property,
+} from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoProject } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const updateProject = createAction({
+ auth: togglTrackAuth,
+ name: 'update_project',
+ classification: 'WRITE',
+ displayName: 'Update Project',
+ description: 'Update the settings of a project.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Updates a project by ID; omitted fields keep their value, and Active = No archives it. Hourly rate is Classic only. Returns the updated project. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ workspace_id: togglCommon.workspace_id,
+ project_id: togglCommon.project_id,
+ name: Property.ShortText({
+ displayName: 'New Name',
+ description: 'Leave empty to keep the current name.',
+ required: false,
+ }),
+ client_id: togglCommon.client_id,
+ is_private: togglCommon.updateFlag({
+ displayName: 'Private',
+ description: 'Whether the project is private.',
+ }),
+ billable: togglCommon.updateFlag({
+ displayName: 'Billable',
+ description: 'Whether the project is billable. (Premium feature)',
+ }),
+ active: togglCommon.updateFlag({
+ displayName: 'Active',
+ description: 'No archives the project, Yes restores it.',
+ }),
+ color: Property.ShortText({
+ displayName: 'Project Color',
+ description:
+ 'Hex color like #ff0000. Leave empty to keep the current color.',
+ required: false,
+ }),
+ estimated_hours: Property.Number({
+ displayName: 'Estimated Hours',
+ description: 'Leave empty to keep the current estimate. (Premium feature)',
+ required: false,
+ }),
+ rate: Property.Number({
+ displayName: 'Hourly Rate',
+ description:
+ 'Leave empty to keep it. Premium, Toggl Track (Classic) only.',
+ required: false,
+ }),
+ start_date: Property.ShortText({
+ displayName: 'Start Date',
+ description: 'Start date of the project timeframe (YYYY-MM-DD).',
+ required: false,
+ }),
+ end_date: Property.ShortText({
+ displayName: 'End Date',
+ description: 'End date of the project timeframe (YYYY-MM-DD).',
+ required: false,
+ }),
+ },
+ outputSchema: togglOutputSchemas.project,
+ async run(context) {
+ const { name, color, estimated_hours, rate, start_date, end_date } =
+ context.propsValue;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const projectId = togglApi.requireId({
+ value: context.propsValue.project_id,
+ label: 'Project',
+ });
+ const clientId = togglApi.optionalId({
+ value: context.propsValue.client_id,
+ label: 'Client',
+ });
+ const isPrivate = togglCommon.flagValue(context.propsValue.is_private);
+ const billable = togglCommon.flagValue(context.propsValue.billable);
+ const active = togglCommon.flagValue(context.propsValue.active);
+ for (const [label, value] of [
+ ['Start Date', start_date],
+ ['End Date', end_date],
+ ]) {
+ if (value && !/^\d{4}-\d{2}-\d{2}$/.test(value)) {
+ throw new Error(`${label} must use the YYYY-MM-DD format.`);
+ }
+ }
+
+ return togglApi.withNotFound({
+ label: `Project ${projectId}`,
+ run: async () => {
+ if (togglApi.isTwo(auth)) {
+ if (!isNil(rate)) {
+ throw togglApi.classicOnlyError('Updating the project hourly rate');
+ }
+ const projectPath = togglApi.twoWorkspacePath({
+ auth,
+ workspaceId,
+ path: `/projects/${projectId}`,
+ });
+ const body = {
+ ...(name ? { name } : {}),
+ ...(isNil(clientId) ? {} : { client_id: clientId }),
+ ...(isNil(isPrivate) ? {} : { private: isPrivate }),
+ ...(isNil(billable) ? {} : { billable }),
+ ...(color ? { color } : {}),
+ ...(isNil(estimated_hours)
+ ? {}
+ : { estimated_mins: Math.round(estimated_hours * 60) }),
+ ...(start_date ? { start_date } : {}),
+ ...(end_date ? { end_date } : {}),
+ };
+ if (Object.keys(body).length === 0 && isNil(active)) {
+ throw new Error('Provide at least one field to update.');
+ }
+ if (Object.keys(body).length > 0) {
+ await togglApi.request<unknown>({
+ auth,
+ method: togglApi.HttpMethod.PATCH,
+ path: projectPath,
+ body,
+ });
+ }
+ if (!isNil(active)) {
+ await togglApi.request<unknown>({
+ auth,
+ method: togglApi.HttpMethod.PATCH,
+ path: `${projectPath}/${active ? 'unarchive' : 'archive'}`,
+ });
+ }
+ const updated = await togglApi.request<TwoProject>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: projectPath,
+ });
+ return togglModels.project(updated);
+ }
+
+ const body = {
+ ...(name ? { name } : {}),
+ ...(isNil(clientId) ? {} : { client_id: clientId }),
+ ...(isNil(isPrivate) ? {} : { is_private: isPrivate }),
+ ...(isNil(billable) ? {} : { billable }),
+ ...(isNil(active) ? {} : { active }),
+ ...(color ? { color } : {}),
+ ...(isNil(estimated_hours) ? {} : { estimated_hours }),
+ ...(isNil(rate) ? {} : { rate }),
+ ...(start_date ? { start_date } : {}),
+ ...(end_date ? { end_date } : {}),
+ };
+ if (Object.keys(body).length === 0) {
+ throw new Error('Provide at least one field to update.');
+ }
+ return togglApi.request<Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.PUT,
+ path: `/workspaces/${workspaceId}/projects/${projectId}`,
+ body,
+ });
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/update-tag.ts b/packages/pieces/community/toggl-track/src/lib/actions/update-tag.ts
new file mode 100644
index 00000000000..63b23a98a24
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/update-tag.ts
@@ -0,0 +1,72 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoTag } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const updateTag = createAction({
+ auth: togglTrackAuth,
+ name: 'update_tag',
+ classification: 'WRITE',
+ displayName: 'Update Tag',
+ description: 'Rename a tag.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Renames a tag by ID; time entries keep the tag under its new name. Returns the updated tag. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ workspace_id: togglCommon.workspace_id,
+ tag_id: togglCommon.tag_id,
+ name: Property.ShortText({
+ displayName: 'New Name',
+ description: 'The new name of the tag.',
+ required: true,
+ }),
+ },
+ outputSchema: togglOutputSchemas.tag,
+ async run(context) {
+ const { name } = context.propsValue;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const tagId = togglApi.requireId({
+ value: context.propsValue.tag_id,
+ label: 'Tag',
+ });
+ const path = `/workspaces/${workspaceId}/tags/${tagId}`;
+
+ return togglApi.withNotFound({
+ label: `Tag ${tagId}`,
+ run: async () => {
+ if (togglApi.isTwo(auth)) {
+ const current = await togglApi.request<TwoTag>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path,
+ });
+ const updated = await togglApi.request<TwoTag>({
+ auth,
+ method: togglApi.HttpMethod.PUT,
+ path,
+ body: { name, color: current.color ?? null },
+ });
+ return togglModels.tag(updated);
+ }
+ const updated = await togglApi.request<
+ Record<string, unknown> | Record<string, unknown>[]
+ >({
+ auth,
+ method: togglApi.HttpMethod.PUT,
+ path,
+ body: { name },
+ });
+ return Array.isArray(updated) ? updated[0] ?? null : updated;
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/toggl-track/src/lib/actions/update-time-entry.ts b/packages/pieces/community/toggl-track/src/lib/actions/update-time-entry.ts
new file mode 100644
index 00000000000..c43bd5c474c
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/actions/update-time-entry.ts
@@ -0,0 +1,210 @@
+import {
+ createAction,
+ isNil,
+ Property,
+} from '@activepieces/pieces-framework';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglModels, TwoTimeEntry } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
+
+export const updateTimeEntry = createAction({
+ auth: togglTrackAuth,
+ name: 'update_time_entry',
+ classification: 'WRITE',
+ displayName: 'Update Time Entry',
+ description: 'Update a single time entry.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Updates one time entry by ID; omitted fields keep their value, Tags replaces the whole list, Clear Tags removes every tag, and a new stop time wins over duration. Returns the updated entry. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ workspace_id: togglCommon.workspace_id,
+ time_entry_id: Property.ShortText({
+ displayName: 'Time Entry ID',
+ description: 'The ID of the time entry to update.',
+ required: true,
+ }),
+ description: Property.LongText({
+ displayName: 'Description',
+ description: 'Leave empty to keep the current description.',
+ required: false,
+ }),
+ clear_description: Property.Checkbox({
+ displayName: 'Clear Description',
+ description: 'Remove the description.',
+ required: false,
+ defaultValue: false,
+ }),
+ start: Property.DateTime({
+ displayName: 'Start Time',
+ description: 'New start time. Leave empty to keep the current start.',
+ required: false,
+ }),
+ stop: Property.DateTime({
+ displayName: 'Stop Time',
+ description: 'New stop time. Leave empty to keep the current stop.',
+ required: false,
+ }),
+ duration: Property.Number({
+ displayName: 'Duration (in seconds)',
+ description:
+ 'New duration; ignored when Stop Time is given. Empty keeps current.',
+ required: false,
+ }),
+ project_id: togglCommon.optional_project_id,
+ task_id: togglCommon.optional_task_id,
+ tags: togglCommon.tags,
+ clear_tags: Property.Checkbox({
+ displayName: 'Clear Tags',
+ description: 'Remove every tag from the time entry.',
+ required: false,
+ defaultValue: false,
+ }),
+ billable: togglCommon.updateFlag({
+ displayName: 'Billable',
+ description: 'Whether the time entry is billable.',
+ }),
+ },
+ outputSchema: togglOutputSchemas.timeEntry,
+ async run(context) {
+ const {
+ description,
+ clear_description,
+ start,
+ stop,
+ duration,
+ tags,
+ clear_tags,
+ } = context.propsValue;
+ const auth = context.auth;
+ const workspaceId = togglApi.requireId({
+ value: context.propsValue.workspace_id,
+ label: 'Workspace',
+ });
+ const timeEntryId = togglApi.requireId({
+ value: context.propsValue.time_entry_id,
+ label: 'Time Entry ID',
+ });
+ const projectId = togglApi.optionalId({
+ value: context.propsValue.project_id,
+ label: 'Project',
+ });
+ const taskId = togglApi.optionalId({
+ value: context.propsValue.task_id,
+ label: 'Task',
+ });
+ const billable = togglCommon.flagValue(context.propsValue.billable);
+ const startIso = start
+ ? togglApi.toIsoDateTime({ value: start, label: 'Start Time' })
+ : undefined;
+ const stopIso = stop
+ ? togglApi.toIsoDateTime({ value: stop, label: 'Stop Time' })
+ : undefined;
+ if (description && clear_description) {
+ throw new Error('Set Description or Clear Description, not both.');
+ }
+ if (!isNil(duration) && duration < 0) {
+ throw new Error(
+ 'Duration must be zero or more seconds. Use Start Time Entry to start a timer.'
+ );
+ }
+ const newDescription = clear_description ? '' : description || undefined;
+ const tagList = togglCommon.tagListValue({ tags, clearTags: clear_tags });
+
+ return togglApi.withNotFound({
+ label: `Time entry ${timeEntryId}`,
+ run: async () => {
+ if (togglApi.isTwo(auth)) {
+ const entryPath = togglApi.twoWorkspacePath({
+ auth,
+ workspaceId,
+ path: `/time-entries/${timeEntryId}`,
+ });
+ const current = await togglApi.request<TwoTimeEntry>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: entryPath,
+ });
+ const effectiveStart = startIso ?? current.start ?? undefined;
+ const seconds = secondsBetween({ start: effectiveStart, stop: stopIso });
+ const tagIds = await togglApi.resolveTwoTagIds({
+ auth,
+ workspaceId,
+ names: tagList,
+ });
+ const body = {
+ ...(isNil(newDescription) ? {} : { description: newDescription }),
+ ...(startIso ? { start: startIso } : {}),
+ ...(isNil(seconds)
+ ? isNil(duration)
+ ? {}
+ : { duration: Math.round(duration) }
+ : { duration: seconds }),
+ ...(isNil(projectId) ? {} : { project_id: projectId }),
+ ...(isNil(taskId) ? {} : { task_id: taskId }),
+ ...(isNil(tagIds) ? {} : { tag_ids: tagIds }),
+ ...(isNil(billable) ? {} : { billable }),
+ };
+ if (Object.keys(body).length === 0) {
+ throw new Error('Provide at least one field to update.');
+ }
+ await togglApi.request<unknown>({
+ auth,
+ method: togglApi.HttpMethod.PATCH,
+ path: entryPath,
+ body,
+ });
+ const updated = await togglApi.request<TwoTimeEntry>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: entryPath,
+ });
+ return togglModels.timeEntry({ item: updated, running: false });
+ }
+
+ const body = {
+ ...(isNil(newDescription) ? {} : { description: newDescription }),
+ ...(startIso ? { start: startIso } : {}),
+ ...(stopIso ? { stop: stopIso } : {}),
+ ...(!stopIso && !isNil(duration) ? { duration: Math.round(duration) } : {}),
+ ...(isNil(projectId) ? {} : { project_id: projectId }),
+ ...(isNil(taskId) ? {} : { task_id: taskId }),
+ ...(isNil(tagList) ? {} : { tags: tagList }),
+ ...(isNil(billable) ? {} : { billable }),
+ };
+ if (Object.keys(body).length === 0) {
+ throw new Error('Provide at least one field to update.');
+ }
+ return togglApi.request<Record<string, unknown>>({
+ auth,
+ method: togglApi.HttpMethod.PUT,
+ path: `/workspaces/${workspaceId}/time_entries/${timeEntryId}`,
+ body,
+ });
+ },
+ });
+ },
+});
+
+function secondsBetween({
+ start,
+ stop,
+}: {
+ start: string | undefined;
+ stop: string | undefined;
+}): number | undefined {
+ if (!start || !stop) {
+ return undefined;
+ }
+ const seconds = Math.round(
+ (new Date(stop).getTime() - new Date(start).getTime()) / 1000
+ );
+ if (seconds < 0) {
+ throw new Error('Stop Time must be after Start Time.');
+ }
+ return seconds;
+}
diff --git a/packages/pieces/community/toggl-track/src/lib/auth.ts b/packages/pieces/community/toggl-track/src/lib/auth.ts
new file mode 100644
index 00000000000..9310e2cf129
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/auth.ts
@@ -0,0 +1,113 @@
+import {
+ AppConnectionType,
+ PieceAuth,
+ Property,
+} from '@activepieces/pieces-framework';
+import { togglApi } from './common/client';
+
+const togglClassicAuth = PieceAuth.SecretText({
+ displayName: 'Toggl Track (Classic)',
+ description: `Use this for classic Toggl Track accounts (track.toggl.com).
+
+1. Log in to [Toggl Track](https://track.toggl.com).
+2. Open your **Profile settings** (https://track.toggl.com/profile).
+3. Scroll to **API Token** at the bottom of the page and copy it (a 32-character code).`,
+ required: true,
+ validate: async ({ auth }) => {
+ try {
+ await togglApi.request({
+ auth: { type: AppConnectionType.SECRET_TEXT, secret_text: auth },
+ method: togglApi.HttpMethod.GET,
+ path: '/me',
+ });
+ return { valid: true };
+ } catch (error) {
+ const status = togglApi.httpStatusOf(error);
+ if (status === 401 || status === 403) {
+ return {
+ valid: false,
+ error:
+ 'Invalid API token. Copy the API Token from https://track.toggl.com/profile. If your account uses Toggl 2.0 (focus.toggl.com), choose the "Toggl 2.0" connection type instead.',
+ };
+ }
+ return {
+ valid: false,
+ error: `Could not check the token with Toggl Track: ${togglApi.errorText(error)}`,
+ };
+ }
+ },
+});
+
+const togglTwoAuth = PieceAuth.CustomAuth({
+ displayName: 'Toggl 2.0',
+ description: `Use this for Toggl 2.0 accounts (focus.toggl.com).
+
+**API token**
+1. Log in to [Toggl 2.0](https://focus.toggl.com).
+2. Open **Settings** (https://focus.toggl.com/settings) and go to the **API token** section of your account settings.
+3. Create a token and copy it. It starts with \`toggl_sk_\`. Tokens can expire, so create a new one and update this connection if requests start failing.
+
+**Organization ID**
+Open Toggl 2.0 in your browser and look at the address bar. The number after \`/organizations/\` is your organization ID (for example \`https://focus.toggl.com/.../organizations/12345678/workspaces/...\`).
+
+Note: Toggl 2.0 limits API requests per hour (30 on the Free plan, 240 on Starter, 600 on Premium).`,
+ required: true,
+ props: {
+ token: PieceAuth.SecretText({
+ displayName: 'API Token',
+ description: 'The Toggl 2.0 API token (starts with toggl_sk_).',
+ required: true,
+ }),
+ organization_id: Property.ShortText({
+ displayName: 'Organization ID',
+ description:
+ 'The number after /organizations/ in the Toggl 2.0 address bar.',
+ required: true,
+ }),
+ },
+ validate: async ({ auth }) => {
+ const connection = togglApi.twoConnection({ props: auth });
+ if (!togglApi.isPositiveId(auth.organization_id)) {
+ return {
+ valid: false,
+ error:
+ 'The Organization ID must be a number. Copy the number after /organizations/ in the Toggl 2.0 address bar.',
+ };
+ }
+ try {
+ await togglApi.twoSettings(connection);
+ } catch (error) {
+ const status = togglApi.httpStatusOf(error);
+ if (status === 401 || status === 403) {
+ return {
+ valid: false,
+ error:
+ 'Invalid or expired API token. Create a new token in Toggl 2.0 settings (it starts with toggl_sk_). If your account uses classic Toggl Track (track.toggl.com), choose the "Toggl Track (Classic)" connection type instead.',
+ };
+ }
+ return {
+ valid: false,
+ error: `Could not check the token with Toggl 2.0: ${togglApi.errorText(error)}`,
+ };
+ }
+ try {
+ await togglApi.twoOrganizationUsers({ auth: connection, perPage: 1 });
+ } catch (error) {
+ const status = togglApi.httpStatusOf(error);
+ if (status === 400 || status === 403 || status === 404) {
+ return {
+ valid: false,
+ error:
+ 'This API token cannot access that organization. Check the Organization ID (the number after /organizations/ in the Toggl 2.0 address bar).',
+ };
+ }
+ return {
+ valid: false,
+ error: `Could not check the organization with Toggl 2.0: ${togglApi.errorText(error)}`,
+ };
+ }
+ return { valid: true };
+ },
+});
+
+export const togglTrackAuth = [togglClassicAuth, togglTwoAuth];
diff --git a/packages/pieces/community/toggl-track/src/lib/common/agent.ts b/packages/pieces/community/toggl-track/src/lib/common/agent.ts
new file mode 100644
index 00000000000..e73f48e615f
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/common/agent.ts
@@ -0,0 +1,266 @@
+import { isNil } from '@activepieces/pieces-framework';
+import { TogglAuthValue, togglApi } from './client';
+import { TwoProject } from './models';
+
+async function listCandidateProjects({
+ auth,
+ includeArchived,
+}: {
+ auth: TogglAuthValue;
+ includeArchived: boolean;
+}): Promise<AgentProject[]> {
+ if (togglApi.isTwo(auth)) {
+ const workspaces = await togglApi.twoWorkspaces(auth);
+ const perWorkspace = await Promise.all(
+ workspaces.map(async (workspace) => {
+ const projects = await togglApi.listTwoPages<TwoProject>({
+ auth,
+ path: togglApi.twoWorkspacePath({
+ auth,
+ workspaceId: workspace.id,
+ path: '/projects',
+ }),
+ queryParams: includeArchived ? {} : { archived: 'false' },
+ });
+ return projects.map((project) => ({
+ id: project.id,
+ name: project.name,
+ workspaceId: workspace.id,
+ clientName: project.client?.name ?? null,
+ }));
+ })
+ );
+ return perWorkspace.flat();
+ }
+ const projects = await togglApi.request<ClassicProject[] | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: '/me/projects',
+ ...(includeArchived ? { queryParams: { include_archived: 'true' } } : {}),
+ });
+ return (projects ?? []).map((project) => ({
+ id: project.id,
+ name: project.name,
+ workspaceId: project.workspace_id,
+ clientName: project.client_name ?? null,
+ }));
+}
+
+function pickProject({
+ projects,
+ reference,
+}: {
+ projects: AgentProject[];
+ reference: string;
+}): AgentProject {
+ const trimmed = reference.trim();
+ if (/^\d+$/.test(trimmed)) {
+ const byId = projects.find((project) => String(project.id) === trimmed);
+ if (byId) {
+ return byId;
+ }
+ }
+ const lowered = trimmed.toLowerCase();
+ const byName = projects.filter(
+ (project) => project.name.trim().toLowerCase() === lowered
+ );
+ if (byName.length === 1) {
+ return byName[0];
+ }
+ if (byName.length > 1) {
+ const ids = byName.map((project) => project.id).join(', ');
+ throw new Error(
+ `${byName.length} projects are named "${trimmed}" (IDs: ${ids}). Pass the project ID instead.`
+ );
+ }
+ const names = projects
+ .slice(0, MAX_LISTED_PROJECTS)
+ .map((project) => `${project.name} (${project.id})`)
+ .join(', ');
+ throw new Error(
+ `Project "${trimmed}" was not found. Projects: ${names || 'none'}${
+ projects.length > MAX_LISTED_PROJECTS ? ', …' : ''
+ }.`
+ );
+}
+
+async function defaultWorkspaceId(auth: TogglAuthValue): Promise<number> {
+ if (togglApi.isTwo(auth)) {
+ const settings = await togglApi.twoSettings(auth);
+ return settings.current_workspace_id;
+ }
+ const me = await togglApi.request<{ default_workspace_id?: number } | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: '/me',
+ });
+ if (isNil(me?.default_workspace_id)) {
+ throw new Error('Could not determine the default Toggl workspace.');
+ }
+ return me.default_workspace_id;
+}
+
+async function resolveTarget({
+ auth,
+ projectReference,
+ includeArchived = false,
+}: {
+ auth: TogglAuthValue;
+ projectReference: string | undefined;
+ includeArchived?: boolean;
+}): Promise<{ workspaceId: number; projectId: number | undefined }> {
+ const reference = projectReference?.trim();
+ if (!reference) {
+ return {
+ workspaceId: await defaultWorkspaceId(auth),
+ projectId: undefined,
+ };
+ }
+ const projects = await listCandidateProjects({ auth, includeArchived });
+ const project = pickProject({ projects, reference });
+ return { workspaceId: project.workspaceId, projectId: project.id };
+}
+
+function parseStart({ value }: { value: string }): string {
+ const trimmed = value.trim();
+ if (trimmed.toLowerCase() === 'now' || trimmed === '') {
+ return new Date().toISOString();
+ }
+ return togglApi.toIsoDateTime({ value: trimmed, label: 'Start' });
+}
+
+function durationSeconds({ minutes }: { minutes: unknown }): number {
+ const parsed = typeof minutes === 'string' ? Number(minutes) : minutes;
+ if (
+ typeof parsed !== 'number' ||
+ !Number.isFinite(parsed) ||
+ parsed <= 0
+ ) {
+ throw new Error('Duration must be a positive number of minutes.');
+ }
+ const seconds = Math.round(parsed * 60);
+ if (seconds <= 0) {
+ throw new Error('Duration must be a positive number of minutes.');
+ }
+ return seconds;
+}
+
+function summarize({
+ entries,
+ groupBy,
+}: {
+ entries: SummaryEntry[];
+ groupBy: SummaryGroupBy;
+}): TimeSummary {
+ const groups = new Map<string, TimeSummaryGroup>();
+ let totalSeconds = 0;
+ for (const entry of entries) {
+ const seconds = entry.seconds;
+ if (isNil(seconds) || seconds < 0) {
+ continue;
+ }
+ totalSeconds += seconds;
+ const target =
+ groupBy === 'project'
+ ? { id: entry.projectId, name: entry.projectName }
+ : groupBy === 'user'
+ ? { id: entry.userId, name: entry.userName }
+ : { id: entry.clientId, name: entry.clientName };
+ const key = `${target.id ?? ''}|${target.name ?? ''}`;
+ const group = groups.get(key) ?? {
+ id: target.id ?? null,
+ name: target.name ?? fallbackName(groupBy),
+ seconds: 0,
+ hours: 0,
+ entry_count: 0,
+ };
+ group.seconds += seconds;
+ group.entry_count += 1;
+ groups.set(key, group);
+ }
+ const list = [...groups.values()]
+ .map((group) => ({ ...group, hours: toHours(group.seconds) }))
+ .sort((a, b) => b.seconds - a.seconds);
+ return {
+ total_seconds: totalSeconds,
+ total_hours: toHours(totalSeconds),
+ groups: list,
+ };
+}
+
+function parseGroupBy(value: string | undefined): SummaryGroupBy {
+ const trimmed = (value ?? '').trim().toLowerCase();
+ if (trimmed === '') {
+ return 'project';
+ }
+ if (trimmed === 'project' || trimmed === 'user' || trimmed === 'client') {
+ return trimmed;
+ }
+ throw new Error('Group By must be "project", "user", or "client".');
+}
+
+function fallbackName(groupBy: SummaryGroupBy): string {
+ return groupBy === 'project'
+ ? 'No project'
+ : groupBy === 'client'
+ ? 'No client'
+ : 'Unknown user';
+}
+
+function toHours(seconds: number): number {
+ return Math.round((seconds / 3600) * 100) / 100;
+}
+
+const MAX_LISTED_PROJECTS = 25;
+
+export const togglAgent = {
+ listCandidateProjects,
+ pickProject,
+ defaultWorkspaceId,
+ resolveTarget,
+ parseStart,
+ durationSeconds,
+ parseGroupBy,
+ summarize,
+ toHours,
+};
+
+export type AgentProject = {
+ id: number;
+ name: string;
+ workspaceId: number;
+ clientName: string | null;
+};
+
+export type SummaryGroupBy = 'project' | 'user' | 'client';
+
+export type SummaryEntry = {
+ seconds: number | null;
+ projectId: number | null;
+ projectName: string | null;
+ userId: number | null;
+ userName: string | null;
+ clientId: number | null;
+ clientName: string | null;
+};
+
+export type TimeSummaryGroup = {
+ id: number | null;
+ name: string;
+ seconds: number;
+ hours: number;
+ entry_count: number;
+};
+
+export type TimeSummary = {
+ total_seconds: number;
+ total_hours: number;
+ groups: TimeSummaryGroup[];
+};
+
+type ClassicProject = {
+ id: number;
+ name: string;
+ workspace_id: number;
+ client_name?: string | null;
+};
diff --git a/packages/pieces/community/toggl-track/src/lib/common/client.ts b/packages/pieces/community/toggl-track/src/lib/common/client.ts
new file mode 100644
index 00000000000..495ba03aa56
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/common/client.ts
@@ -0,0 +1,523 @@
+import { AppConnectionType, isNil } from '@activepieces/pieces-framework';
+import {
+ HttpMethod,
+ QueryParams,
+ httpClient,
+} from '@activepieces/pieces-common';
+
+async function request<T>({
+ auth,
+ method,
+ path,
+ queryParams,
+ body,
+}: TogglRequest): Promise<T> {
+ try {
+ const response = await httpClient.sendRequest<T>({
+ method,
+ url: `${baseUrl(auth)}${path}`,
+ headers: {
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ Authorization: authorizationHeader(auth),
+ },
+ queryParams,
+ body,
+ });
+ return response.body;
+ } catch (error) {
+ const status = httpStatusOf(error);
+ if (isTwo(auth) && status === 402) {
+ throw new Error(
+ 'Toggl 2.0 hourly API request limit reached for this organization (30 requests per hour on the Free plan). Wait for the limit to reset or upgrade the Toggl plan.'
+ );
+ }
+ if (
+ isTwo(auth) &&
+ (status === 403 || status === 404) &&
+ path.startsWith('/organizations/') &&
+ (responseDetail(error) ?? '').toLowerCase().includes('organization')
+ ) {
+ throw new Error(
+ `Toggl 2.0 denied access to organization ${auth.props.organization_id}. Check the Organization ID in the connection (the number after /organizations/ in the Toggl 2.0 address bar).`
+ );
+ }
+ throw error;
+ }
+}
+
+async function classicReportsRequest<T>({
+ auth,
+ workspaceId,
+ body,
+}: {
+ auth: TogglAuthValue;
+ workspaceId: number;
+ body: Record<string, unknown>;
+}): Promise<{ body: T; headers: Record<string, unknown> }> {
+ const response = await httpClient.sendRequest<T>({
+ method: HttpMethod.POST,
+ url: `${CLASSIC_REPORTS_BASE_URL}/workspace/${workspaceId}/search/time_entries`,
+ headers: {
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ Authorization: authorizationHeader(auth),
+ },
+ body,
+ });
+ return { body: response.body, headers: response.headers ?? {} };
+}
+
+async function withNotFound<T>({
+ label,
+ run,
+}: {
+ label: string;
+ run: () => Promise<T>;
+}): Promise<T> {
+ try {
+ return await run();
+ } catch (error) {
+ if (httpStatusOf(error) === 404) {
+ throw new Error(
+ `${label} was not found. Check the ID and the selected workspace.`
+ );
+ }
+ throw error;
+ }
+}
+
+async function listTwoPages<T>({
+ auth,
+ path,
+ queryParams,
+}: {
+ auth: TogglAuthValue;
+ path: string;
+ queryParams?: QueryParams;
+}): Promise<T[]> {
+ const collected = await collectTwoPages<T>({
+ auth,
+ path,
+ queryParams: queryParams ?? {},
+ page: 1,
+ });
+ return collected;
+}
+
+async function listTwoPageOrAll<T>({
+ auth,
+ path,
+ queryParams,
+ page,
+ perPage,
+}: {
+ auth: TogglAuthValue;
+ path: string;
+ queryParams: QueryParams;
+ page: number | undefined;
+ perPage: number | undefined;
+}): Promise<T[]> {
+ if (isNil(page)) {
+ return listTwoPages<T>({ auth, path, queryParams });
+ }
+ const size = Math.min(Math.max(Math.floor(perPage ?? TWO_PAGE_SIZE), 1), TWO_PAGE_SIZE);
+ const body = await request<T[] | { data: T[] | null }>({
+ auth,
+ method: HttpMethod.GET,
+ path,
+ queryParams: {
+ ...queryParams,
+ page: String(Math.max(Math.floor(page), 1)),
+ per_page: String(size),
+ },
+ });
+ return Array.isArray(body) ? body : body?.data ?? [];
+}
+
+async function collectTwoPages<T>({
+ auth,
+ path,
+ queryParams,
+ page,
+}: {
+ auth: TogglAuthValue;
+ path: string;
+ queryParams: QueryParams;
+ page: number;
+}): Promise<T[]> {
+ if (page > TWO_MAX_PAGES) {
+ throw new Error(
+ `Toggl 2.0 returned more than ${TWO_PAGE_SIZE * TWO_MAX_PAGES} results. Narrow the filters and try again.`
+ );
+ }
+ const body = await request<T[] | { data: T[] | null }>({
+ auth,
+ method: HttpMethod.GET,
+ path,
+ queryParams: {
+ ...queryParams,
+ page: String(page),
+ per_page: String(TWO_PAGE_SIZE),
+ },
+ });
+ const items = Array.isArray(body) ? body : body?.data ?? [];
+ if (items.length < TWO_PAGE_SIZE) {
+ return items;
+ }
+ const rest = await collectTwoPages<T>({
+ auth,
+ path,
+ queryParams,
+ page: page + 1,
+ });
+ return [...items, ...rest];
+}
+
+function isTwo(auth: TogglAuthValue): auth is TogglTwoAuthValue {
+ return auth.type === AppConnectionType.CUSTOM_AUTH;
+}
+
+function twoConnection({ props }: { props: TogglTwoProps }): TogglAuthValue {
+ return { type: AppConnectionType.CUSTOM_AUTH, props };
+}
+
+function twoOrganizationId(auth: TogglTwoAuthValue): number {
+ return requireId({
+ value: auth.props.organization_id,
+ label: 'Organization ID',
+ });
+}
+
+function twoWorkspacePath({
+ auth,
+ workspaceId,
+ path,
+}: {
+ auth: TogglTwoAuthValue;
+ workspaceId: number;
+ path: string;
+}): string {
+ return `/organizations/${twoOrganizationId(auth)}/workspaces/${workspaceId}${path}`;
+}
+
+async function twoSettings(auth: TogglAuthValue): Promise<TwoSettings> {
+ return request<TwoSettings>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/users/me/settings',
+ });
+}
+
+async function twoCurrentUserAccountId(
+ auth: TogglAuthValue
+): Promise<number | null> {
+ const account = await request<{ user_account_id?: number } | null>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/accounts/me',
+ });
+ return account?.user_account_id ?? null;
+}
+
+async function twoOrganizationUsers({
+ auth,
+ perPage,
+ queryParams,
+}: {
+ auth: TogglAuthValue;
+ perPage: number;
+ queryParams?: QueryParams;
+}): Promise<TwoOrganizationUser[]> {
+ if (!isTwo(auth)) {
+ return [];
+ }
+ return request<TwoOrganizationUser[]>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/organizations/${twoOrganizationId(auth)}/users`,
+ queryParams: { ...queryParams, page: '1', per_page: String(perPage) },
+ });
+}
+
+async function twoWorkspaces(auth: TogglTwoAuthValue): Promise<TwoWorkspace[]> {
+ const userAccountId = await twoCurrentUserAccountId(auth).catch(() => null);
+ if (!isNil(userAccountId)) {
+ const users = await twoOrganizationUsers({
+ auth,
+ perPage: 1,
+ queryParams: { user_account_ids: String(userAccountId) },
+ });
+ const me = users.find((user) => user.user_account_id === userAccountId);
+ if (me && me.workspaces.length > 0) {
+ return me.workspaces.map((workspace) => ({
+ id: workspace.id,
+ name: workspace.name,
+ }));
+ }
+ }
+ const settings = await twoSettings(auth);
+ return [
+ {
+ id: settings.current_workspace_id,
+ name: `Workspace ${settings.current_workspace_id}`,
+ },
+ ];
+}
+
+async function resolveTwoTagIds({
+ auth,
+ workspaceId,
+ names,
+}: {
+ auth: TogglTwoAuthValue;
+ workspaceId: number;
+ names: string[] | undefined;
+}): Promise<number[] | undefined> {
+ if (isNil(names)) {
+ return undefined;
+ }
+ if (names.length === 0) {
+ return [];
+ }
+ const existing = await listTwoPages<TwoTag>({
+ auth,
+ path: `/workspaces/${workspaceId}/tags`,
+ });
+ const byName = new Map(
+ existing.map((tag) => [tag.name.trim().toLowerCase(), tag.id])
+ );
+ const uniqueNames = [...new Set(names.map((name) => name.trim()))].filter(
+ (name) => name.length > 0
+ );
+ const ids = await Promise.all(
+ uniqueNames.map(async (name) => {
+ const found = byName.get(name.toLowerCase());
+ if (!isNil(found)) {
+ return found;
+ }
+ const created = await request<TwoTag>({
+ auth,
+ method: HttpMethod.POST,
+ path: `/workspaces/${workspaceId}/tags`,
+ body: { name },
+ });
+ return created.id;
+ })
+ );
+ return ids;
+}
+
+function requireId({
+ value,
+ label,
+}: {
+ value: unknown;
+ label: string;
+}): number {
+ const parsed = parseId(value);
+ if (isNil(parsed)) {
+ throw new Error(`${label} must be a numeric Toggl ID.`);
+ }
+ return parsed;
+}
+
+function optionalId({
+ value,
+ label,
+}: {
+ value: unknown;
+ label: string;
+}): number | undefined {
+ if (isNil(value) || value === '') {
+ return undefined;
+ }
+ return requireId({ value, label });
+}
+
+function parseId(value: unknown): number | null {
+ if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) {
+ return value;
+ }
+ if (typeof value === 'string' && /^\d{1,15}$/.test(value.trim())) {
+ const parsed = Number(value.trim());
+ return parsed > 0 ? parsed : null;
+ }
+ return null;
+}
+
+function isPositiveId(value: unknown): boolean {
+ return !isNil(parseId(value));
+}
+
+function toIsoDateTime({
+ value,
+ label,
+}: {
+ value: string;
+ label: string;
+}): string {
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) {
+ throw new Error(
+ `${label} is not a valid date. Use YYYY-MM-DD or an ISO 8601 / RFC 3339 timestamp.`
+ );
+ }
+ return date.toISOString();
+}
+
+function classicOnlyError(feature: string): Error {
+ return new Error(
+ `${feature} is only available for Toggl Track (Classic) connections. Toggl 2.0 does not offer this in its public API.`
+ );
+}
+
+function httpStatusOf(error: unknown): number | undefined {
+ if (typeof error !== 'object' || error === null || !('response' in error)) {
+ return undefined;
+ }
+ const response = error.response;
+ if (
+ typeof response !== 'object' ||
+ response === null ||
+ !('status' in response)
+ ) {
+ return undefined;
+ }
+ return typeof response.status === 'number' ? response.status : undefined;
+}
+
+function errorText(error: unknown): string {
+ const status = httpStatusOf(error);
+ if (isNil(status)) {
+ return error instanceof Error ? error.message : String(error);
+ }
+ const detail = responseDetail(error);
+ return detail ? `HTTP ${status}: ${detail}` : `HTTP ${status}`;
+}
+
+function responseDetail(error: unknown): string | null {
+ if (typeof error !== 'object' || error === null || !('response' in error)) {
+ return null;
+ }
+ const response = error.response;
+ if (typeof response !== 'object' || response === null || !('body' in response)) {
+ return null;
+ }
+ const body = response.body;
+ if (typeof body === 'string') {
+ return body.slice(0, 300);
+ }
+ if (typeof body === 'object' && body !== null) {
+ if ('error_description' in body && typeof body.error_description === 'string') {
+ return body.error_description;
+ }
+ if ('message' in body && typeof body.message === 'string') {
+ return body.message;
+ }
+ }
+ return null;
+}
+
+function baseUrl(auth: TogglAuthValue): string {
+ return isTwo(auth) ? TWO_BASE_URL : CLASSIC_BASE_URL;
+}
+
+function authorizationHeader(auth: TogglAuthValue): string {
+ if (isTwo(auth)) {
+ return `Bearer ${auth.props.token.trim()}`;
+ }
+ return `Basic ${Buffer.from(`${auth.secret_text.trim()}:api_token`).toString(
+ 'base64'
+ )}`;
+}
+
+const CLASSIC_BASE_URL = 'https://api.track.toggl.com/api/v9';
+const TWO_BASE_URL = 'https://focus.toggl.com/api';
+const CLASSIC_REPORTS_BASE_URL = 'https://api.track.toggl.com/reports/api/v3';
+const TWO_PAGE_SIZE = 100;
+const TWO_MAX_PAGES = 50;
+
+export const togglApi = {
+ HttpMethod,
+ request,
+ classicReportsRequest,
+ withNotFound,
+ listTwoPages,
+ listTwoPageOrAll,
+ isTwo,
+ twoConnection,
+ twoOrganizationId,
+ twoWorkspacePath,
+ twoSettings,
+ twoCurrentUserAccountId,
+ twoOrganizationUsers,
+ twoWorkspaces,
+ resolveTwoTagIds,
+ requireId,
+ optionalId,
+ isPositiveId,
+ toIsoDateTime,
+ classicOnlyError,
+ httpStatusOf,
+ errorText,
+ baseUrl,
+ authorizationHeader,
+};
+
+type TogglRequest = {
+ auth: TogglAuthValue;
+ method: HttpMethod;
+ path: string;
+ queryParams?: QueryParams;
+ body?: unknown;
+};
+
+type TogglTwoProps = {
+ token: string;
+ organization_id: string;
+};
+
+type TogglClassicAuthValue = {
+ type: AppConnectionType.SECRET_TEXT;
+ secret_text: string;
+};
+
+
+type TwoSettings = {
+ current_workspace_id: number;
+};
+
+type TwoWorkspace = {
+ id: number;
+ name: string;
+};
+
+type TwoTag = {
+ id: number;
+ name: string;
+};
+
+export type TogglTwoAuthValue = {
+ type: AppConnectionType.CUSTOM_AUTH;
+ props: TogglTwoProps;
+};
+
+export type TogglAuthValue = TogglClassicAuthValue | TogglTwoAuthValue;
+
+export type TwoOrganizationUser = {
+ id: number;
+ user_account_id: number;
+ name: string;
+ email: string;
+ active: boolean;
+ joined?: boolean;
+ owner?: boolean;
+ created_at?: string;
+ updated_at?: string;
+ workspaces: {
+ id: number;
+ name: string;
+ workspace_user_id: number;
+ }[];
+};
diff --git a/packages/pieces/community/toggl-track/src/lib/common/index.ts b/packages/pieces/community/toggl-track/src/lib/common/index.ts
index d5c9dc48fc1..235d5e85bc6 100644
--- a/packages/pieces/community/toggl-track/src/lib/common/index.ts
+++ b/packages/pieces/community/toggl-track/src/lib/common/index.ts
@@ -1,328 +1,451 @@
import { Property } from '@activepieces/pieces-framework';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import { togglTrackAuth } from '../auth';
+import { TogglAuthValue, togglApi } from './client';
+import { TwoClient, TwoProject, TwoTag, TwoTask } from './models';
+async function loadOptions<T extends number | string>({
+ auth,
+ missing,
+ errorLabel,
+ load,
+}: {
+ auth: TogglAuthValue | undefined;
+ missing: string | null;
+ errorLabel: string;
+ load: (auth: TogglAuthValue) => Promise<DropdownOption<T>[]>;
+}): Promise<DropdownState<T>> {
+ if (!auth) {
+ return {
+ disabled: true,
+ placeholder: 'Connect your account first',
+ options: [],
+ };
+ }
+ if (missing) {
+ return { disabled: true, placeholder: missing, options: [] };
+ }
+ try {
+ const options = await load(auth);
+ return { disabled: false, options };
+ } catch (error) {
+ return {
+ disabled: true,
+ placeholder: `Error fetching ${errorLabel}: ${togglApi.errorText(error)}`,
+ options: [],
+ };
+ }
+}
-type TogglOrganization = {
- id: number;
- name: string;
-};
-type TogglWorkspace = {
- id: number;
- name: string;
-};
-type TogglClient = {
- id: number;
- name: string;
-};
-type TogglProject = {
- id: number;
- name: string;
-};
-type TogglTag = {
- id: number;
- name: string;
-};
-type TogglTask = {
- id: number;
- name: string;
+async function listOrganizations(auth: TogglAuthValue): Promise<DropdownOption<number>[]> {
+ if (togglApi.isTwo(auth)) {
+ const organizationId = togglApi.twoOrganizationId(auth);
+ return [{ label: `Organization ${organizationId}`, value: organizationId }];
+ }
+ const organizations = await togglApi.request<Named[]>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: '/me/organizations',
+ });
+ return (organizations ?? []).map((org) => ({ label: org.name, value: org.id }));
+}
+
+async function listWorkspaces(auth: TogglAuthValue): Promise<DropdownOption<number>[]> {
+ if (togglApi.isTwo(auth)) {
+ const workspaces = await togglApi.twoWorkspaces(auth);
+ return workspaces.map((workspace) => ({
+ label: workspace.name,
+ value: workspace.id,
+ }));
+ }
+ const workspaces = await togglApi.request<Named[]>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: '/me/workspaces',
+ });
+ return (workspaces ?? []).map((workspace) => ({
+ label: workspace.name,
+ value: workspace.id,
+ }));
+}
+
+async function listClients({
+ auth,
+ workspaceId,
+}: {
+ auth: TogglAuthValue;
+ workspaceId: number;
+}): Promise<DropdownOption<number>[]> {
+ if (togglApi.isTwo(auth)) {
+ const clients = await togglApi.listTwoPages<TwoClient>({
+ auth,
+ path: `/workspaces/${workspaceId}/clients`,
+ });
+ return clients.map((client) => ({ label: client.name, value: client.id }));
+ }
+ const clients = await togglApi.request<Named[] | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/workspaces/${workspaceId}/clients`,
+ });
+ return (clients ?? []).map((client) => ({
+ label: client.name,
+ value: client.id,
+ }));
+}
+
+async function listProjects({
+ auth,
+ workspaceId,
+}: {
+ auth: TogglAuthValue;
+ workspaceId: number;
+}): Promise<DropdownOption<number>[]> {
+ if (togglApi.isTwo(auth)) {
+ const projects = await togglApi.listTwoPages<TwoProject>({
+ auth,
+ path: togglApi.twoWorkspacePath({
+ auth,
+ workspaceId,
+ path: '/projects',
+ }),
+ queryParams: { archived: 'false' },
+ });
+ return projects.map((project) => ({
+ label: project.name,
+ value: project.id,
+ }));
+ }
+ const projects = await togglApi.request<Named[] | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/workspaces/${workspaceId}/projects`,
+ });
+ return (projects ?? []).map((project) => ({
+ label: project.name,
+ value: project.id,
+ }));
+}
+
+async function listTags({
+ auth,
+ workspaceId,
+}: {
+ auth: TogglAuthValue;
+ workspaceId: number;
+}): Promise<DropdownOption<string>[]> {
+ if (togglApi.isTwo(auth)) {
+ const tags = await togglApi.listTwoPages<TwoTag>({
+ auth,
+ path: `/workspaces/${workspaceId}/tags`,
+ });
+ return tags.map((tag) => ({ label: tag.name, value: tag.name }));
+ }
+ const tags = await togglApi.request<Named[] | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/workspaces/${workspaceId}/tags`,
+ });
+ return (tags ?? []).map((tag) => ({ label: tag.name, value: tag.name }));
+}
+
+async function listTasks({
+ auth,
+ workspaceId,
+ projectId,
+}: {
+ auth: TogglAuthValue;
+ workspaceId: number;
+ projectId: number;
+}): Promise<DropdownOption<number>[]> {
+ if (togglApi.isTwo(auth)) {
+ const tasks = await togglApi.listTwoPages<TwoTask>({
+ auth,
+ path: togglApi.twoWorkspacePath({ auth, workspaceId, path: '/tasks' }),
+ queryParams: { project_id: String(projectId), archived: 'false' },
+ });
+ return tasks.map((task) => ({ label: task.name, value: task.id }));
+ }
+ const response = await togglApi.request<{ data: Named[] | null }>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/workspaces/${workspaceId}/tasks`,
+ queryParams: { pid: String(projectId) },
+ });
+ return (response?.data ?? []).map((task) => ({
+ label: task.name,
+ value: task.id,
+ }));
+}
+
+function clientDropdown({
+ required,
+ description,
+}: {
+ required: boolean;
+ description: string;
+}) {
+ return Property.Dropdown({
+ auth: togglTrackAuth,
+ displayName: 'Client',
+ description,
+ required,
+ refreshers: ['workspace_id'],
+ options: async ({ auth, workspace_id }) =>
+ loadOptions({
+ auth,
+ missing: workspace_id ? null : 'Select a workspace first',
+ errorLabel: 'clients',
+ load: (connection) =>
+ listClients({
+ auth: connection,
+ workspaceId: togglApi.requireId({
+ value: workspace_id,
+ label: 'Workspace',
+ }),
+ }),
+ }),
+ });
+}
+
+async function listTagIds({
+ auth,
+ workspaceId,
+}: {
+ auth: TogglAuthValue;
+ workspaceId: number;
+}): Promise<DropdownOption<number>[]> {
+ if (togglApi.isTwo(auth)) {
+ const tags = await togglApi.listTwoPages<TwoTag>({
+ auth,
+ path: `/workspaces/${workspaceId}/tags`,
+ });
+ return tags.map((tag) => ({ label: tag.name, value: tag.id }));
+ }
+ const tags = await togglApi.request<Named[] | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: `/workspaces/${workspaceId}/tags`,
+ });
+ return (tags ?? []).map((tag) => ({ label: tag.name, value: tag.id }));
+}
+
+function workspaceDropdown({ required }: { required: boolean }) {
+ return Property.Dropdown({
+ auth: togglTrackAuth,
+ displayName: 'Workspace',
+ description: required
+ ? 'The workspace to operate in.'
+ : 'The workspace to search in. Toggl Track (Classic): leave empty to search all workspaces. Toggl 2.0: leave empty to use your current workspace.',
+ required,
+ refreshers: [],
+ options: async ({ auth }) =>
+ loadOptions({
+ auth,
+ missing: null,
+ errorLabel: 'workspaces',
+ load: listWorkspaces,
+ }),
+ });
+}
+
+function projectDropdown({
+ required,
+ description,
+}: {
+ required: boolean;
+ description: string;
+}) {
+ return Property.Dropdown({
+ auth: togglTrackAuth,
+ displayName: 'Project',
+ description,
+ required,
+ refreshers: ['workspace_id'],
+ options: async ({ auth, workspace_id }) =>
+ loadOptions({
+ auth,
+ missing: workspace_id ? null : 'Select a workspace first',
+ errorLabel: 'projects',
+ load: (connection) =>
+ listProjects({
+ auth: connection,
+ workspaceId: togglApi.requireId({
+ value: workspace_id,
+ label: 'Workspace',
+ }),
+ }),
+ }),
+ });
+}
+
+function updateFlag({
+ displayName,
+ description,
+}: {
+ displayName: string;
+ description: string;
+}) {
+ return Property.StaticDropdown({
+ displayName,
+ description: `${description} Leave empty to keep the current value.`,
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Yes', value: 'yes' },
+ { label: 'No', value: 'no' },
+ ],
+ },
+ });
+}
+
+function flagValue(value: string | undefined | null): boolean | undefined {
+ if (value === 'yes') return true;
+ if (value === 'no') return false;
+ return undefined;
+}
+
+function tagListValue({
+ tags,
+ clearTags,
+}: {
+ tags: string[] | undefined;
+ clearTags: boolean | undefined;
+}): string[] | undefined {
+ if (clearTags) {
+ if (tags && tags.length > 0) {
+ throw new Error('Set Tags or Clear Tags, not both.');
+ }
+ return [];
+ }
+ return tags && tags.length > 0 ? tags : undefined;
}
export const togglCommon = {
+ updateFlag,
+ flagValue,
+ tagListValue,
organization_id: Property.Dropdown({
- auth:togglTrackAuth,
+ auth: togglTrackAuth,
displayName: 'Organization',
- description: 'The organization to operate in.',
+ description:
+ 'The organization to operate in. For Toggl 2.0 this is the organization from the connection.',
required: true,
refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Connect your account first',
- options: [],
- };
- }
- const apiToken = auth.secret_text;
- const response = await httpClient.sendRequest<TogglOrganization[]>({
- method: HttpMethod.GET,
- url: 'https://api.track.toggl.com/api/v9/me/organizations',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(
- `${apiToken}:api_token`
- ).toString('base64')}`,
- },
- });
- if (response.status === 200) {
- return {
- disabled: false,
- options: (response.body || []).map((org) => ({
- label: org.name,
- value: org.id,
- })),
- };
- }
- return {
- disabled: true,
- placeholder: 'Error fetching organizations',
- options: [],
- };
- },
+ options: async ({ auth }) =>
+ loadOptions({
+ auth,
+ missing: null,
+ errorLabel: 'organizations',
+ load: listOrganizations,
+ }),
}),
- workspace_id: Property.Dropdown({
- auth:togglTrackAuth,
- displayName: 'Workspace',
- description: 'The workspace to operate in.',
+ workspace_id: workspaceDropdown({ required: true }),
+ optional_workspace_id: workspaceDropdown({ required: false }),
+ client_id: clientDropdown({
+ required: false,
+ description: 'The client to associate the project with.',
+ }),
+ required_client_id: clientDropdown({
required: true,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'Connect your account first',
- options: [],
- };
- }
- const apiToken = auth.secret_text;
-
- const response = await httpClient.sendRequest<TogglWorkspace[]>({
- method: HttpMethod.GET,
- url: 'https://api.track.toggl.com/api/v9/me/workspaces',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(
- `${apiToken}:api_token`
- ).toString('base64')}`,
- },
- });
- if (response.status === 200) {
- return {
- disabled: false,
-
- options: (response.body || []).map((workspace) => ({
- label: workspace.name,
- value: workspace.id,
- })),
- };
- }
- return {
- disabled: true,
- placeholder: 'Error fetching workspaces',
- options: [],
- };
- },
+ description: 'The client to use. Agents can pass the client ID directly.',
}),
- client_id: Property.Dropdown({
- auth:togglTrackAuth,
- displayName: 'Client',
- description: 'The client to associate the project with.',
- required: false,
+ tag_id: Property.Dropdown({
+ auth: togglTrackAuth,
+ displayName: 'Tag',
+ description: 'The tag to use. Agents can pass the tag ID directly.',
+ required: true,
refreshers: ['workspace_id'],
- options: async ({ auth, workspace_id }) => {
- if (!auth || !workspace_id) {
- return {
- disabled: true,
- placeholder: 'Select a workspace first',
- options: [],
- };
- }
- const apiToken = auth.secret_text;
- const response = await httpClient.sendRequest<TogglClient[]>({
- method: HttpMethod.GET,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/clients`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(
- `${apiToken}:api_token`
- ).toString('base64')}`,
- },
- });
- if (response.status === 200) {
- return {
- disabled: false,
- options: (response.body || []).map((client) => ({
- label: client.name,
- value: client.id,
- })),
- };
- }
- return {
- disabled: true,
- placeholder: 'Error fetching clients',
- options: [],
- };
- },
+ options: async ({ auth, workspace_id }) =>
+ loadOptions({
+ auth,
+ missing: workspace_id ? null : 'Select a workspace first',
+ errorLabel: 'tags',
+ load: (connection) =>
+ listTagIds({
+ auth: connection,
+ workspaceId: togglApi.requireId({
+ value: workspace_id,
+ label: 'Workspace',
+ }),
+ }),
+ }),
}),
- project_id: Property.Dropdown({
- auth:togglTrackAuth,
- displayName: 'Project',
- description: 'The project to create the task under.',
+ project_id: projectDropdown({
required: true,
- refreshers: ['workspace_id'],
- options: async ({ auth, workspace_id }) => {
- if (!auth || !workspace_id) {
- return {
- disabled: true,
- placeholder: 'Select a workspace first',
- options: [],
- };
- }
- const apiToken = auth.secret_text;
- const response = await httpClient.sendRequest<TogglProject[]>({
- method: HttpMethod.GET,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/projects`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(
- `${apiToken}:api_token`
- ).toString('base64')}`,
- },
- });
- if (response.status === 200) {
- return {
- disabled: false,
- options: (response.body || []).map((project) => ({
- label: project.name,
- value: project.id,
- })),
- };
- }
- return {
- disabled: true,
- placeholder: 'Error fetching projects',
- options: [],
- };
- },
+ description: 'The project to create the task under.',
}),
- optional_project_id: Property.Dropdown({
- auth:togglTrackAuth,
- displayName: 'Project',
- description: 'The project to associate the time entry with.',
+ optional_project_id: projectDropdown({
required: false,
- refreshers: ['workspace_id'],
- options: async ({ auth, workspace_id }) => {
- if (!auth || !workspace_id) {
- return {
- disabled: true,
- placeholder: 'Select a workspace first',
- options: [],
- };
- }
- const apiToken = auth.secret_text;
- const response = await httpClient.sendRequest<TogglProject[]>({
- method: HttpMethod.GET,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/projects`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(
- `${apiToken}:api_token`
- ).toString('base64')}`,
- },
- });
- if (response.status === 200) {
- return {
- disabled: false,
- options: (response.body || []).map((project) => ({
- label: project.name,
- value: project.id,
- })),
- };
- }
- return {
- disabled: true,
- placeholder: 'Error fetching projects',
- options: [],
- };
- },
+ description: 'The project to associate the time entry with.',
}),
tags: Property.MultiSelectDropdown({
- auth:togglTrackAuth,
+ auth: togglTrackAuth,
displayName: 'Tags',
- description: 'Tags to associate with the time entry. You can create new tags by typing them.',
+ description:
+ 'Tags to associate with the time entry. Tags that do not exist yet are created in the workspace.',
required: false,
refreshers: ['workspace_id'],
- options: async ({ auth, workspace_id }) => {
- if (!auth || !workspace_id) {
- return {
- disabled: true,
- placeholder: 'Select a workspace first',
- options: [],
- };
- }
- const apiToken = auth.secret_text;
- const response = await httpClient.sendRequest<TogglTag[]>({
- method: HttpMethod.GET,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/tags`,
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(
- `${apiToken}:api_token`
- ).toString('base64')}`,
- },
- });
- if (response.status === 200) {
- return {
- disabled: false,
- options: (response.body || []).map((tag) => ({
- label: tag.name,
- value: tag.name,
- })),
- };
- }
- return {
- disabled: true,
- placeholder: 'Error fetching tags',
- options: [],
- };
- },
+ options: async ({ auth, workspace_id }) =>
+ loadOptions({
+ auth,
+ missing: workspace_id ? null : 'Select a workspace first',
+ errorLabel: 'tags',
+ load: (connection) =>
+ listTags({
+ auth: connection,
+ workspaceId: togglApi.requireId({
+ value: workspace_id,
+ label: 'Workspace',
+ }),
+ }),
+ }),
}),
- optional_task_id: Property.Dropdown({
- auth:togglTrackAuth,
- displayName: "Task",
- description: "The task to select.",
+ optional_task_id: taskDropdown({ projectField: 'project_id' }),
+ taskDropdown,
+};
+
+function taskDropdown({ projectField }: { projectField: string }) {
+ return Property.Dropdown({
+ auth: togglTrackAuth,
+ displayName: 'Task',
+ description: 'The task to select.',
required: false,
- refreshers: ['workspace_id', 'optional_project_id'],
- options: async ({ auth, workspace_id, optional_project_id }) => {
- if (!auth || !workspace_id || !optional_project_id) {
- return {
- disabled: true,
- placeholder: 'Select a workspace and project first',
- options: [],
- };
- }
- const apiToken = auth.secret_text;
+ refreshers: ['workspace_id', projectField],
+ options: async (context) => {
+ const auth = context.auth;
+ const workspaceValue = context['workspace_id'];
+ const projectValue = context[projectField];
+ return loadOptions({
+ auth,
+ missing:
+ workspaceValue && projectValue
+ ? null
+ : 'Select a workspace and project first',
+ errorLabel: 'tasks',
+ load: (connection) =>
+ listTasks({
+ auth: connection,
+ workspaceId: togglApi.requireId({
+ value: workspaceValue,
+ label: 'Workspace',
+ }),
+ projectId: togglApi.requireId({
+ value: projectValue,
+ label: 'Project',
+ }),
+ }),
+ });
+ },
+ });
+}
- const response = await httpClient.sendRequest<{ data: TogglTask[] }>({
- method: HttpMethod.GET,
- url: `https://api.track.toggl.com/api/v9/workspaces/${workspace_id}/tasks`,
- queryParams: {
- pid: optional_project_id as string
- },
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Basic ${Buffer.from(
- `${apiToken}:api_token`
- ).toString('base64')}`,
- },
- });
+type Named = { id: number; name: string };
- if (response.status === 200) {
- return {
- disabled: false,
- options: (response.body.data || []).map((task) => ({
- label: task.name,
- value: task.id,
- })),
- };
- }
-
- return {
- disabled: true,
- placeholder: 'Error fetching tasks',
- options: [],
- };
- }
-}),
-};
+type DropdownOption<T> = { label: string; value: T };
+type DropdownState<T> = {
+ disabled: boolean;
+ placeholder?: string;
+ options: DropdownOption<T>[];
+};
diff --git a/packages/pieces/community/toggl-track/src/lib/common/models.ts b/packages/pieces/community/toggl-track/src/lib/common/models.ts
new file mode 100644
index 00000000000..7789d734995
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/common/models.ts
@@ -0,0 +1,416 @@
+import { isNil } from '@activepieces/pieces-framework';
+import { TwoOrganizationUser } from './client';
+
+function client(item: TwoClient): NormalizedClient {
+ return {
+ id: item.id,
+ wid: item.workspace_id,
+ name: item.name,
+ archived: !item.active,
+ at: item.updated_at ?? item.created_at,
+ creator_id: item.toggl_user_id ?? null,
+ notes: null,
+ external_reference: null,
+ };
+}
+
+function tag(item: TwoTag): NormalizedTag {
+ return {
+ id: item.id,
+ workspace_id: item.workspace_id,
+ name: item.name,
+ at: item.updated_at ?? item.created_at,
+ creator_id: null,
+ deleted_at: item.deleted_at ?? null,
+ };
+}
+
+function project(item: TwoProject): NormalizedProject {
+ const estimatedMinutes = item.estimated_mins ?? null;
+ const trackedSeconds = item.total_tracked_secs ?? null;
+ return {
+ id: item.id,
+ workspace_id: item.workspace_id,
+ client_id: item.client_id ?? null,
+ client_name: item.client?.name ?? null,
+ name: item.name,
+ is_private: item.private,
+ active: isNil(item.archived_at),
+ status: isNil(item.archived_at) ? 'active' : 'archived',
+ billable: item.billable,
+ template: item.is_template,
+ color: item.color ?? null,
+ auto_estimates: item.auto_compute_estimates,
+ estimated_hours: isNil(estimatedMinutes) ? null : estimatedMinutes / 60,
+ estimated_seconds: isNil(estimatedMinutes) ? null : estimatedMinutes * 60,
+ actual_seconds: trackedSeconds,
+ actual_hours: isNil(trackedSeconds) ? null : trackedSeconds / 3600,
+ rate: null,
+ currency: item.fixed_fee?.currency ?? null,
+ fixed_fee: item.fixed_fee?.amount ?? null,
+ start_date: item.start_date ?? null,
+ end_date: item.end_date ?? null,
+ pinned: item.pinned,
+ created_at: item.created_at,
+ at: item.updated_at ?? item.created_at,
+ };
+}
+
+function task(item: TwoTask): NormalizedTask {
+ const estimatedMinutes = item.estimated_mins ?? null;
+ return {
+ id: item.id,
+ name: item.name,
+ workspace_id: item.workspace_id,
+ project_id: item.project_id ?? null,
+ project_name: item.project?.name ?? null,
+ client_name: item.client?.name ?? null,
+ user_id: item.toggl_user_id ?? null,
+ active: isNil(item.archived_at),
+ estimated_seconds: isNil(estimatedMinutes) ? null : estimatedMinutes * 60,
+ tracked_seconds: item.total_tracked_time ?? null,
+ recurring: item.is_recurring_series ?? false,
+ external_reference: null,
+ at: item.updated_at ?? item.created_at,
+ };
+}
+
+function timeEntry({
+ item,
+ running,
+}: {
+ item: TwoTimeEntry;
+ running: boolean;
+}): NormalizedTimeEntry {
+ const start = item.start ?? null;
+ const startMs = isNil(start) ? null : new Date(start).getTime();
+ const isRunning = running || (isNil(item.duration) && !isNil(start));
+ const duration = isRunning ? -1 : item.duration ?? null;
+ const stop =
+ !isRunning && !isNil(startMs) && !isNil(item.duration)
+ ? new Date(startMs + item.duration * 1000).toISOString()
+ : null;
+ return {
+ id: item.id,
+ workspace_id: item.workspace_id,
+ project_id: item.project_id ?? null,
+ task_id: item.task_id ?? null,
+ user_id: item.toggl_user_id,
+ description: item.description ?? null,
+ start,
+ stop,
+ duration,
+ billable: item.billable ?? false,
+ tags: (item.tags ?? []).map((entryTag) => entryTag.name),
+ tag_ids: item.tag_ids ?? (item.tags ?? []).map((entryTag) => entryTag.id),
+ at: item.updated_at ?? item.created_at,
+ };
+}
+
+function user({
+ item,
+ workspaceId,
+}: {
+ item: TwoOrganizationUser;
+ workspaceId: number;
+}): NormalizedUser {
+ const membership = item.workspaces.find(
+ (workspace) => workspace.id === workspaceId
+ );
+ return {
+ id: membership?.workspace_user_id ?? item.id,
+ user_id: item.user_account_id,
+ workspace_id: workspaceId,
+ name: item.name,
+ email: item.email,
+ active: item.active,
+ inactive: !item.active,
+ admin: null,
+ role: null,
+ timezone: null,
+ at: item.updated_at ?? item.created_at ?? null,
+ };
+}
+
+function reportRow(item: TwoTimeEntry): NormalizedReportRow {
+ const entry = timeEntry({ item, running: false });
+ return {
+ user_id: entry.user_id,
+ username: null,
+ project_id: entry.project_id,
+ project_name: null,
+ client_name: null,
+ task_id: entry.task_id,
+ task_name: null,
+ description: entry.description,
+ billable: entry.billable,
+ tag_ids: entry.tag_ids,
+ tag_names: entry.tags,
+ row_number: null,
+ time_entries: [
+ {
+ id: entry.id,
+ seconds: isNil(entry.duration) || entry.duration < 0 ? null : entry.duration,
+ start: entry.start,
+ stop: entry.stop,
+ at: entry.at,
+ },
+ ],
+ };
+}
+
+function classicWorkspace(
+ workspace: Record<string, unknown>
+): Record<string, unknown> {
+ return Object.fromEntries(
+ Object.entries(workspace).filter(
+ ([key]) => key !== 'api_token' && key !== 'ical_url'
+ )
+ );
+}
+
+function twoWorkspace({
+ id,
+ name,
+ organizationId,
+ currency,
+}: {
+ id: number;
+ name: string | null;
+ organizationId: number;
+ currency: string | null;
+}): Record<string, unknown> {
+ return {
+ id,
+ name,
+ organization_id: organizationId,
+ role: null,
+ admin: null,
+ premium: null,
+ default_currency: currency,
+ default_hourly_rate: null,
+ active_project_count: null,
+ logo_url: null,
+ last_modified: null,
+ at: null,
+ };
+}
+
+function isTracked(item: TwoTimeEntry): boolean {
+ return !isNil(item.start);
+}
+
+function isTimeEntry(value: unknown): value is TwoTimeEntry {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ 'id' in value &&
+ typeof value.id === 'number'
+ );
+}
+
+export const togglModels = {
+ client,
+ tag,
+ project,
+ task,
+ timeEntry,
+ user,
+ reportRow,
+ classicWorkspace,
+ twoWorkspace,
+ isTracked,
+ isTimeEntry,
+};
+
+type Lite = { id: number; name: string };
+
+export type TwoClient = {
+ id: number;
+ workspace_id: number;
+ name: string;
+ active: boolean;
+ toggl_user_id?: number;
+ created_at: string;
+ updated_at?: string;
+};
+
+export type TwoTag = {
+ id: number;
+ workspace_id: number;
+ name: string;
+ color?: string | null;
+ created_at: string;
+ updated_at?: string;
+ deleted_at?: string | null;
+};
+
+export type TwoProject = {
+ id: number;
+ workspace_id: number;
+ name: string;
+ private: boolean;
+ billable: boolean;
+ is_template: boolean;
+ auto_compute_estimates: boolean;
+ pinned: boolean;
+ client_id?: number | null;
+ client?: Lite | null;
+ color?: string | null;
+ estimated_mins?: number | null;
+ total_tracked_secs?: number | null;
+ fixed_fee?: { amount: number; currency: string } | null;
+ start_date?: string | null;
+ end_date?: string | null;
+ archived_at?: string | null;
+ created_at: string;
+ updated_at?: string;
+};
+
+export type TwoTask = {
+ id: number;
+ workspace_id: number;
+ name: string;
+ project_id?: number | null;
+ project?: Lite | null;
+ client?: Lite | null;
+ toggl_user_id?: number;
+ estimated_mins?: number | null;
+ total_tracked_time?: number | null;
+ is_recurring_series?: boolean;
+ archived_at?: string | null;
+ created_at: string;
+ updated_at?: string;
+};
+
+export type TwoTimeEntry = {
+ id: number;
+ workspace_id: number;
+ toggl_user_id: number;
+ project_id?: number | null;
+ task_id?: number | null;
+ description?: string | null;
+ start?: string | null;
+ planned_start?: string | null;
+ duration?: number | null;
+ billable?: boolean;
+ tags?: Lite[] | null;
+ tag_ids?: number[] | null;
+ created_at: string;
+ updated_at?: string;
+};
+
+export type NormalizedClient = {
+ id: number;
+ wid: number;
+ name: string;
+ archived: boolean;
+ at: string;
+ creator_id: number | null;
+ notes: string | null;
+ external_reference: string | null;
+};
+
+export type NormalizedTag = {
+ id: number;
+ workspace_id: number;
+ name: string;
+ at: string;
+ creator_id: number | null;
+ deleted_at: string | null;
+};
+
+export type NormalizedProject = {
+ id: number;
+ workspace_id: number;
+ client_id: number | null;
+ client_name: string | null;
+ name: string;
+ is_private: boolean;
+ active: boolean;
+ status: string;
+ billable: boolean;
+ template: boolean;
+ color: string | null;
+ auto_estimates: boolean;
+ estimated_hours: number | null;
+ estimated_seconds: number | null;
+ actual_seconds: number | null;
+ actual_hours: number | null;
+ rate: number | null;
+ currency: string | null;
+ fixed_fee: number | null;
+ start_date: string | null;
+ end_date: string | null;
+ pinned: boolean;
+ created_at: string;
+ at: string;
+};
+
+export type NormalizedTask = {
+ id: number;
+ name: string;
+ workspace_id: number;
+ project_id: number | null;
+ project_name: string | null;
+ client_name: string | null;
+ user_id: number | null;
+ active: boolean;
+ estimated_seconds: number | null;
+ tracked_seconds: number | null;
+ recurring: boolean;
+ external_reference: string | null;
+ at: string;
+};
+
+export type NormalizedTimeEntry = {
+ id: number;
+ workspace_id: number;
+ project_id: number | null;
+ task_id: number | null;
+ user_id: number;
+ description: string | null;
+ start: string | null;
+ stop: string | null;
+ duration: number | null;
+ billable: boolean;
+ tags: string[];
+ tag_ids: number[];
+ at: string;
+};
+
+export type NormalizedUser = {
+ id: number;
+ user_id: number;
+ workspace_id: number;
+ name: string;
+ email: string;
+ active: boolean;
+ inactive: boolean;
+ admin: boolean | null;
+ role: string | null;
+ timezone: string | null;
+ at: string | null;
+};
+
+export type NormalizedReportRow = {
+ user_id: number;
+ username: string | null;
+ project_id: number | null;
+ project_name: string | null;
+ client_name: string | null;
+ task_id: number | null;
+ task_name: string | null;
+ description: string | null;
+ billable: boolean;
+ tag_ids: number[];
+ tag_names: string[];
+ row_number: number | null;
+ time_entries: {
+ id: number;
+ seconds: number | null;
+ start: string | null;
+ stop: string | null;
+ at: string;
+ }[];
+};
diff --git a/packages/pieces/community/toggl-track/src/lib/common/time-entries.ts b/packages/pieces/community/toggl-track/src/lib/common/time-entries.ts
new file mode 100644
index 00000000000..7b520d05373
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/common/time-entries.ts
@@ -0,0 +1,96 @@
+import { isNil } from '@activepieces/pieces-framework';
+import { TogglTwoAuthValue, togglApi } from './client';
+import { NormalizedTimeEntry, togglModels, TwoTimeEntry } from './models';
+
+async function twoStart({
+ auth,
+ workspaceId,
+ start,
+ description,
+ projectId,
+ taskId,
+ tags,
+ billable,
+}: {
+ auth: TogglTwoAuthValue;
+ workspaceId: number;
+ start: string;
+ description: string | undefined;
+ projectId: number | undefined;
+ taskId: number | undefined;
+ tags: string[] | undefined;
+ billable: boolean | undefined;
+}): Promise<NormalizedTimeEntry> {
+ const tagIds = await togglApi.resolveTwoTagIds({
+ auth,
+ workspaceId,
+ names: tags,
+ });
+ const started = await togglApi.request<TwoTimeEntry>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: togglApi.twoWorkspacePath({
+ auth,
+ workspaceId,
+ path: '/tracking/start',
+ }),
+ body: {
+ type: 'activity',
+ start,
+ ...(description ? { description } : {}),
+ ...(isNil(projectId) ? {} : { project_id: projectId }),
+ ...(isNil(taskId) ? {} : { task_id: taskId }),
+ ...(isNil(tagIds) ? {} : { tag_ids: tagIds }),
+ ...(isNil(billable) ? {} : { billable }),
+ },
+ });
+ return togglModels.timeEntry({ item: started, running: true });
+}
+
+async function twoCurrent({
+ auth,
+ workspaceId,
+}: {
+ auth: TogglTwoAuthValue;
+ workspaceId: number;
+}): Promise<NormalizedTimeEntry | null> {
+ const body = await togglApi.request<unknown>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: togglApi.twoWorkspacePath({
+ auth,
+ workspaceId,
+ path: '/tracking/current',
+ }),
+ });
+ if (!togglModels.isTimeEntry(body)) {
+ return null;
+ }
+ return togglModels.timeEntry({ item: body, running: true });
+}
+
+async function twoStop({
+ auth,
+ workspaceId,
+}: {
+ auth: TogglTwoAuthValue;
+ workspaceId: number;
+}): Promise<NormalizedTimeEntry> {
+ const stopped = await togglApi.request<TwoTimeEntry>({
+ auth,
+ method: togglApi.HttpMethod.POST,
+ path: togglApi.twoWorkspacePath({
+ auth,
+ workspaceId,
+ path: '/tracking/stop',
+ }),
+ body: { end: new Date().toISOString() },
+ });
+ return togglModels.timeEntry({ item: stopped, running: false });
+}
+
+export const togglTimeEntries = {
+ twoStart,
+ twoCurrent,
+ twoStop,
+};
diff --git a/packages/pieces/community/toggl-track/src/lib/output-schemas.ts b/packages/pieces/community/toggl-track/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..08eef27008a
--- /dev/null
+++ b/packages/pieces/community/toggl-track/src/lib/output-schemas.ts
@@ -0,0 +1,366 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+const clientFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Client ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'wid', label: 'Workspace ID', format: 'number' },
+ { key: 'archived', label: 'Archived', format: 'boolean' },
+ { key: 'notes', label: 'Notes' },
+ { key: 'external_reference', label: 'External Reference' },
+ { key: 'creator_id', label: 'Creator ID', format: 'number' },
+ { key: 'at', label: 'Last Updated', format: 'datetime' },
+];
+
+const tagFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Tag ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'workspace_id', label: 'Workspace ID', format: 'number' },
+ { key: 'creator_id', label: 'Creator ID', format: 'number' },
+ { key: 'deleted_at', label: 'Deleted At', format: 'datetime' },
+ { key: 'at', label: 'Last Updated', format: 'datetime' },
+];
+
+const projectFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Project ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'workspace_id', label: 'Workspace ID', format: 'number' },
+ { key: 'client_id', label: 'Client ID', format: 'number' },
+ { key: 'client_name', label: 'Client Name' },
+ { key: 'status', label: 'Status' },
+ { key: 'active', label: 'Active', format: 'boolean' },
+ { key: 'is_private', label: 'Private', format: 'boolean' },
+ { key: 'billable', label: 'Billable', format: 'boolean' },
+ { key: 'template', label: 'Template', format: 'boolean' },
+ { key: 'pinned', label: 'Pinned', format: 'boolean' },
+ { key: 'color', label: 'Color' },
+ { key: 'estimated_hours', label: 'Estimated Hours', format: 'number' },
+ { key: 'actual_hours', label: 'Tracked Hours', format: 'number' },
+ { key: 'actual_seconds', label: 'Tracked Seconds', format: 'number' },
+ { key: 'rate', label: 'Hourly Rate', format: 'number' },
+ { key: 'fixed_fee', label: 'Fixed Fee', format: 'number' },
+ { key: 'currency', label: 'Currency' },
+ { key: 'start_date', label: 'Start Date', format: 'date' },
+ { key: 'end_date', label: 'End Date', format: 'date' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'at', label: 'Last Updated', format: 'datetime' },
+];
+
+const taskFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Task ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'workspace_id', label: 'Workspace ID', format: 'number' },
+ { key: 'project_id', label: 'Project ID', format: 'number' },
+ { key: 'project_name', label: 'Project Name' },
+ { key: 'user_id', label: 'User ID', format: 'number' },
+ { key: 'active', label: 'Active', format: 'boolean' },
+ { key: 'estimated_seconds', label: 'Estimated Seconds', format: 'number' },
+ { key: 'tracked_seconds', label: 'Tracked Seconds', format: 'number' },
+ { key: 'recurring', label: 'Recurring', format: 'boolean' },
+ { key: 'at', label: 'Last Updated', format: 'datetime' },
+];
+
+const timeEntryFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Time Entry ID', format: 'number' },
+ { key: 'description', label: 'Description' },
+ { key: 'start', label: 'Start', format: 'datetime' },
+ { key: 'stop', label: 'Stop', format: 'datetime' },
+ {
+ key: 'duration',
+ label: 'Duration (Seconds)',
+ format: 'number',
+ description:
+ 'Duration in seconds. -1 while the timer is running.',
+ },
+ { key: 'billable', label: 'Billable', format: 'boolean' },
+ { key: 'workspace_id', label: 'Workspace ID', format: 'number' },
+ { key: 'project_id', label: 'Project ID', format: 'number' },
+ { key: 'task_id', label: 'Task ID', format: 'number' },
+ { key: 'user_id', label: 'User ID', format: 'number' },
+ { key: 'tags', label: 'Tags' },
+ { key: 'tag_ids', label: 'Tag IDs' },
+ { key: 'at', label: 'Last Updated', format: 'datetime' },
+];
+
+const userFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Workspace User ID', format: 'number' },
+ { key: 'user_id', label: 'User ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'workspace_id', label: 'Workspace ID', format: 'number' },
+ { key: 'active', label: 'Active', format: 'boolean' },
+ { key: 'admin', label: 'Admin', format: 'boolean' },
+ { key: 'role', label: 'Role' },
+ { key: 'timezone', label: 'Timezone' },
+ { key: 'at', label: 'Last Updated', format: 'datetime' },
+];
+
+const workspaceFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Workspace ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'organization_id', label: 'Organization ID', format: 'number' },
+ { key: 'role', label: 'Role' },
+ { key: 'admin', label: 'Admin', format: 'boolean' },
+ { key: 'premium', label: 'Premium', format: 'boolean' },
+ { key: 'default_currency', label: 'Default Currency' },
+ { key: 'default_hourly_rate', label: 'Default Hourly Rate', format: 'number' },
+ { key: 'active_project_count', label: 'Active Projects', format: 'number' },
+ { key: 'logo_url', label: 'Logo', format: 'image' },
+ { key: 'last_modified', label: 'Last Modified', format: 'datetime' },
+ { key: 'at', label: 'Last Updated', format: 'datetime' },
+];
+
+const reportEntryFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Time Entry ID', format: 'number' },
+ { key: 'seconds', label: 'Seconds', format: 'number' },
+ { key: 'start', label: 'Start', format: 'datetime' },
+ { key: 'stop', label: 'Stop', format: 'datetime' },
+ { key: 'at', label: 'Last Updated', format: 'datetime' },
+];
+
+const reportRowFields: OutputSchema['fields'] = [
+ { key: 'description', label: 'Description' },
+ { key: 'user_id', label: 'User ID', format: 'number' },
+ { key: 'username', label: 'User Name' },
+ { key: 'project_id', label: 'Project ID', format: 'number' },
+ { key: 'project_name', label: 'Project Name' },
+ { key: 'client_name', label: 'Client Name' },
+ { key: 'task_id', label: 'Task ID', format: 'number' },
+ { key: 'task_name', label: 'Task Name' },
+ { key: 'billable', label: 'Billable', format: 'boolean' },
+ { key: 'tag_ids', label: 'Tag IDs' },
+ { key: 'tag_names', label: 'Tag Names' },
+ { key: 'row_number', label: 'Row Number', format: 'number' },
+ {
+ key: 'time_entries',
+ label: 'Time Entries',
+ labelKey: 'start',
+ listItems: reportEntryFields,
+ },
+];
+
+const organizationUserFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Organization User ID', format: 'number' },
+ { key: 'user_id', label: 'User ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'admin', label: 'Admin', format: 'boolean' },
+ { key: 'owner', label: 'Owner', format: 'boolean' },
+ { key: 'inactive', label: 'Inactive', format: 'boolean' },
+ { key: 'joined', label: 'Joined', format: 'boolean' },
+ { key: 'workspace_ids', label: 'Workspace IDs' },
+];
+
+const client: OutputSchema = { fields: clientFields };
+
+const clientList: OutputSchema = {
+ itemLabel: '{name}',
+ fields: [
+ { key: 'clients', label: 'Clients', value: '', listItems: clientFields },
+ ],
+};
+
+const tag: OutputSchema = { fields: tagFields };
+
+const tagList: OutputSchema = {
+ itemLabel: '{name}',
+ fields: [{ key: 'tags', label: 'Tags', value: '', listItems: tagFields }],
+};
+
+const project: OutputSchema = { fields: projectFields };
+
+const projectList: OutputSchema = {
+ itemLabel: '{name}',
+ fields: [
+ { key: 'projects', label: 'Projects', value: '', listItems: projectFields },
+ ],
+};
+
+const task: OutputSchema = { fields: taskFields };
+
+const taskList: OutputSchema = {
+ fields: [
+ { key: 'total_count', label: 'Total Count', format: 'number' },
+ { key: 'page', label: 'Page', format: 'number' },
+ { key: 'per_page', label: 'Per Page', format: 'number' },
+ {
+ key: 'data',
+ label: 'Tasks',
+ labelKey: 'name',
+ listItems: taskFields,
+ },
+ ],
+};
+
+const timeEntry: OutputSchema = { fields: timeEntryFields };
+
+const stoppedTimeEntry: OutputSchema = {
+ fields: [
+ ...timeEntryFields,
+ {
+ key: 'success',
+ label: 'Success',
+ format: 'boolean',
+ description: 'Only present (false) when no time entry was running.',
+ },
+ {
+ key: 'message',
+ label: 'Message',
+ description: 'Only present when no time entry was running.',
+ },
+ ],
+};
+
+const timeEntryList: OutputSchema = {
+ itemLabel: '{description}',
+ fields: [
+ {
+ key: 'time_entries',
+ label: 'Time Entries',
+ value: '',
+ listItems: timeEntryFields,
+ },
+ ],
+};
+
+const userList: OutputSchema = {
+ itemLabel: '{name}',
+ fields: [{ key: 'users', label: 'Users', value: '', listItems: userFields }],
+};
+
+const workspace: OutputSchema = { fields: workspaceFields };
+
+const deleted: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'id', label: 'Deleted ID', format: 'number' },
+ ],
+};
+
+const currentTimeEntry: OutputSchema = {
+ fields: [
+ {
+ key: 'running',
+ label: 'Running',
+ format: 'boolean',
+ description: 'False when no time entry is running; the other fields are then absent.',
+ },
+ ...timeEntryFields,
+ ],
+};
+
+const detailedReport: OutputSchema = {
+ fields: [
+ {
+ key: 'rows',
+ label: 'Rows',
+ labelKey: 'description',
+ listItems: reportRowFields,
+ },
+ { key: 'has_more', label: 'Has More', format: 'boolean' },
+ {
+ key: 'next_cursor',
+ label: 'Next Page Cursor',
+ description: 'Pass back as Next Page Cursor to get the next page.',
+ },
+ ],
+};
+
+const invitation: OutputSchema = {
+ fields: [
+ { key: 'invitations', label: 'Invitations' },
+ { key: 'messages', label: 'Messages' },
+ ],
+};
+
+const workspaceList: OutputSchema = {
+ itemLabel: '{name}',
+ fields: [
+ {
+ key: 'workspaces',
+ label: 'Workspaces',
+ value: '',
+ listItems: workspaceFields,
+ },
+ ],
+};
+
+const organizationUserList: OutputSchema = {
+ itemLabel: '{name}',
+ fields: [
+ {
+ key: 'users',
+ label: 'Users',
+ value: '',
+ listItems: organizationUserFields,
+ },
+ ],
+};
+
+const group: OutputSchema = {
+ fields: [
+ { key: 'group_id', label: 'Group ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'workspace_ids', label: 'Workspace IDs' },
+ { key: 'user_ids', label: 'Member IDs' },
+ { key: 'at', label: 'Last Updated', format: 'datetime' },
+ ],
+};
+
+const projectUser: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Project User ID', format: 'number' },
+ { key: 'project_id', label: 'Project ID', format: 'number' },
+ { key: 'user_id', label: 'User ID', format: 'number' },
+ { key: 'workspace_id', label: 'Workspace ID', format: 'number' },
+ { key: 'manager', label: 'Manager', format: 'boolean' },
+ { key: 'rate', label: 'Hourly Rate', format: 'number' },
+ { key: 'at', label: 'Last Updated', format: 'datetime' },
+ ],
+};
+
+const timeSummary: OutputSchema = {
+ fields: [
+ { key: 'start_date', label: 'Start Date', format: 'date' },
+ { key: 'end_date', label: 'End Date', format: 'date' },
+ { key: 'group_by', label: 'Grouped By' },
+ { key: 'total_hours', label: 'Total Hours', format: 'number' },
+ { key: 'total_seconds', label: 'Total Seconds', format: 'number' },
+ {
+ key: 'groups',
+ label: 'Groups',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Name' },
+ { key: 'id', label: 'ID', format: 'number' },
+ { key: 'hours', label: 'Hours', format: 'number' },
+ { key: 'seconds', label: 'Seconds', format: 'number' },
+ { key: 'entry_count', label: 'Entries', format: 'number' },
+ ],
+ },
+ ],
+};
+
+export const togglOutputSchemas = {
+ timeSummary,
+ deleted,
+ currentTimeEntry,
+ detailedReport,
+ invitation,
+ workspaceList,
+ organizationUserList,
+ group,
+ projectUser,
+ client,
+ clientList,
+ tag,
+ tagList,
+ project,
+ projectList,
+ task,
+ taskList,
+ timeEntry,
+ stoppedTimeEntry,
+ timeEntryList,
+ userList,
+ workspace,
+};
diff --git a/packages/pieces/community/toggl-track/src/lib/triggers/new-client.ts b/packages/pieces/community/toggl-track/src/lib/triggers/new-client.ts
index fe9712b8554..50022891871 100644
--- a/packages/pieces/community/toggl-track/src/lib/triggers/new-client.ts
+++ b/packages/pieces/community/toggl-track/src/lib/triggers/new-client.ts
@@ -4,7 +4,8 @@ import {
TriggerStrategy,
} from '@activepieces/pieces-framework';
import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import { togglTrackAuth } from '../auth';
+import { togglApi } from '../common/client';
import { togglCommon } from '../common';
import {
generateTogglWebhookInstructions,
@@ -18,7 +19,7 @@ export const newClient = createTrigger({
displayName: 'New Client',
description: 'Fires when a new client is created in a workspace.',
aiMetadata: {
- description: 'Fires when a new client is created in the configured Toggl Track workspace, delivering the created client (id, name, notes, workspace). Delivered via a Toggl webhook the user must set up manually.',
+ description: 'Fires when a client is created in the workspace, delivering the client. Needs a webhook created manually in Toggl. Classic only.',
},
props: {
workspace_id: togglCommon.workspace_id,
@@ -49,11 +50,13 @@ export const newClient = createTrigger({
async onEnable(context) {
- // Manual setup - no programmatic registration needed
+ if (togglApi.isTwo(context.auth)) {
+ throw togglApi.classicOnlyError(WEBHOOK_TRIGGER_NAME);
+ }
},
- async onDisable(context) {
- // Manual setup - users manage webhooks in Toggl Track UI
+ async onDisable() {
+ return;
},
async run(context) {
@@ -91,3 +94,5 @@ export const newClient = createTrigger({
return [payload];
},
});
+
+const WEBHOOK_TRIGGER_NAME = 'The New Client trigger';
diff --git a/packages/pieces/community/toggl-track/src/lib/triggers/new-project.ts b/packages/pieces/community/toggl-track/src/lib/triggers/new-project.ts
index 9e2be5ad2e0..fe6ca18f542 100644
--- a/packages/pieces/community/toggl-track/src/lib/triggers/new-project.ts
+++ b/packages/pieces/community/toggl-track/src/lib/triggers/new-project.ts
@@ -4,7 +4,8 @@ import {
TriggerStrategy,
} from '@activepieces/pieces-framework';
import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import { togglTrackAuth } from '../auth';
+import { togglApi } from '../common/client';
import { togglCommon } from '../common';
import {
generateTogglWebhookInstructions,
@@ -18,7 +19,7 @@ export const newProject = createTrigger({
displayName: 'New Project',
description: 'Fires when a new project is added.',
aiMetadata: {
- description: 'Fires when a new project is created in the configured Toggl Track workspace, delivering the created project (id, name, client association, billing/color settings). Delivered via a Toggl webhook the user must set up manually.',
+ description: 'Fires when a project is created in the workspace, delivering the project. Needs a webhook created manually in Toggl. Classic only.',
},
props: {
workspace_id: togglCommon.workspace_id,
@@ -63,11 +64,13 @@ export const newProject = createTrigger({
type: TriggerStrategy.WEBHOOK,
async onEnable(context) {
- // Manual setup - no programmatic registration needed
+ if (togglApi.isTwo(context.auth)) {
+ throw togglApi.classicOnlyError(WEBHOOK_TRIGGER_NAME);
+ }
},
- async onDisable(context) {
- // Manual setup - users manage webhooks in Toggl Track UI
+ async onDisable() {
+ return;
},
async run(context) {
@@ -99,3 +102,5 @@ export const newProject = createTrigger({
return [payload];
},
});
+
+const WEBHOOK_TRIGGER_NAME = 'The New Project trigger';
diff --git a/packages/pieces/community/toggl-track/src/lib/triggers/new-tag.ts b/packages/pieces/community/toggl-track/src/lib/triggers/new-tag.ts
index 7f2c37560d7..aaeea512e40 100644
--- a/packages/pieces/community/toggl-track/src/lib/triggers/new-tag.ts
+++ b/packages/pieces/community/toggl-track/src/lib/triggers/new-tag.ts
@@ -4,7 +4,8 @@ import {
TriggerStrategy,
} from '@activepieces/pieces-framework';
import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import { togglTrackAuth } from '../auth';
+import { togglApi } from '../common/client';
import { togglCommon } from '../common';
import {
generateTogglWebhookInstructions,
@@ -18,7 +19,7 @@ export const newTag = createTrigger({
displayName: 'New Tag',
description: 'Triggers when a new tag is created',
aiMetadata: {
- description: 'Fires when a new tag is created in the configured Toggl Track workspace, delivering the created tag (id, name, workspace). Delivered via a Toggl webhook the user must set up manually.',
+ description: 'Fires when a tag is created in the workspace, delivering the tag. Needs a webhook created manually in Toggl. Classic only.',
},
props: {
workspace_id: togglCommon.workspace_id,
@@ -46,11 +47,13 @@ export const newTag = createTrigger({
type: TriggerStrategy.WEBHOOK,
async onEnable(context) {
- // Manual setup - no programmatic registration needed
+ if (togglApi.isTwo(context.auth)) {
+ throw togglApi.classicOnlyError(WEBHOOK_TRIGGER_NAME);
+ }
},
- async onDisable(context) {
- // Manual setup - users manage webhooks in Toggl Track UI
+ async onDisable() {
+ return;
},
async run(context) {
@@ -82,3 +85,5 @@ export const newTag = createTrigger({
return [payload];
},
});
+
+const WEBHOOK_TRIGGER_NAME = 'The New Tag trigger';
diff --git a/packages/pieces/community/toggl-track/src/lib/triggers/new-task.ts b/packages/pieces/community/toggl-track/src/lib/triggers/new-task.ts
index f6d59cf8b87..0c2fde90639 100644
--- a/packages/pieces/community/toggl-track/src/lib/triggers/new-task.ts
+++ b/packages/pieces/community/toggl-track/src/lib/triggers/new-task.ts
@@ -4,7 +4,8 @@ import {
TriggerStrategy,
} from '@activepieces/pieces-framework';
import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import { togglTrackAuth } from '../auth';
+import { togglApi } from '../common/client';
import { togglCommon } from '../common';
import {
generateTogglWebhookInstructions,
@@ -18,7 +19,7 @@ export const newTask = createTrigger({
displayName: 'New Task',
description: 'Fires when a new task is created.',
aiMetadata: {
- description: 'Fires when a new task is created in the configured Toggl Track workspace, delivering the created task (id, name, project association, estimated time). Can be narrowed to a single project via the optional project filter. Delivered via a Toggl webhook the user must set up manually.',
+ description: 'Fires when a task is created in the workspace, delivering the task; an optional filter narrows it to one project. Needs a webhook created manually in Toggl. Classic only.',
},
props: {
workspace_id: togglCommon.workspace_id,
@@ -54,11 +55,13 @@ export const newTask = createTrigger({
type: TriggerStrategy.WEBHOOK,
async onEnable(context) {
- // Manual setup - no programmatic registration needed
+ if (togglApi.isTwo(context.auth)) {
+ throw togglApi.classicOnlyError(WEBHOOK_TRIGGER_NAME);
+ }
},
- async onDisable(context) {
- // Manual setup - users manage webhooks in Toggl Track UI
+ async onDisable() {
+ return;
},
async run(context) {
@@ -96,3 +99,5 @@ export const newTask = createTrigger({
return [payload];
},
});
+
+const WEBHOOK_TRIGGER_NAME = 'The New Task trigger';
diff --git a/packages/pieces/community/toggl-track/src/lib/triggers/new-time-entry-started.ts b/packages/pieces/community/toggl-track/src/lib/triggers/new-time-entry-started.ts
index 0a3e441c395..1c2a9ef99db 100644
--- a/packages/pieces/community/toggl-track/src/lib/triggers/new-time-entry-started.ts
+++ b/packages/pieces/community/toggl-track/src/lib/triggers/new-time-entry-started.ts
@@ -1,45 +1,64 @@
import {
AppConnectionValueForAuthProperty,
createTrigger,
+ isNil,
TriggerStrategy,
} from '@activepieces/pieces-framework';
-import { togglTrackAuth } from '../..';
-import { togglCommon } from '../common';
import {
- HttpMethod,
- httpClient,
DedupeStrategy,
Polling,
pollingHelper,
} from '@activepieces/pieces-common';
+import { togglTrackAuth } from '../auth';
+import { togglCommon } from '../common';
+import { togglApi } from '../common/client';
+import { togglTimeEntries } from '../common/time-entries';
+import { togglOutputSchemas } from '../output-schemas';
-const polling: Polling<AppConnectionValueForAuthProperty<typeof togglTrackAuth>, Record<string, any>> = {
+const polling: Polling<
+ AppConnectionValueForAuthProperty<typeof togglTrackAuth>,
+ { workspace_id: unknown }
+> = {
strategy: DedupeStrategy.TIMEBASED,
items: async ({ auth, propsValue }) => {
- const authHeader = `Basic ${Buffer.from(`${auth.secret_text}:api_token`).toString('base64')}`;
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: 'https://api.track.toggl.com/api/v9/me/time_entries',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': authHeader,
- },
+ const workspaceId = togglApi.optionalId({
+ value: propsValue.workspace_id,
+ label: 'Workspace',
});
- const timeEntries = response.body as any[];
-
- const runningEntries = timeEntries.filter((entry: any) => {
- const isRunning = entry.duration < 0;
- const isInWorkspace = !propsValue['workspace_id'] ||
- entry.workspace_id === propsValue['workspace_id'];
- return isRunning && isInWorkspace;
- });
+ if (togglApi.isTwo(auth)) {
+ const targetWorkspaceId =
+ workspaceId ?? (await togglApi.twoSettings(auth)).current_workspace_id;
+ const running = await togglTimeEntries.twoCurrent({
+ auth,
+ workspaceId: targetWorkspaceId,
+ });
+ if (!running || isNil(running.start)) {
+ return [];
+ }
+ return [
+ {
+ epochMilliSeconds: new Date(running.start).getTime(),
+ data: running,
+ },
+ ];
+ }
- return runningEntries.map((entry: any) => ({
- epochMilliSeconds: new Date(entry.start).getTime(),
- data: entry,
- }));
+ const timeEntries = await togglApi.request<RunningEntry[] | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: '/me/time_entries',
+ });
+ return (timeEntries ?? [])
+ .filter(
+ (entry) =>
+ entry.duration < 0 &&
+ (isNil(workspaceId) || entry.workspace_id === workspaceId)
+ )
+ .map((entry) => ({
+ epochMilliSeconds: new Date(entry.start).getTime(),
+ data: entry,
+ }));
},
};
@@ -48,13 +67,16 @@ export const newTimeEntryStarted = createTrigger({
name: 'new_time_entry_started',
classification: 'READ',
displayName: 'New Time Entry Started',
- description: 'Fires when a new time entry is started and is currently running.',
+ description:
+ 'Fires when a new time entry is started and is currently running.',
aiMetadata: {
- description: 'Fires when a time entry is started and is currently running (open-ended, negative duration) for the authenticated user, delivering the running entry. Polls Toggl periodically and emits newly started running entries, optionally scoped to the configured workspace.',
+ description:
+ 'Fires when a running timer starts for the connected user, delivering the running entry. Polls Toggl; on Toggl 2.0 a timer started and stopped between two polls is missed.',
},
props: {
workspace_id: togglCommon.workspace_id,
},
+ outputSchema: togglOutputSchemas.timeEntry,
sampleData: {
id: 1234567891,
workspace_id: 987654,
@@ -63,46 +85,35 @@ export const newTimeEntryStarted = createTrigger({
billable: false,
start: '2025-08-29T11:15:00Z',
stop: null,
- duration: -1734567890,
+ duration: -1756466100,
description: 'Working on API integration',
tags: ['development', 'api'],
+ tag_ids: [111, 222],
at: '2025-08-29T11:15:00+00:00',
user_id: 6,
- created_with: 'Toggl Track',
},
type: TriggerStrategy.POLLING,
async onEnable(context) {
- await pollingHelper.onEnable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ await pollingHelper.onEnable(polling, context);
},
async onDisable(context) {
- await pollingHelper.onDisable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ await pollingHelper.onDisable(polling, context);
},
async run(context) {
- return await pollingHelper.poll(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- files: context.files,
- });
+ return await pollingHelper.poll(polling, context);
},
async test(context) {
- return await pollingHelper.test(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- files: context.files,
- });
+ return await pollingHelper.test(polling, context);
},
});
+
+type RunningEntry = {
+ id: number;
+ workspace_id: number;
+ duration: number;
+ start: string;
+};
diff --git a/packages/pieces/community/toggl-track/src/lib/triggers/new-time-entry.ts b/packages/pieces/community/toggl-track/src/lib/triggers/new-time-entry.ts
index 24f3fc32d72..2ba24aa563b 100644
--- a/packages/pieces/community/toggl-track/src/lib/triggers/new-time-entry.ts
+++ b/packages/pieces/community/toggl-track/src/lib/triggers/new-time-entry.ts
@@ -4,7 +4,8 @@ import {
TriggerStrategy,
} from '@activepieces/pieces-framework';
import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { togglTrackAuth } from '../..';
+import { togglTrackAuth } from '../auth';
+import { togglApi } from '../common/client';
import { togglCommon } from '../common';
import {
generateTogglWebhookInstructions,
@@ -19,12 +20,12 @@ export const newTimeEntry = createTrigger({
description:
'Fires when a new time entry is added (with optional project/task filter).',
aiMetadata: {
- description: 'Fires when a new time entry is created in the configured Toggl Track workspace, delivering the entry (start/stop, duration, description, tags, project/task, billable). Can be narrowed to a specific project and/or task via the optional filters. Delivered via a Toggl webhook the user must set up manually.',
+ description: 'Fires when a time entry is created in the workspace, delivering the entry; optional filters narrow it to one project or task. Needs a webhook created manually in Toggl. Classic only.',
},
props: {
workspace_id: togglCommon.workspace_id,
optional_project_id: togglCommon.optional_project_id,
- task_id: togglCommon.optional_task_id,
+ task_id: togglCommon.taskDropdown({ projectField: 'optional_project_id' }),
setupInstructions: Property.MarkDown({
value: generateTogglWebhookInstructions(
TOGGL_WEBHOOK_EVENTS.TIME_ENTRY_CREATED,
@@ -61,11 +62,13 @@ export const newTimeEntry = createTrigger({
type: TriggerStrategy.WEBHOOK,
async onEnable(context) {
- // Manual setup - no programmatic registration needed
+ if (togglApi.isTwo(context.auth)) {
+ throw togglApi.classicOnlyError(WEBHOOK_TRIGGER_NAME);
+ }
},
- async onDisable(context) {
- // Manual setup - users manage webhooks in Toggl Track UI
+ async onDisable() {
+ return;
},
async run(context) {
@@ -109,3 +112,5 @@ export const newTimeEntry = createTrigger({
return [payload];
},
});
+
+const WEBHOOK_TRIGGER_NAME = 'The New Time Entry trigger';
diff --git a/packages/pieces/community/toggl-track/src/lib/triggers/new-workspace.ts b/packages/pieces/community/toggl-track/src/lib/triggers/new-workspace.ts
index a8cf3d540af..9c37b7202fd 100644
--- a/packages/pieces/community/toggl-track/src/lib/triggers/new-workspace.ts
+++ b/packages/pieces/community/toggl-track/src/lib/triggers/new-workspace.ts
@@ -3,34 +3,35 @@ import {
createTrigger,
TriggerStrategy,
} from '@activepieces/pieces-framework';
-import { togglTrackAuth } from '../..';
import {
- HttpMethod,
- httpClient,
DedupeStrategy,
Polling,
pollingHelper,
} from '@activepieces/pieces-common';
+import { togglTrackAuth } from '../auth';
+import { togglApi } from '../common/client';
+import { togglModels } from '../common/models';
+import { togglOutputSchemas } from '../output-schemas';
-const polling: Polling<AppConnectionValueForAuthProperty<typeof togglTrackAuth>, Record<string, never>> = {
+const polling: Polling<
+ AppConnectionValueForAuthProperty<typeof togglTrackAuth>,
+ Record<string, never>
+> = {
strategy: DedupeStrategy.TIMEBASED,
items: async ({ auth }) => {
- const authHeader = `Basic ${Buffer.from(`${auth.secret_text}:api_token`).toString('base64')}`;
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: 'https://api.track.toggl.com/api/v9/workspaces',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': authHeader,
- },
+ if (togglApi.isTwo(auth)) {
+ throw togglApi.classicOnlyError(TRIGGER_NAME);
+ }
+ const workspaces = await togglApi.request<ClassicWorkspace[] | null>({
+ auth,
+ method: togglApi.HttpMethod.GET,
+ path: '/workspaces',
});
-
- const workspaces = response.body as any[];
-
- return workspaces.map((workspace: any) => ({
- epochMilliSeconds: new Date(workspace.at || workspace.last_modified).getTime(),
- data: workspace,
+ return (workspaces ?? []).map((workspace) => ({
+ epochMilliSeconds: new Date(
+ workspace.at ?? workspace.last_modified ?? 0
+ ).getTime(),
+ data: togglModels.classicWorkspace(workspace),
}));
},
};
@@ -40,11 +41,14 @@ export const newWorkspace = createTrigger({
name: 'new_workspace',
classification: 'READ',
displayName: 'New or Updated Workspace',
- description: 'Fires when a workspace is created or updated (Toggl only supports workspace updated events).',
+ description:
+ 'Fires when a workspace is created or updated (Toggl only supports workspace updated events).',
aiMetadata: {
- description: 'Fires when a workspace accessible to the authenticated user is created or modified, delivering the workspace record. Polls Toggl periodically and emits each workspace whose last-modified timestamp is new since the previous poll.',
+ description:
+ 'Fires when a workspace is created or modified, delivering the workspace record (API token removed). Polls Toggl. Classic only.',
},
props: {},
+ outputSchema: togglOutputSchemas.workspace,
sampleData: {
id: 20763798,
organization_id: 20764737,
@@ -69,7 +73,6 @@ export const newWorkspace = createTrigger({
reports_collapse: true,
rounding: 1,
rounding_minutes: 0,
- api_token: '72565784d2250b9ba2f2d61039ba9fee',
at: '2025-09-01T09:23:02+00:00',
logo_url: 'https://assets.track.toggl.com/images/workspace.jpg',
ical_enabled: true,
@@ -79,36 +82,33 @@ export const newWorkspace = createTrigger({
type: TriggerStrategy.POLLING,
async onEnable(context) {
- await pollingHelper.onEnable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ if (togglApi.isTwo(context.auth)) {
+ throw togglApi.classicOnlyError(TRIGGER_NAME);
+ }
+ await pollingHelper.onEnable(polling, context);
},
async onDisable(context) {
- await pollingHelper.onDisable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ await pollingHelper.onDisable(polling, context);
},
async run(context) {
- return await pollingHelper.poll(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- files: context.files,
- });
+ return await pollingHelper.poll(polling, context);
},
async test(context) {
- return await pollingHelper.test(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- files: context.files,
- });
+ return await pollingHelper.test(polling, context);
},
});
+
+const TRIGGER_NAME = 'The New or Updated Workspace trigger';
+
+type ClassicWorkspace = {
+ id: number;
+ name: string;
+ at?: string;
+ last_modified?: string;
+ api_token?: string;
+ ical_url?: string;
+ [key: string]: unknown;
+};
diff --git a/packages/pieces/community/toggl-track/test/agent.test.ts b/packages/pieces/community/toggl-track/test/agent.test.ts
new file mode 100644
index 00000000000..5c25376659f
--- /dev/null
+++ b/packages/pieces/community/toggl-track/test/agent.test.ts
@@ -0,0 +1,161 @@
+import { describe, expect, it } from 'vitest';
+import { AgentProject, togglAgent } from '../src/lib/common/agent';
+import { togglApi } from '../src/lib/common/client';
+import { togglCommon } from '../src/lib/common';
+import { createTimeEntry } from '../src/lib/actions/create-time-entry';
+import { startTimeEntry } from '../src/lib/actions/start-time-entry';
+import { updateTimeEntry } from '../src/lib/actions/update-time-entry';
+import { newTimeEntry } from '../src/lib/triggers/new-time-entry';
+
+const projects: AgentProject[] = [
+ { id: 1, name: 'Website', workspaceId: 10, clientName: 'Acme' },
+ { id: 2, name: 'App', workspaceId: 10, clientName: null },
+ { id: 3, name: 'app', workspaceId: 11, clientName: 'Beta' },
+];
+
+describe('pickProject', () => {
+ it('finds a project by numeric id', () => {
+ expect(togglAgent.pickProject({ projects, reference: '3' }).workspaceId).toBe(11);
+ });
+
+ it('finds a unique name case-insensitively', () => {
+ expect(togglAgent.pickProject({ projects, reference: 'WEBSITE' }).id).toBe(1);
+ });
+
+ it('lists ids when the name is ambiguous', () => {
+ expect(() => togglAgent.pickProject({ projects, reference: 'App' })).toThrow(
+ /2 projects are named "App" \(IDs: 2, 3\)/
+ );
+ });
+
+ it('lists candidates when the name is unknown', () => {
+ expect(() => togglAgent.pickProject({ projects, reference: 'Nope' })).toThrow(
+ /Project "Nope" was not found\. Projects: Website \(1\), App \(2\), app \(3\)\./
+ );
+ });
+});
+
+describe('summarize', () => {
+ const entries = [
+ { seconds: 3600, projectId: 1, projectName: 'Website', userId: 7, userName: 'Jo', clientId: 5, clientName: 'Acme' },
+ { seconds: 1800, projectId: 1, projectName: 'Website', userId: 8, userName: 'Al', clientId: 5, clientName: 'Acme' },
+ { seconds: 900, projectId: null, projectName: null, userId: 7, userName: 'Jo', clientId: null, clientName: null },
+ { seconds: -1, projectId: 2, projectName: 'App', userId: 7, userName: 'Jo', clientId: null, clientName: null },
+ ];
+
+ it('groups by project with totals, counts, and no-project fallback', () => {
+ const summary = togglAgent.summarize({ entries, groupBy: 'project' });
+ expect(summary.total_seconds).toBe(6300);
+ expect(summary.total_hours).toBe(1.75);
+ expect(summary.groups).toEqual([
+ { id: 1, name: 'Website', seconds: 5400, hours: 1.5, entry_count: 2 },
+ { id: null, name: 'No project', seconds: 900, hours: 0.25, entry_count: 1 },
+ ]);
+ });
+
+ it('groups by user and skips running entries', () => {
+ const summary = togglAgent.summarize({ entries, groupBy: 'user' });
+ expect(summary.groups.map((group) => [group.name, group.seconds, group.entry_count])).toEqual([
+ ['Jo', 4500, 2],
+ ['Al', 1800, 1],
+ ]);
+ });
+
+ it('groups by client with the no-client fallback', () => {
+ const summary = togglAgent.summarize({ entries, groupBy: 'client' });
+ expect(summary.groups).toEqual([
+ { id: 5, name: 'Acme', seconds: 5400, hours: 1.5, entry_count: 2 },
+ { id: null, name: 'No client', seconds: 900, hours: 0.25, entry_count: 1 },
+ ]);
+ });
+});
+
+describe('input parsing', () => {
+ it('accepts only the three group-by values', () => {
+ expect(togglAgent.parseGroupBy(undefined)).toBe('project');
+ expect(togglAgent.parseGroupBy(' USER ')).toBe('user');
+ expect(() => togglAgent.parseGroupBy('team')).toThrow(/must be "project", "user", or "client"/);
+ });
+
+ it('converts minutes to seconds, rounding after the multiplication', () => {
+ expect(togglAgent.durationSeconds({ minutes: '25' })).toBe(1500);
+ expect(togglAgent.durationSeconds({ minutes: 1.5 })).toBe(90);
+ expect(togglAgent.durationSeconds({ minutes: 0.25 })).toBe(15);
+ expect(togglAgent.durationSeconds({ minutes: 0.6 })).toBe(36);
+ });
+
+ it('rejects durations that are not a positive number of seconds', () => {
+ expect(() => togglAgent.durationSeconds({ minutes: 0 })).toThrow(/positive number of minutes/);
+ expect(() => togglAgent.durationSeconds({ minutes: -5 })).toThrow(/positive number of minutes/);
+ expect(() => togglAgent.durationSeconds({ minutes: 0.004 })).toThrow(/positive number of minutes/);
+ expect(() => togglAgent.durationSeconds({ minutes: 'abc' })).toThrow(/positive number of minutes/);
+ });
+
+ it('treats "now" and ISO datetimes as start values', () => {
+ const before = Date.now();
+ const now = new Date(togglAgent.parseStart({ value: 'NOW' })).getTime();
+ expect(now).toBeGreaterThanOrEqual(before - 1000);
+ expect(togglAgent.parseStart({ value: '2026-10-08T10:00:00Z' })).toBe('2026-10-08T10:00:00.000Z');
+ expect(() => togglAgent.parseStart({ value: 'yesterday' })).toThrow(/not a valid date/);
+ });
+});
+
+
+describe('task dropdown refreshers', () => {
+ it.each([
+ ['create_time_entry', createTimeEntry],
+ ['start_time_entry', startTimeEntry],
+ ['update_time_entry', updateTimeEntry],
+ ['new_time_entry trigger', newTimeEntry],
+ ])('%s refreshers only name props that exist on the action', (_name, action) => {
+ const propNames = Object.keys(action.props);
+ for (const prop of Object.values(action.props)) {
+ const refreshers = (prop as { refreshers?: string[] }).refreshers ?? [];
+ for (const refresher of refreshers) {
+ expect(propNames).toContain(refresher);
+ }
+ }
+ });
+
+ it('refreshes the task dropdown from the project prop', () => {
+ const taskProp = updateTimeEntry.props['task_id'] as { refreshers: string[] };
+ expect(taskProp.refreshers).toEqual(['workspace_id', 'project_id']);
+ });
+});
+
+describe('clearing tags', () => {
+ it('keeps the current tags when nothing is set', () => {
+ expect(togglCommon.tagListValue({ tags: undefined, clearTags: undefined })).toBeUndefined();
+ expect(togglCommon.tagListValue({ tags: [], clearTags: false })).toBeUndefined();
+ });
+
+ it('returns the selected tags', () => {
+ expect(togglCommon.tagListValue({ tags: ['a', 'b'], clearTags: false })).toEqual(['a', 'b']);
+ });
+
+ it('returns an empty list when Clear Tags is set', () => {
+ expect(togglCommon.tagListValue({ tags: [], clearTags: true })).toEqual([]);
+ expect(togglCommon.tagListValue({ tags: undefined, clearTags: true })).toEqual([]);
+ });
+
+ it('rejects Tags combined with Clear Tags', () => {
+ expect(() => togglCommon.tagListValue({ tags: ['a'], clearTags: true })).toThrow(
+ /Set Tags or Clear Tags, not both/
+ );
+ });
+
+ it('resolves an empty tag list to an empty id list on Toggl 2.0', async () => {
+ const auth = togglApi.twoConnection({
+ props: { token: 'test-token', organization_id: '1' },
+ });
+ if (!togglApi.isTwo(auth)) {
+ throw new Error('expected a Toggl 2.0 connection');
+ }
+ await expect(
+ togglApi.resolveTwoTagIds({ auth, workspaceId: 1, names: [] })
+ ).resolves.toEqual([]);
+ await expect(
+ togglApi.resolveTwoTagIds({ auth, workspaceId: 1, names: undefined })
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/packages/pieces/community/toggl-track/vitest.config.ts b/packages/pieces/community/toggl-track/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/toggl-track/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})