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(workable): manage candidates and react to stage changes from flows and AI agents (#16825)

Odai Ahmadec31e84ef051
diff --git a/bun.lock b/bun.lock
index 5315f566533..db7fcbfe514 100644
--- a/bun.lock
+++ b/bun.lock
@@ -10183,7 +10183,7 @@
},
"packages/pieces/community/workable": {
"name": "@activepieces/piece-workable",
- "version": "0.2.1",
+ "version": "0.3.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -10191,7 +10191,8 @@
"@activepieces/pieces-framework": "workspace:*",
},
"devDependencies": {
- "tslib": "^2.3.0",
+ "tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/workday": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index 98f930d8bb2..27221fa8dcf 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,21 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### Workable 0.3.0: Move Candidate is no longer an agent tool, and some step outputs change
+
+**Move Candidate** is now shown only in the flow builder. AI agents and MCP clients get **Move Candidate (by IDs)** instead, which takes the candidate ID and the target stage as text.
+
+Once a step is upgraded to Workable 0.3.0, these outputs change:
+
+- **Get Candidate** returns the candidate itself, without the `candidate` wrapper.
+- **Move Candidate** and **Rate Candidate** return `{success, candidate_id, ...}` instead of `{status, headers, body}`.
+- **Get Members** returns `nextCursor` and `hasMore` instead of `paging`, and refuses a Limit above 100.
+- **New Candidate** ignores webhook deliveries that are unsigned or that arrive more than 6 hours after Workable fired them.
+
+#### What you need to do
+
+If a Run Agent step or MCP client uses Move Candidate as a tool, switch it to Move Candidate (by IDs). Flow steps that use Move Candidate keep working. Steps keep running on the version they were built with until you upgrade them; when you upgrade, update any later step that reads `candidate.*` from Get Candidate, `body` from Move Candidate or Rate Candidate, or `paging` from Get Members.
+
#### iLoveAPI 0.1.0: Create Signature Request is no longer an agent tool, and triggers need a Webhook Secret
iLoveAPI 0.1.0 changes what an existing step does once it is upgraded to that version. Steps keep running on the version they were built with until you upgrade them.
diff --git a/packages/pieces/community/workable/package.json b/packages/pieces/community/workable/package.json
index 50b38a6b025..ed87fb468b1 100644
--- a/packages/pieces/community/workable/package.json
+++ b/packages/pieces/community/workable/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-workable",
- "version": "0.2.1",
+ "version": "0.3.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.6.2",
+ "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/workable/src/index.ts b/packages/pieces/community/workable/src/index.ts
index c62f6dbf809..ac285d33968 100644
--- a/packages/pieces/community/workable/src/index.ts
+++ b/packages/pieces/community/workable/src/index.ts
@@ -1,42 +1,106 @@
-
-import { createPiece, PieceAuth } from "@activepieces/pieces-framework";
-import { getCandidate } from "./lib/actions/get-candidate";
-import { getMembers } from "./lib/actions/get-members";
-import { getJob } from "./lib/actions/get-job";
-import { getStages } from "./lib/actions/get-stages";
-import { moveCandidate } from "./lib/actions/move-candidate";
-import { rateCandidate } from "./lib/actions/rate-candidate";
-import { newCandidate } from "./lib/triggers/new-candidate";
-import { createCustomApiCallAction } from "@activepieces/pieces-common";
-import { PieceCategory } from '@activepieces/pieces-framework';
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
+import { createAction, createPiece, PieceCategory } from '@activepieces/pieces-framework';
+import { addCandidateTags } from './lib/actions/add-candidate-tags';
+import { addComment } from './lib/actions/add-comment';
+import { createCandidateAi } from './lib/actions/ai/create-candidate-ai';
+import { moveCandidateAi } from './lib/actions/ai/move-candidate-ai';
+import { copyCandidateToJob } from './lib/actions/copy-candidate-to-job';
+import { createCandidate } from './lib/actions/create-candidate';
+import { disqualifyCandidate } from './lib/actions/disqualify-candidate';
+import { getCandidate } from './lib/actions/get-candidate';
+import { getCandidateActivities } from './lib/actions/get-candidate-activities';
+import { getJob } from './lib/actions/get-job';
+import { getMembers } from './lib/actions/get-members';
+import { getStages } from './lib/actions/get-stages';
+import { listAccounts } from './lib/actions/list-accounts';
+import { listCandidates } from './lib/actions/list-candidates';
+import { listDisqualificationReasons } from './lib/actions/list-disqualification-reasons';
+import { listJobQuestions } from './lib/actions/list-job-questions';
+import { listJobs } from './lib/actions/list-jobs';
+import { listRecruiters } from './lib/actions/list-recruiters';
+import { moveCandidate } from './lib/actions/move-candidate';
+import { rateCandidate } from './lib/actions/rate-candidate';
+import { revertDisqualification } from './lib/actions/revert-disqualification';
+import { updateCandidate } from './lib/actions/update-candidate';
import { workableAuth } from './lib/auth';
+import { baseUrlFor, isSameApiUrl, resolveSubdomain, ROOT_URL, tokenOf } from './lib/common/client';
+import { accountSubdomainProp } from './lib/common/props';
+import { workableValues } from './lib/common/values';
+import { candidateStageChanged } from './lib/triggers/candidate-stage-changed';
+import { newCandidate } from './lib/triggers/new-candidate';
+
+const baseCustomApiCall = createCustomApiCallAction({
+ baseUrl: () => ROOT_URL,
+ auth: workableAuth,
+ description: 'Make a custom API call to your Workable account (https://{subdomain}.workable.com/spi/v3).',
+ extraProps: { account_subdomain: accountSubdomainProp },
+ authMapping: async (auth, propsValue) => {
+ const subdomain = await resolveSubdomain({ token: tokenOf(auth), subdomain: propsValue['account_subdomain'] });
+ const url = workableValues.rec(propsValue['url'])['url'];
+ if (typeof url !== 'string' || !isSameApiUrl({ subdomain, candidate: url })) {
+ throw new Error(`Custom API Call only sends your token to ${baseUrlFor(subdomain)}. Use a path such as /jobs or a full URL on that host.`);
+ }
+ return { Authorization: `Bearer ${tokenOf(auth)}`, Accept: 'application/json' };
+ },
+});
-
+const runCustomApiCall: typeof baseCustomApiCall.run = async (context) => {
+ const values: Record<string, unknown> = context.propsValue;
+ const subdomain = await resolveSubdomain({ token: tokenOf(context.auth), subdomain: values['account_subdomain'] });
+ const urlProps = workableValues.rec(context.propsValue['url']);
+ const raw = typeof urlProps['url'] === 'string' ? urlProps['url'].trim() : '';
+ const absolute = /^https?:\/\//i.test(raw) ? raw : `${baseUrlFor(subdomain)}/${raw.replace(/^\/+/, '')}`;
+ return baseCustomApiCall.run({
+ ...context,
+ propsValue: Object.assign({}, context.propsValue, { account_subdomain: subdomain, url: { ...urlProps, url: absolute } }),
+ });
+};
+
+export const workableCustomApiCall = createAction({
+ ...baseCustomApiCall,
+ auth: workableAuth,
+ audience: 'human',
+ classification: 'DESTRUCTIVE',
+ aiMetadata: {
+ description:
+ 'Send a raw request to any Workable SPI v3 endpoint (relative path such as "jobs" or "candidates/{id}") on the selected account. The method can be DELETE. Returns the raw response.',
+ idempotent: false,
+ },
+ run: runCustomApiCall,
+ test: runCustomApiCall,
+});
export const workable = createPiece({
- displayName: "Workable",
+ displayName: 'Workable',
auth: workableAuth,
- minimumSupportedRelease: '0.36.1',
- logoUrl: "https://cdn.activepieces.com/pieces/workable.png",
- categories:[PieceCategory.HUMAN_RESOURCES],
- authors: ['Cloudieunnie'],
+ minimumSupportedRelease: '0.88.2',
+ logoUrl: 'https://cdn.activepieces.com/pieces/workable.png',
+ categories: [PieceCategory.HUMAN_RESOURCES],
+ authors: ['Cloudieunnie', 'OdaiAhmed99'],
actions: [
- getCandidate,
- getMembers,
- getJob,
- getStages,
- moveCandidate,
+ getCandidate,
+ getMembers,
+ getJob,
+ getStages,
+ moveCandidate,
+ moveCandidateAi,
rateCandidate,
- createCustomApiCallAction({
- baseUrl: () => `https://workable.com/spi/v3/`,
- auth: workableAuth,
- authMapping: async (auth) => ({
- Authorization: `Bearer ${auth.secret_text}`,
- Accept: 'application/json'
- })
- })
- ],
- triggers: [
- newCandidate
+ listCandidates,
+ listJobs,
+ createCandidate,
+ createCandidateAi,
+ updateCandidate,
+ addComment,
+ disqualifyCandidate,
+ revertDisqualification,
+ addCandidateTags,
+ listDisqualificationReasons,
+ listRecruiters,
+ listJobQuestions,
+ getCandidateActivities,
+ copyCandidateToJob,
+ listAccounts,
+ workableCustomApiCall,
],
+ triggers: [newCandidate, candidateStageChanged],
});
diff --git a/packages/pieces/community/workable/src/lib/actions/add-candidate-tags.ts b/packages/pieces/community/workable/src/lib/actions/add-candidate-tags.ts
new file mode 100644
index 00000000000..6b52234085a
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/add-candidate-tags.ts
@@ -0,0 +1,53 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { encodeId } from '../common/client';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp, candidateIdProp } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { workableValues } from '../common/values';
+
+export const addCandidateTags = createAction({
+ auth: workableAuth,
+ name: 'add_candidate_tags',
+ classification: 'WRITE',
+ displayName: 'Add Candidate Tags',
+ description: 'Adds tags to a candidate and keeps the tags they already have.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ "Add one or more tags to a Workable candidate. Reads the candidate's current tags and saves the union, so existing tags stay and a second run changes nothing.",
+ idempotent: true,
+ },
+ outputSchema: workableSchemas.tags,
+ props: {
+ account_subdomain: accountSubdomainProp,
+ id: candidateIdProp,
+ tags: Property.Array({ displayName: 'Tags', required: true }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const v = workableValues;
+ const wanted = v.stringList({ value: p.tags, label: 'Tags' }) ?? [];
+ if (wanted.length === 0) {
+ throw new Error('Give at least one tag to add.');
+ }
+ const id = encodeId({ value: p.id, label: 'Candidate ID' });
+ const client = workableOps.client({ auth: context.auth, subdomain: p.account_subdomain });
+ const current = workableOps.unwrap({ body: await client.request({ method: HttpMethod.GET, path: `/candidates/${id}` }), key: 'candidate' });
+ const existing = v.list(current['tags']).map((tag) => v.str(tag)).filter((tag): tag is string => tag !== null);
+ const lower = new Set(existing.map((tag) => tag.toLowerCase()));
+ const added = wanted.filter((tag) => !lower.has(tag.toLowerCase()));
+ const candidateId = decodeURIComponent(id);
+ if (added.length === 0) {
+ return { candidate_id: candidateId, tags: existing, added: [] };
+ }
+ const tags = [...existing, ...added];
+ const body = await client.request({ method: HttpMethod.PUT, path: `/candidates/${id}/tags`, body: { tags } });
+ const saved = v.list(v.rec(body)['tags']).map((tag) => v.str(tag)).filter((tag): tag is string => tag !== null);
+ if (saved.length === 0) {
+ return { candidate_id: candidateId, tags, added };
+ }
+ return { candidate_id: candidateId, tags: saved, added: saved.filter((tag) => !lower.has(tag.toLowerCase())) };
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/actions/add-comment.ts b/packages/pieces/community/workable/src/lib/actions/add-comment.ts
new file mode 100644
index 00000000000..f2c2dae3d28
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/add-comment.ts
@@ -0,0 +1,61 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { encodeId } from '../common/client';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp, candidateIdProp, memberIdText } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { workableValues } from '../common/values';
+
+export const addComment = createAction({
+ auth: workableAuth,
+ name: 'add_comment',
+ classification: 'WRITE',
+ displayName: 'Add Comment',
+ description: "Adds a comment to a candidate's timeline.",
+ audience: 'both',
+ aiMetadata: {
+ description:
+ "Add a comment to a Workable candidate's timeline on behalf of a hiring-team member (member ID from Get Members). Visibility limits which roles can see it; empty means everyone on the hiring team. Not idempotent: each call adds another comment.",
+ idempotent: false,
+ },
+ outputSchema: workableSchemas.commented,
+ props: {
+ account_subdomain: accountSubdomainProp,
+ id: candidateIdProp,
+ member_id: memberIdText({ description: 'ID of the member writing the comment. Find it with Get Members.' }),
+ body: Property.LongText({ displayName: 'Comment', required: true }),
+ policy: Property.StaticMultiSelectDropdown({
+ displayName: 'Visible To',
+ description: 'Roles that can see the comment. Empty: everyone on the hiring team.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Simple members', value: 'simple' },
+ { label: 'Reviewers', value: 'reviewer' },
+ ],
+ },
+ }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const v = workableValues;
+ const text = v.optionalText(p.body);
+ if (text === undefined) {
+ throw new Error('Comment is required.');
+ }
+ const memberId = v.optionalText(p.member_id);
+ if (memberId === undefined) {
+ throw new Error('Acting Member ID is required.');
+ }
+ const policy = v.stringList({ value: p.policy, label: 'Visible To' }) ?? [];
+ const comment: Record<string, unknown> = { body: text };
+ if (policy.length > 0) {
+ comment['policy'] = policy;
+ }
+ const id = encodeId({ value: p.id, label: 'Candidate ID' });
+ const client = workableOps.client({ auth: context.auth, subdomain: p.account_subdomain });
+ await client.request({ method: HttpMethod.POST, path: `/candidates/${id}/comments`, body: { member_id: memberId, comment } });
+ return { success: true, candidate_id: decodeURIComponent(id) };
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/actions/ai/create-candidate-ai.ts b/packages/pieces/community/workable/src/lib/actions/ai/create-candidate-ai.ts
new file mode 100644
index 00000000000..161a8cc2d4c
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/ai/create-candidate-ai.ts
@@ -0,0 +1,45 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { workableAuth } from '../../auth';
+import { workableOps } from '../../common/operations';
+import { accountSubdomainProp, candidateFieldProps, candidateInputFrom } from '../../common/props';
+import { workableSchemas } from '../../common/schemas';
+
+export const createCandidateAi = createAction({
+ auth: workableAuth,
+ name: 'create_candidate_ai',
+ classification: 'WRITE',
+ displayName: 'Create Candidate (by IDs)',
+ description: 'Adds a candidate to a job given by its shortcode, or to the talent pool.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Create a Workable candidate. Give a job shortcode (from List Jobs) to add them to that job, optionally with a stage slug (from Get Stages); leave the shortcode empty to add them to the talent pool. First name, last name and email are required. Sourced is on by default so Workable sends no email. If the email already exists on that job Workable refuses it; then find the candidate with List Candidates instead of retrying.',
+ idempotent: false,
+ },
+ outputSchema: workableSchemas.createdCandidate,
+ props: {
+ account_subdomain: accountSubdomainProp,
+ job_shortcode: Property.ShortText({
+ displayName: 'Job Shortcode',
+ description: 'Shortcode of the job. Empty adds the candidate to the talent pool.',
+ required: false,
+ }),
+ stage: Property.ShortText({
+ displayName: 'Stage Slug',
+ description: 'Stage slug from Get Stages, for example "applied". Empty uses the first stage. Ignored for the talent pool.',
+ required: false,
+ }),
+ ...candidateFieldProps(),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const client = workableOps.client({ auth: context.auth, subdomain: p.account_subdomain });
+ return workableOps.createCandidate({
+ client,
+ jobShortcode: p.job_shortcode,
+ stage: p.job_shortcode ? p.stage : undefined,
+ sourced: p.sourced,
+ input: candidateInputFrom(p),
+ });
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/actions/ai/move-candidate-ai.ts b/packages/pieces/community/workable/src/lib/actions/ai/move-candidate-ai.ts
new file mode 100644
index 00000000000..cf76815ec41
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/ai/move-candidate-ai.ts
@@ -0,0 +1,35 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { workableAuth } from '../../auth';
+import { workableOps } from '../../common/operations';
+import { accountSubdomainProp, candidateIdProp, memberIdText } from '../../common/props';
+import { workableSchemas } from '../../common/schemas';
+
+export const moveCandidateAi = createAction({
+ auth: workableAuth,
+ name: 'move_candidate_ai',
+ classification: 'WRITE',
+ displayName: 'Move Candidate (by IDs)',
+ description: 'Moves a candidate to a pipeline stage given by its slug.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Move a Workable candidate to another stage of their job pipeline. Needs the candidate ID, the acting member ID (from Get Members) and the target stage slug (from Get Stages for the candidate's job, for example \"phone-screen\"). Running it again with the same stage leaves the candidate there.",
+ idempotent: false,
+ },
+ outputSchema: workableSchemas.moved,
+ props: {
+ account_subdomain: accountSubdomainProp,
+ id: candidateIdProp,
+ member_id: memberIdText({ description: 'ID of the member the move is recorded for. Find it with Get Members.' }),
+ target_stage: Property.ShortText({
+ displayName: 'Target Stage Slug',
+ description: 'Slug of the stage, for example "phone-screen". Find it with Get Stages.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const client = workableOps.client({ auth: context.auth, subdomain: p.account_subdomain });
+ return workableOps.moveCandidate({ client, candidateId: p.id, memberId: p.member_id, targetStage: p.target_stage });
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/actions/copy-candidate-to-job.ts b/packages/pieces/community/workable/src/lib/actions/copy-candidate-to-job.ts
new file mode 100644
index 00000000000..2c204f817a5
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/copy-candidate-to-job.ts
@@ -0,0 +1,66 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { encodeId, WorkableClient } from '../common/client';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp, candidateIdProp, memberIdText } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { workableValues } from '../common/values';
+
+export const copyCandidateToJob = createAction({
+ auth: workableAuth,
+ name: 'copy_candidate_to_job',
+ classification: 'WRITE',
+ displayName: 'Copy Candidate to Job',
+ description: 'Copies a candidate to another job. The original stays where it is.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Copy a Workable candidate into another job (target job shortcode from List Jobs), optionally into a stage slug, on behalf of a hiring-team member. The original candidate is unchanged. Workable refuses a second copy into the same job.',
+ idempotent: false,
+ },
+ outputSchema: workableSchemas.copied,
+ props: {
+ account_subdomain: accountSubdomainProp,
+ id: candidateIdProp,
+ member_id: memberIdText({ description: 'ID of the member making the copy. Find it with Get Members.' }),
+ target_job_shortcode: Property.ShortText({ displayName: 'Target Job Shortcode', required: true }),
+ target_stage: Property.ShortText({
+ displayName: 'Target Stage Slug',
+ description: 'Stage in the target job. Empty uses the first stage.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const v = workableValues;
+ const memberId = v.optionalText(p.member_id);
+ if (memberId === undefined) {
+ throw new Error('Acting Member ID is required.');
+ }
+ const target = v.optionalText(p.target_job_shortcode);
+ if (target === undefined) {
+ throw new Error('Target Job Shortcode is required.');
+ }
+ const id = encodeId({ value: p.id, label: 'Candidate ID' });
+ const client = workableOps.client({ auth: context.auth, subdomain: p.account_subdomain });
+ const stage = v.optionalText(p.target_stage) ?? (await firstStageSlug({ client, shortcode: target }));
+ const body = { member_id: memberId, target_job_shortcode: target, target_stage: stage };
+ const response = await client.request({ method: HttpMethod.POST, path: `/candidates/${id}/copy`, body });
+ return {
+ source_candidate_id: decodeURIComponent(id),
+ target_job_shortcode: target,
+ candidate: workableOps.unwrap({ body: response, key: 'candidate' }),
+ };
+ },
+});
+
+async function firstStageSlug({ client, shortcode }: { client: WorkableClient; shortcode: string }): Promise<string> {
+ const path = `/jobs/${encodeURIComponent(shortcode)}/stages`;
+ const stages = workableValues.list(workableValues.rec(await client.request({ method: HttpMethod.GET, path }))['stages']);
+ const slug = workableValues.str(workableValues.rec(stages[0])['slug']);
+ if (slug === null) {
+ throw new Error(`Job ${shortcode} has no pipeline stages, so the candidate cannot be copied there.`);
+ }
+ return slug;
+}
diff --git a/packages/pieces/community/workable/src/lib/actions/create-candidate.ts b/packages/pieces/community/workable/src/lib/actions/create-candidate.ts
new file mode 100644
index 00000000000..9ff772cef34
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/create-candidate.ts
@@ -0,0 +1,37 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp, candidateFieldProps, candidateInputFrom, jobDropdown, stageDropdown } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+
+export const createCandidate = createAction({
+ auth: workableAuth,
+ name: 'create_candidate',
+ classification: 'WRITE',
+ displayName: 'Create Candidate',
+ description: 'Adds a candidate to a job, or to the talent pool when no job is selected.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Create a Workable candidate in a job and stage picked from dropdowns, or in the talent pool when no job is picked. Sourced by default, so no email is sent. A second run with the same email on the same job fails with a duplicate error instead of creating a copy.',
+ idempotent: false,
+ },
+ outputSchema: workableSchemas.createdCandidate,
+ props: {
+ account_subdomain: accountSubdomainProp,
+ job: jobDropdown({ displayName: 'Job', description: 'Job to add the candidate to. Empty adds them to the talent pool.', required: false }),
+ stage: stageDropdown({ required: false, description: 'Stage to add the candidate in. Empty uses the first stage.' }),
+ ...candidateFieldProps(),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const client = workableOps.client({ auth: context.auth, subdomain: p.account_subdomain });
+ return workableOps.createCandidate({
+ client,
+ jobShortcode: p.job,
+ stage: p.job ? p.stage : undefined,
+ sourced: p.sourced,
+ input: candidateInputFrom(p),
+ });
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/actions/disqualify-candidate.ts b/packages/pieces/community/workable/src/lib/actions/disqualify-candidate.ts
new file mode 100644
index 00000000000..0e7e385eec7
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/disqualify-candidate.ts
@@ -0,0 +1,64 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { encodeId } from '../common/client';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp, candidateIdProp, memberIdText } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { workableValues } from '../common/values';
+
+const MAX_NOTE = 256;
+
+export const disqualifyCandidate = createAction({
+ auth: workableAuth,
+ name: 'disqualify_candidate',
+ classification: 'WRITE',
+ displayName: 'Disqualify Candidate',
+ description: 'Disqualifies a candidate, with an optional reason and note.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Disqualify a Workable candidate on behalf of a hiring-team member. Optional reason ID (from List Disqualification Reasons), a note of up to 256 characters, and whether the candidate withdrew. Undo with Revert Disqualification. Running it again on a disqualified candidate keeps them disqualified.',
+ idempotent: true,
+ },
+ outputSchema: workableSchemas.disqualified,
+ props: {
+ account_subdomain: accountSubdomainProp,
+ id: candidateIdProp,
+ member_id: memberIdText({ description: 'ID of the member disqualifying the candidate. Find it with Get Members.' }),
+ disqualify_reason_id: Property.ShortText({
+ displayName: 'Reason ID',
+ description: 'Find it with List Disqualification Reasons.',
+ required: false,
+ }),
+ disqualify_note: Property.LongText({ displayName: 'Note', description: 'Up to 256 characters.', required: false }),
+ withdrew: Property.Checkbox({ displayName: 'Candidate Withdrew', required: false, defaultValue: false }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const v = workableValues;
+ const memberId = v.optionalText(p.member_id);
+ if (memberId === undefined) {
+ throw new Error('Acting Member ID is required.');
+ }
+ const note = v.optionalText(p.disqualify_note);
+ if (note !== undefined && note.length > MAX_NOTE) {
+ throw new Error(`Note is ${note.length} characters; Workable allows at most ${MAX_NOTE}.`);
+ }
+ const body: Record<string, unknown> = { member_id: memberId };
+ const reason = v.optionalText(p.disqualify_reason_id);
+ if (reason !== undefined) {
+ body['disqualify_reason_id'] = reason;
+ }
+ if (note !== undefined) {
+ body['disqualify_note'] = note;
+ }
+ if (v.bool(p.withdrew) === true) {
+ body['withdrew'] = true;
+ }
+ const id = encodeId({ value: p.id, label: 'Candidate ID' });
+ const client = workableOps.client({ auth: context.auth, subdomain: p.account_subdomain });
+ await client.request({ method: HttpMethod.POST, path: `/candidates/${id}/disqualify`, body });
+ return { success: true, candidate_id: decodeURIComponent(id), disqualified: true };
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/actions/get-candidate-activities.ts b/packages/pieces/community/workable/src/lib/actions/get-candidate-activities.ts
new file mode 100644
index 00000000000..a38276a593c
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/get-candidate-activities.ts
@@ -0,0 +1,30 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { encodeId } from '../common/client';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp, candidateIdProp } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { workableValues } from '../common/values';
+
+export const getCandidateActivities = createAction({
+ auth: workableAuth,
+ name: 'get_candidate_activities',
+ classification: 'READ',
+ displayName: 'Get Candidate Activities',
+ description: "Gets a candidate's timeline: comments, stage moves, ratings and more.",
+ audience: 'both',
+ aiMetadata: {
+ description: "Get the activity timeline of one Workable candidate by candidate ID: comments, stage moves, ratings, disqualifications, each with member and time. Read-only.",
+ idempotent: true,
+ },
+ outputSchema: workableSchemas.activities,
+ props: { account_subdomain: accountSubdomainProp, id: candidateIdProp },
+ async run(context) {
+ const client = workableOps.client({ auth: context.auth, subdomain: context.propsValue.account_subdomain });
+ const id = encodeId({ value: context.propsValue.id, label: 'Candidate ID' });
+ const body = await client.request({ method: HttpMethod.GET, path: `/candidates/${id}/activities` });
+ const activities = workableValues.records(workableValues.rec(body)['activities']);
+ return { activities, count: activities.length };
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/actions/get-candidate.ts b/packages/pieces/community/workable/src/lib/actions/get-candidate.ts
index 263715a93c6..e52343a44f7 100644
--- a/packages/pieces/community/workable/src/lib/actions/get-candidate.ts
+++ b/packages/pieces/community/workable/src/lib/actions/get-candidate.ts
@@ -1,38 +1,32 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
import { workableAuth } from '../auth';
-import { createAction, Property } from '@activepieces/pieces-framework';
-import { getAccountSubdomain } from '../common/get-subdomain';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { encodeId } from '../common/client';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp, candidateIdProp } from '../common/props';
+import { workableSchemas } from '../common/schemas';
export const getCandidate = createAction({
auth: workableAuth,
name: 'getCandidate',
classification: 'READ',
displayName: 'Get Candidate',
- description: "Gets candidate's information.",
+ description: "Gets a candidate's full profile.",
audience: 'both',
- aiMetadata: { description: 'Fetch a single Workable candidate record by its candidate ID. Use to look up a known candidate before rating, moving, or referencing them. Requires the exact candidate ID; this is a read-only lookup and is idempotent.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Fetch one Workable candidate by candidate ID, with contact details, stage, job, tags, skills, experience and education. Use before updating, moving or rating a known candidate. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: workableSchemas.candidate,
props: {
- id: Property.ShortText({
- displayName: "Candidate's Id",
- required: true
- })
+ account_subdomain: accountSubdomainProp,
+ id: candidateIdProp,
},
async run(context) {
- // Action logic here
- const candidateId = context.propsValue.id;
- const accessToken = context.auth.secret_text;
- const account = await getAccountSubdomain(accessToken);
-
- //get candidate information
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `https://${account}.workable.com/spi/v3/candidates/${candidateId}`,
- headers: {
- Authorization: `Bearer ${accessToken}`,
- Accept: 'application/json',
- },
- });
-
- return response.body;
+ const client = workableOps.client({ auth: context.auth, subdomain: context.propsValue.account_subdomain });
+ const id = encodeId({ value: context.propsValue.id, label: 'Candidate ID' });
+ const body = await client.request({ method: HttpMethod.GET, path: `/candidates/${id}` });
+ return workableOps.unwrap({ body, key: 'candidate' });
},
});
diff --git a/packages/pieces/community/workable/src/lib/actions/get-job.ts b/packages/pieces/community/workable/src/lib/actions/get-job.ts
index 83faff787b1..1dff890ac50 100644
--- a/packages/pieces/community/workable/src/lib/actions/get-job.ts
+++ b/packages/pieces/community/workable/src/lib/actions/get-job.ts
@@ -1,42 +1,46 @@
-import { workableAuth } from '../auth';
+import { HttpMethod } from '@activepieces/pieces-common';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
-import { getAccountSubdomain } from '../common/get-subdomain';
+import { workableAuth } from '../auth';
+import { encodeId } from '../common/client';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp } from '../common/props';
+import { workableSchemas } from '../common/schemas';
export const getJob = createAction({
auth: workableAuth,
name: 'getJob',
classification: 'READ',
displayName: 'Get Job',
- description: 'Gets specific job deatils.',
+ description: 'Gets the details of a job.',
audience: 'both',
- aiMetadata: { description: 'Fetch details of a single Workable job posting identified by its shortcode. Use when you have a job shortcode and need its full attributes. Requires the exact job shortcode; read-only and idempotent.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Fetch one Workable job by its shortcode, with title, state, department, location and URLs; turn on Include Description for the description, requirements and benefits. Find shortcodes with List Jobs. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: workableSchemas.job,
props: {
+ account_subdomain: accountSubdomainProp,
shortcode: Property.ShortText({
- displayName: "Shortcode",
- description: "Shortcode of specific job",
- required: true
- })
+ displayName: 'Job Shortcode',
+ description: 'Shortcode of the job, for example "GROOV005". Find it with List Jobs.',
+ required: true,
+ }),
+ include_description: Property.Checkbox({
+ displayName: 'Include Description',
+ description: 'Also return the description, requirements and benefits.',
+ required: false,
+ defaultValue: false,
+ }),
},
async run(context) {
- // Action logic here
- const shortcode = context.propsValue?.shortcode;
- const accessToken = context.auth.secret_text;
-
- // get account subdomain
- const account = await getAccountSubdomain(accessToken);
-
- const url = `https://${account}.workable.com/spi/v3/jobs/${shortcode}`;
-
- const response = await httpClient.sendRequest({
+ const client = workableOps.client({ auth: context.auth, subdomain: context.propsValue.account_subdomain });
+ const shortcode = encodeId({ value: context.propsValue.shortcode, label: 'Job Shortcode' });
+ const body = await client.request({
method: HttpMethod.GET,
- url: url,
- headers: {
- Authorization: `Bearer ${accessToken}`,
- Accept: 'application/json',
- },
+ path: `/jobs/${shortcode}`,
+ query: { include_fields: context.propsValue.include_description === true ? 'description,requirements,benefits' : undefined },
});
-
- return response.body;
+ return workableOps.unwrap({ body, key: 'job' });
},
});
diff --git a/packages/pieces/community/workable/src/lib/actions/get-members.ts b/packages/pieces/community/workable/src/lib/actions/get-members.ts
index 5ad68117575..c7c87086333 100644
--- a/packages/pieces/community/workable/src/lib/actions/get-members.ts
+++ b/packages/pieces/community/workable/src/lib/actions/get-members.ts
@@ -1,82 +1,57 @@
-import { workableAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { getAccountSubdomain } from '../common/get-subdomain';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { workableAuth } from '../auth';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { workableValues } from '../common/values';
export const getMembers = createAction({
auth: workableAuth,
name: 'getMembers',
classification: 'SEARCH',
displayName: 'Get Members',
- description: 'Gets members of hiring team.',
+ description: 'Lists members of the hiring team, one page at a time.',
audience: 'both',
- aiMetadata: { description: "Lists Workable account members (hiring team users). With no filters it returns all members; supply role, job shortcode, email, or exact name to narrow results. Use to resolve a member ID needed by actions like rating or moving a candidate. Read-only and idempotent.", idempotent: true },
+ aiMetadata: {
+ description:
+ 'List Workable account members (hiring team users) with ID, name, email and role. Filter by role, job shortcode, email or exact name. Returns one page; when hasMore is true pass nextCursor as Cursor. Use to find the acting member ID that moving, rating, commenting and disqualifying need. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: workableSchemas.members,
props: {
- limit: Property.Number({
- displayName: "Limit",
- description: "Default is 50",
- required: false
- }),
- role: Property.ShortText({
- displayName: "Role",
- description: "Filter for member of specified role",
- required: false
- }),
- shortcode: Property.ShortText({
- displayName: "Shortcode",
- description: "Shortcode of specific job",
- required: false
- }),
- email: Property.ShortText({
- displayName: "Member's email",
- description: "Filter for specific member by email",
- required: false
- }),
- name: Property.ShortText({
- displayName: "Member's name",
- description: "Filter for members of specified name (Exact Match)",
- required: false
+ account_subdomain: accountSubdomainProp,
+ role: Property.StaticDropdown({
+ displayName: 'Role',
+ required: false,
+ options: {
+ options: [
+ { label: 'Admin', value: 'admin' },
+ { label: 'Simple', value: 'simple' },
+ { label: 'Reviewer', value: 'reviewer' },
+ ],
+ },
}),
+ shortcode: Property.ShortText({ displayName: 'Job Shortcode', description: 'Only members of this job.', required: false }),
+ email: Property.ShortText({ displayName: 'Email', description: 'Only the member with this email.', required: false }),
+ name: Property.ShortText({ displayName: 'Name', description: 'Only members with this exact name.', required: false }),
+ limit: Property.Number({ displayName: 'Limit', description: 'Members per page, 1 to 100. Default 50.', required: false }),
+ cursor: Property.ShortText({ displayName: 'Cursor', description: 'nextCursor from a previous run, to get the next page.', required: false }),
},
async run(context) {
- // Action logic here
- const limit = context.propsValue['limit'];
- const role = context.propsValue['role'];
- const shortcode = context.propsValue['shortcode'];
- const email = context.propsValue['email'];
- const name = context.propsValue['name'];
-
- const accessToken = context.auth.secret_text;
-
- const queryParams: Record<string, any> = {};
-
- if(limit !== undefined && limit !== null) {
- queryParams["limit"] = limit;
- }
- if(role && role.trim() !== ''){
- queryParams["role"] = role;
- }
- if(shortcode && shortcode.trim() !== ""){
- queryParams["shortcode"] = shortcode;
- }
- if(email && email.trim() !== ""){
- queryParams["email"] = email;
- }
- if(name && name.trim() !== ''){
- queryParams["name"] = name;
- }
-
- const subdomain = await getAccountSubdomain(accessToken);
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `https://${subdomain}.workable.com/spi/v3/members`,
- headers: {
- Authorization: `Bearer ${accessToken}`,
- Accept: "application/json"
+ const p = context.propsValue;
+ const client = workableOps.client({ auth: context.auth, subdomain: p.account_subdomain });
+ return workableOps.listPage({
+ client,
+ path: '/members',
+ key: 'members',
+ query: {
+ role: workableValues.optionalText(p.role),
+ shortcode: workableValues.optionalText(p.shortcode),
+ email: workableValues.optionalText(p.email),
+ name: workableValues.optionalText(p.name),
},
- queryParams
- })
-
- return response.body;
+ limit: p.limit,
+ cursor: p.cursor,
+ });
},
});
diff --git a/packages/pieces/community/workable/src/lib/actions/get-stages.ts b/packages/pieces/community/workable/src/lib/actions/get-stages.ts
index 7337dd0a81f..ac6554eb0dd 100644
--- a/packages/pieces/community/workable/src/lib/actions/get-stages.ts
+++ b/packages/pieces/community/workable/src/lib/actions/get-stages.ts
@@ -1,38 +1,39 @@
-import { workableAuth } from '../auth';
+import { HttpMethod } from '@activepieces/pieces-common';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { getAccountSubdomain } from '../common/get-subdomain';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { workableAuth } from '../auth';
+import { encodeId } from '../common/client';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { workableValues } from '../common/values';
export const getStages = createAction({
auth: workableAuth,
name: 'getStages',
classification: 'SEARCH',
displayName: 'Get Stages',
- description: 'Gets stages in your recruitment pipeline stages.',
+ description: 'Lists the pipeline stages of a job, or of the account when no job is given.',
audience: 'both',
- aiMetadata: { description: 'Lists the recruitment pipeline stages for a specific Workable job, identified by its shortcode. Use to discover valid stage slugs before moving a candidate. Requires the exact job shortcode; read-only and idempotent.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'List Workable recruitment pipeline stages with slug, name and kind. Give a job shortcode for that job\'s pipeline, or leave it empty for the account-wide stages. Use to find valid stage slugs before moving or creating a candidate. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: workableSchemas.stages,
props: {
+ account_subdomain: accountSubdomainProp,
shortcode: Property.ShortText({
- displayName: "Shortcode",
- description: "Shortcode of specific job",
- required: true
- })
+ displayName: 'Job Shortcode',
+ description: 'Shortcode of the job. Empty lists the account-wide stages.',
+ required: false,
+ }),
},
async run(context) {
- // Action logic here
- const shortcode = context.propsValue.shortcode;
-
- const accessToken = context.auth.secret_text;
- const account = await getAccountSubdomain(accessToken);
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `https://${account}.workable.com/spi/v3/jobs/${shortcode}/stages`,
- headers: {
- Authorization: `Bearer ${accessToken}`,
- Accept: "application/json"
- }
- });
- return response.body;
+ const client = workableOps.client({ auth: context.auth, subdomain: context.propsValue.account_subdomain });
+ const shortcode = workableValues.optionalText(context.propsValue.shortcode);
+ const path = shortcode === undefined ? '/stages' : `/jobs/${encodeId({ value: shortcode, label: 'Job Shortcode' })}/stages`;
+ const body = await client.request({ method: HttpMethod.GET, path });
+ const stages = workableValues.records(workableValues.rec(body)['stages']);
+ return { stages, count: stages.length };
},
});
diff --git a/packages/pieces/community/workable/src/lib/actions/list-accounts.ts b/packages/pieces/community/workable/src/lib/actions/list-accounts.ts
new file mode 100644
index 00000000000..3a69e6580b7
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/list-accounts.ts
@@ -0,0 +1,24 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { listAccounts as fetchAccounts, tokenOf } from '../common/client';
+import { workableSchemas } from '../common/schemas';
+
+export const listAccounts = createAction({
+ auth: workableAuth,
+ name: 'list_accounts',
+ classification: 'READ',
+ displayName: 'List Accounts',
+ description: 'Lists the Workable accounts this token can use, with their subdomains.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'List the Workable accounts the connected token can access, with name and subdomain. Steps use the first account unless Account Subdomain is filled, so call this when the token may cover several accounts. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: workableSchemas.accounts,
+ props: {},
+ async run(context) {
+ const accounts = await fetchAccounts(tokenOf(context.auth));
+ return { accounts, count: accounts.length };
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/actions/list-candidates.ts b/packages/pieces/community/workable/src/lib/actions/list-candidates.ts
new file mode 100644
index 00000000000..b873df4c6d4
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/list-candidates.ts
@@ -0,0 +1,49 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { workableValues } from '../common/values';
+
+export const listCandidates = createAction({
+ auth: workableAuth,
+ name: 'list_candidates',
+ classification: 'SEARCH',
+ displayName: 'List Candidates',
+ description: 'Finds candidates by email, job, stage or date, one page at a time.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Search Workable candidates. Filter by exact email, job shortcode, stage slug (needs a job shortcode), created after or updated after a date. Returns one page of up to 100 candidates; when hasMore is true pass nextCursor as Cursor for the next page. Use to find a candidate ID. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: workableSchemas.candidates,
+ props: {
+ account_subdomain: accountSubdomainProp,
+ email: Property.ShortText({ displayName: 'Email', description: 'Only candidates with this email.', required: false }),
+ shortcode: Property.ShortText({ displayName: 'Job Shortcode', description: 'Only candidates of this job.', required: false }),
+ stage: Property.ShortText({ displayName: 'Stage Slug', description: 'Only candidates in this stage. Needs Job Shortcode.', required: false }),
+ created_after: Property.DateTime({ displayName: 'Created After', required: false }),
+ updated_after: Property.DateTime({ displayName: 'Updated After', required: false }),
+ limit: Property.Number({ displayName: 'Limit', description: 'Candidates per page, 1 to 100. Default 50.', required: false }),
+ cursor: Property.ShortText({ displayName: 'Cursor', description: 'nextCursor from a previous run, to get the next page.', required: false }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const v = workableValues;
+ const shortcode = v.optionalText(p.shortcode);
+ const stage = v.optionalText(p.stage);
+ if (stage !== undefined && shortcode === undefined) {
+ throw new Error('Stage Slug needs a Job Shortcode, because stages belong to a job.');
+ }
+ const query = {
+ email: v.optionalText(p.email),
+ shortcode,
+ stage,
+ created_after: v.isoDate({ value: p.created_after, label: 'Created After' }),
+ updated_after: v.isoDate({ value: p.updated_after, label: 'Updated After' }),
+ };
+ const client = workableOps.client({ auth: context.auth, subdomain: p.account_subdomain });
+ return workableOps.listPage({ client, path: '/candidates', key: 'candidates', query, limit: p.limit, cursor: p.cursor });
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/actions/list-disqualification-reasons.ts b/packages/pieces/community/workable/src/lib/actions/list-disqualification-reasons.ts
new file mode 100644
index 00000000000..335c0f727c1
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/list-disqualification-reasons.ts
@@ -0,0 +1,29 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { workableValues } from '../common/values';
+
+export const listDisqualificationReasons = createAction({
+ auth: workableAuth,
+ name: 'list_disqualification_reasons',
+ classification: 'SEARCH',
+ displayName: 'List Disqualification Reasons',
+ description: 'Lists the disqualification reasons set up in the account.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'List the disqualification reasons of the Workable account with ID and name. Use the ID as Reason ID in Disqualify Candidate. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: workableSchemas.disqualificationReasons,
+ props: { account_subdomain: accountSubdomainProp },
+ async run(context) {
+ const client = workableOps.client({ auth: context.auth, subdomain: context.propsValue.account_subdomain });
+ const body = await client.request({ method: HttpMethod.GET, path: '/disqualification_reasons' });
+ const v = workableValues;
+ const reasons = Array.isArray(body) ? v.records(body) : v.records(v.rec(body)['disqualification_reasons']);
+ return { reasons, count: reasons.length };
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/actions/list-job-questions.ts b/packages/pieces/community/workable/src/lib/actions/list-job-questions.ts
new file mode 100644
index 00000000000..bb79408b282
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/list-job-questions.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { encodeId } from '../common/client';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { workableValues } from '../common/values';
+
+export const listJobQuestions = createAction({
+ auth: workableAuth,
+ name: 'list_job_questions',
+ classification: 'READ',
+ displayName: 'List Job Questions',
+ description: 'Lists the application form questions of a job.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'List the application form questions of one Workable job (by shortcode) with key, text, type, whether required and the choices. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: workableSchemas.questions,
+ props: {
+ account_subdomain: accountSubdomainProp,
+ shortcode: Property.ShortText({ displayName: 'Job Shortcode', required: true }),
+ },
+ async run(context) {
+ const client = workableOps.client({ auth: context.auth, subdomain: context.propsValue.account_subdomain });
+ const shortcode = encodeId({ value: context.propsValue.shortcode, label: 'Job Shortcode' });
+ const body = await client.request({ method: HttpMethod.GET, path: `/jobs/${shortcode}/questions` });
+ const questions = workableValues.records(workableValues.rec(body)['questions']);
+ return { questions, count: questions.length };
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/actions/list-jobs.ts b/packages/pieces/community/workable/src/lib/actions/list-jobs.ts
new file mode 100644
index 00000000000..2c602645282
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/list-jobs.ts
@@ -0,0 +1,57 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { workableValues } from '../common/values';
+
+export const listJobs = createAction({
+ auth: workableAuth,
+ name: 'list_jobs',
+ classification: 'SEARCH',
+ displayName: 'List Jobs',
+ description: 'Lists jobs, optionally by state or date, one page at a time.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'List Workable jobs with shortcode, title, state, department and location. Filter by state (draft, published, archived, closed), created after or updated after a date. Returns one page of up to 100 jobs; when hasMore is true pass nextCursor as Cursor. Use to find a job shortcode. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: workableSchemas.jobs,
+ props: {
+ account_subdomain: accountSubdomainProp,
+ state: Property.StaticDropdown({
+ displayName: 'State',
+ required: false,
+ options: {
+ options: [
+ { label: 'Draft', value: 'draft' },
+ { label: 'Published', value: 'published' },
+ { label: 'Archived', value: 'archived' },
+ { label: 'Closed', value: 'closed' },
+ ],
+ },
+ }),
+ created_after: Property.DateTime({ displayName: 'Created After', required: false }),
+ updated_after: Property.DateTime({ displayName: 'Updated After', required: false }),
+ limit: Property.Number({ displayName: 'Limit', description: 'Jobs per page, 1 to 100. Default 50.', required: false }),
+ cursor: Property.ShortText({ displayName: 'Cursor', description: 'nextCursor from a previous run, to get the next page.', required: false }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const v = workableValues;
+ const client = workableOps.client({ auth: context.auth, subdomain: p.account_subdomain });
+ return workableOps.listPage({
+ client,
+ path: '/jobs',
+ key: 'jobs',
+ query: {
+ state: v.optionalText(p.state),
+ created_after: v.isoDate({ value: p.created_after, label: 'Created After' }),
+ updated_after: v.isoDate({ value: p.updated_after, label: 'Updated After' }),
+ },
+ limit: p.limit,
+ cursor: p.cursor,
+ });
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/actions/list-recruiters.ts b/packages/pieces/community/workable/src/lib/actions/list-recruiters.ts
new file mode 100644
index 00000000000..76eb9dd4eb2
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/list-recruiters.ts
@@ -0,0 +1,34 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { encodeId } from '../common/client';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { workableValues } from '../common/values';
+
+export const listRecruiters = createAction({
+ auth: workableAuth,
+ name: 'list_recruiters',
+ classification: 'SEARCH',
+ displayName: 'List Recruiters',
+ description: 'Lists external recruiters of the account or of one job.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'List the external recruiters (agencies) of the Workable account, or of one job when a job shortcode is given, with ID, name and email. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: workableSchemas.recruiters,
+ props: {
+ account_subdomain: accountSubdomainProp,
+ shortcode: Property.ShortText({ displayName: 'Job Shortcode', description: 'Only recruiters of this job.', required: false }),
+ },
+ async run(context) {
+ const client = workableOps.client({ auth: context.auth, subdomain: context.propsValue.account_subdomain });
+ const shortcode = workableValues.optionalText(context.propsValue.shortcode);
+ const path = shortcode === undefined ? '/recruiters' : `/jobs/${encodeId({ value: shortcode, label: 'Job Shortcode' })}/recruiters`;
+ const body = await client.request({ method: HttpMethod.GET, path });
+ const recruiters = workableValues.records(workableValues.rec(body)['recruiters']);
+ return { recruiters, count: recruiters.length };
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/actions/move-candidate.ts b/packages/pieces/community/workable/src/lib/actions/move-candidate.ts
index 87c03fccca6..c3710a4e114 100644
--- a/packages/pieces/community/workable/src/lib/actions/move-candidate.ts
+++ b/packages/pieces/community/workable/src/lib/actions/move-candidate.ts
@@ -1,57 +1,36 @@
-import { workableAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { getAccountSubdomain } from '../common/get-subdomain';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { workableAuth } from '../auth';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp, jobDropdown, memberDropdown, stageDropdown } from '../common/props';
+import { workableSchemas } from '../common/schemas';
export const moveCandidate = createAction({
auth: workableAuth,
name: 'moveCandidate',
classification: 'WRITE',
displayName: 'Move Candidate',
- description: 'Moves candidate to the specified stage.',
- audience: 'both',
- aiMetadata: { description: 'Moves a Workable candidate into a target pipeline stage, recording the move on behalf of a given hiring-team member. Use to advance or change a candidate stage in the recruitment pipeline. Requires the candidate ID, the acting member ID, and the target stage slug (resolve valid slugs via Get Stages). Not idempotent — each call posts a stage transition.', idempotent: false },
+ description: 'Moves a candidate to another stage of their job pipeline.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Move a Workable candidate to a pipeline stage picked from dropdowns, recorded as the chosen hiring-team member. Running it again with the same stage leaves the candidate in that stage.',
+ idempotent: false,
+ },
+ outputSchema: workableSchemas.moved,
props: {
+ account_subdomain: accountSubdomainProp,
id: Property.ShortText({
- displayName: "Candidate's Id",
- description: "Id of candidate",
- required: true
- }),
- member_id: Property.ShortText({
- displayName: "Member's Id",
- description: "This person's Id is used to move the candidate to the next stage",
- required: true
+ displayName: 'Candidate ID',
+ description: 'The Workable candidate ID, for example "ce4da98".',
+ required: true,
}),
- target_stage: Property.ShortText({
- displayName: "Target stage name",
- description: "Slug of stage target should be moved to",
- required: true
- })
+ job: jobDropdown({ displayName: 'Job', description: "The candidate's job, used only to list its stages.", required: false }),
+ target_stage: stageDropdown({ required: true, description: 'Stage to move the candidate to.' }),
+ member_id: memberDropdown({ description: 'The hiring-team member the move is recorded for.' }),
},
async run(context) {
- // Action logic here
- const id = context.propsValue.id;
- const member_id = context.propsValue.member_id;
- const target_stage = context.propsValue.target_stage;
-
- const accessToken = context.auth.secret_text;
- const subdomain = await getAccountSubdomain(accessToken);
-
- const payload: Record<string, any> = {
- member_id: member_id,
- target_stage: target_stage
- }
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `https://${subdomain}.workable.com/spi/v3/candidates/${id}/move`,
- headers: {
- Authorization: `Bearer ${accessToken}`,
- Accept: "application/json"
- },
- body: payload
- })
-
- return response;
+ const p = context.propsValue;
+ const client = workableOps.client({ auth: context.auth, subdomain: p.account_subdomain });
+ return workableOps.moveCandidate({ client, candidateId: p.id, memberId: p.member_id, targetStage: p.target_stage });
},
});
diff --git a/packages/pieces/community/workable/src/lib/actions/rate-candidate.ts b/packages/pieces/community/workable/src/lib/actions/rate-candidate.ts
index 7eb1d75f164..e0b7ff3da5a 100644
--- a/packages/pieces/community/workable/src/lib/actions/rate-candidate.ts
+++ b/packages/pieces/community/workable/src/lib/actions/rate-candidate.ts
@@ -1,79 +1,81 @@
-import { workableAuth } from '../auth';
+import { HttpMethod } from '@activepieces/pieces-common';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { getAccountSubdomain } from '../common/get-subdomain';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { workableAuth } from '../auth';
+import { encodeId, WorkableApiError } from '../common/client';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp, candidateIdProp, memberIdText } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { workableValues } from '../common/values';
+
+const MAX_GRADE: Record<string, number> = { thumbs: 2, stars: 4, numbers: 9 };
export const rateCandidate = createAction({
auth: workableAuth,
name: 'rateCandidate',
classification: 'WRITE',
- displayName: 'Rate candidate',
- description: 'Rates the candidate on workable.',
+ displayName: 'Rate Candidate',
+ description: 'Adds a rating with a comment to a candidate.',
audience: 'both',
- aiMetadata: { description: 'Adds a rating with a comment to a Workable candidate on behalf of a hiring-team member, using one of the thumbs, stars, or numbers scales. Use to record an evaluation of a candidate. Requires the candidate ID, the acting member ID, a comment, the chosen scale, and a grade valid for that scale (thumbs 0-2, stars 0-4, numbers 0-9). Not idempotent — each call appends a new rating.', idempotent: false },
+ aiMetadata: {
+ description:
+ 'Add a rating with a comment to a Workable candidate on behalf of a hiring-team member. Scale thumbs takes grade 0-2, stars 0-4, numbers 0-9 (whole numbers); out-of-range grades are refused before calling Workable. Find the member ID with Get Members. Each member can rate a candidate once; a second rating by the same member is refused. Talent-pool candidates (no job) cannot be rated.',
+ idempotent: false,
+ },
+ outputSchema: workableSchemas.rated,
props: {
- id: Property.ShortText({
- displayName: "Candidate's Id",
- description: "Id of candidate",
- required: true
- }),
- member_id: Property.ShortText({
- displayName: "Member's Id",
- description: "Id of member that is adding the rating",
- required: true
- }),
- comment: Property.LongText({
- displayName: "Comment",
- description: "Comment about the scoring of the candidate",
- required: true
- }),
+ account_subdomain: accountSubdomainProp,
+ id: candidateIdProp,
+ member_id: memberIdText({ description: 'ID of the member adding the rating. Find it with Get Members.' }),
+ comment: Property.LongText({ displayName: 'Comment', description: 'Comment about the rating.', required: true }),
scale: Property.StaticDropdown({
- displayName: "Rating scale",
- description: "Select scale to rate candidate on",
+ displayName: 'Rating Scale',
required: true,
options: {
options: [
- {label: "Thumbs", value: "thumbs"},
- {label: "Stars", value: "stars"},
- {label: "Numbers", value: "numbers"}
- ]
- }
+ { label: 'Thumbs (0-2)', value: 'thumbs' },
+ { label: 'Stars (0-4)', value: 'stars' },
+ { label: 'Numbers (0-9)', value: 'numbers' },
+ ],
+ },
}),
- grade: Property.Number({
- displayName: "Grade",
- description: "Thumbs scale: 0-2, Stars scale: 0-4, Numbers scale: 0-9",
- required: true
- })
+ grade: Property.Number({ displayName: 'Grade', description: 'Thumbs: 0-2, Stars: 0-4, Numbers: 0-9.', required: true }),
},
async run(context) {
- // Action logic here
- const id = context.propsValue.id;
- const member_id = context.propsValue.member_id;
- const comment = context.propsValue.comment;
- const scale = context.propsValue.scale;
- const grade = context.propsValue.grade;
-
- const accessToken = context.auth.secret_text;
- const subdomain = await getAccountSubdomain(accessToken);
-
- const body: Record<string, any> = {
- comment,
- scale,
- member_id,
- grade
- };
-
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `https://${subdomain}.workable.com/spi/v3/candidates/${id}/ratings`,
- headers: {
- Authorization: `Bearer ${accessToken}`,
- Accept: "application/json"
- },
- body: body
-
- })
- return response;
+ const p = context.propsValue;
+ const scale = workableValues.optionalText(p.scale);
+ if (scale === undefined || MAX_GRADE[scale] === undefined) {
+ throw new Error('Rating Scale must be thumbs, stars or numbers.');
+ }
+ const grade = workableValues.integer({ value: p.grade, label: `Grade for the ${scale} scale`, min: 0, max: MAX_GRADE[scale] });
+ if (grade === undefined) {
+ throw new Error('Grade is required.');
+ }
+ const comment = workableValues.optionalText(p.comment);
+ if (comment === undefined) {
+ throw new Error('Comment is required.');
+ }
+ const memberId = workableValues.optionalText(p.member_id);
+ if (memberId === undefined) {
+ throw new Error('Acting Member ID is required.');
+ }
+ const id = encodeId({ value: p.id, label: 'Candidate ID' });
+ const client = workableOps.client({ auth: context.auth, subdomain: p.account_subdomain });
+ try {
+ await client.request({
+ method: HttpMethod.POST,
+ path: `/candidates/${id}/ratings`,
+ body: { member_id: memberId, comment, scale, grade },
+ });
+ } catch (error) {
+ if (error instanceof WorkableApiError && error.status === 422) {
+ throw new WorkableApiError({
+ message: `${error.message} Workable allows one rating per member per candidate, so this member may already have rated this candidate.`,
+ status: error.status,
+ responseBody: error.responseBody,
+ });
+ }
+ throw error;
+ }
+ return { success: true, candidate_id: decodeURIComponent(id), scale, grade };
},
});
diff --git a/packages/pieces/community/workable/src/lib/actions/revert-disqualification.ts b/packages/pieces/community/workable/src/lib/actions/revert-disqualification.ts
new file mode 100644
index 00000000000..5cc423d4af8
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/revert-disqualification.ts
@@ -0,0 +1,39 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { encodeId } from '../common/client';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp, candidateIdProp, memberIdText } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { workableValues } from '../common/values';
+
+export const revertDisqualification = createAction({
+ auth: workableAuth,
+ name: 'revert_disqualification',
+ classification: 'WRITE',
+ displayName: 'Revert Disqualification',
+ description: 'Brings a disqualified candidate back into the pipeline.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Undo the disqualification of a Workable candidate on behalf of a hiring-team member (member ID from Get Members). The candidate returns to the stage they were in.',
+ idempotent: true,
+ },
+ outputSchema: workableSchemas.disqualified,
+ props: {
+ account_subdomain: accountSubdomainProp,
+ id: candidateIdProp,
+ member_id: memberIdText({ description: 'ID of the member reverting the disqualification. Find it with Get Members.' }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const memberId = workableValues.optionalText(p.member_id);
+ if (memberId === undefined) {
+ throw new Error('Acting Member ID is required.');
+ }
+ const id = encodeId({ value: p.id, label: 'Candidate ID' });
+ const client = workableOps.client({ auth: context.auth, subdomain: p.account_subdomain });
+ await client.request({ method: HttpMethod.POST, path: `/candidates/${id}/revert`, body: { member_id: memberId } });
+ return { success: true, candidate_id: decodeURIComponent(id), disqualified: false };
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/actions/update-candidate.ts b/packages/pieces/community/workable/src/lib/actions/update-candidate.ts
new file mode 100644
index 00000000000..be229b1cf64
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/actions/update-candidate.ts
@@ -0,0 +1,90 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { encodeId } from '../common/client';
+import { workableOps } from '../common/operations';
+import { accountSubdomainProp, candidateIdProp } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { workableValues } from '../common/values';
+
+const TEXT_FIELDS = ['firstname', 'lastname', 'email', 'headline', 'summary', 'phone', 'address', 'cover_letter'] as const;
+const CLEARABLE = ['headline', 'summary', 'phone', 'address', 'cover_letter'];
+
+export const updateCandidate = createAction({
+ auth: workableAuth,
+ name: 'update_candidate',
+ classification: 'WRITE',
+ displayName: 'Update Candidate',
+ description: "Updates a candidate's profile. Empty fields are left unchanged.",
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Update fields on an existing Workable candidate by candidate ID. Only the fields you give are changed; use Clear Fields to blank headline, summary, phone, address or cover letter. Skills replace the whole skill list when given. Use Add Candidate Tags for tags and Move Candidate for stages. Running it twice with the same values gives the same result.',
+ idempotent: true,
+ },
+ outputSchema: workableSchemas.candidate,
+ props: {
+ account_subdomain: accountSubdomainProp,
+ id: candidateIdProp,
+ firstname: Property.ShortText({ displayName: 'First Name', required: false }),
+ lastname: Property.ShortText({ displayName: 'Last Name', required: false }),
+ email: Property.ShortText({ displayName: 'Email', required: false }),
+ headline: Property.ShortText({ displayName: 'Headline', required: false }),
+ summary: Property.LongText({ displayName: 'Summary', required: false }),
+ phone: Property.ShortText({ displayName: 'Phone', required: false }),
+ address: Property.ShortText({ displayName: 'Address', required: false }),
+ cover_letter: Property.LongText({ displayName: 'Cover Letter', required: false }),
+ skills: Property.Array({
+ displayName: 'Skills',
+ description: 'Replaces all current skills when given. Leave empty to keep them.',
+ required: false,
+ }),
+ clear_fields: Property.StaticMultiSelectDropdown({
+ displayName: 'Clear Fields',
+ description: 'Fields to blank out on the candidate.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Headline', value: 'headline' },
+ { label: 'Summary', value: 'summary' },
+ { label: 'Phone', value: 'phone' },
+ { label: 'Address', value: 'address' },
+ { label: 'Cover Letter', value: 'cover_letter' },
+ ],
+ },
+ }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const v = workableValues;
+ const candidate: Record<string, unknown> = {};
+ const values: Record<string, unknown> = p;
+ for (const key of TEXT_FIELDS) {
+ const value = v.optionalText(values[key]);
+ if (value !== undefined) {
+ candidate[key] = value;
+ }
+ }
+ const clear = v.stringList({ value: p.clear_fields, label: 'Clear Fields' }) ?? [];
+ for (const key of clear) {
+ if (!CLEARABLE.includes(key)) {
+ throw new Error(`Clear Fields does not support "${key}".`);
+ }
+ if (key in candidate) {
+ throw new Error(`"${key}" is both set and cleared. Choose one.`);
+ }
+ candidate[key] = '';
+ }
+ const skills = v.stringList({ value: p.skills, label: 'Skills' });
+ if (skills !== undefined && skills.length > 0) {
+ candidate['skills'] = skills;
+ }
+ if (Object.keys(candidate).length === 0) {
+ throw new Error('Nothing to update. Fill at least one field or pick a field to clear.');
+ }
+ const id = encodeId({ value: p.id, label: 'Candidate ID' });
+ const client = workableOps.client({ auth: context.auth, subdomain: p.account_subdomain });
+ const body = await client.request({ method: HttpMethod.PATCH, path: `/candidates/${id}`, body: { candidate } });
+ return workableOps.unwrap({ body, key: 'candidate' });
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/auth.ts b/packages/pieces/community/workable/src/lib/auth.ts
index 0ad25452e3b..ad183e4c5bb 100644
--- a/packages/pieces/community/workable/src/lib/auth.ts
+++ b/packages/pieces/community/workable/src/lib/auth.ts
@@ -1,16 +1,33 @@
import { PieceAuth } from '@activepieces/pieces-framework';
+import { listAccounts, tokenOf, WorkableApiError } from './common/client';
export const workableAuth = PieceAuth.SecretText({
- displayName: "API Access Token",
- description: `
- 1. Click your profile icon in the upper right and navigate to Settings > Integrations > Apps.
- 2. Locate the API Access Tokens section near the top of the page.
- 3. Click the button **+ Generate API token**.
- 4. Select the following scopes:
- - r_jobs
- - r_candidates
- - w_candidates
- 5. Click Generate token to complete the process.
- `,
- required: true
- })
+ displayName: 'API Access Token',
+ description: `
+1. In Workable, click your profile icon in the upper right and open **Settings → Integrations**.
+2. In the **API Access Tokens** section, click **Generate new token**.
+3. Select these scopes:
+ - r_jobs
+ - r_candidates
+ - w_candidates
+ - w_comments (optional, for Add Comment)
+4. Click **Generate token** and paste it here. Workable shows the token only once.
+
+If the token can see several Workable accounts, steps use the first one unless you fill **Account Subdomain**.
+`,
+ required: true,
+ validate: async ({ auth }) => {
+ try {
+ const accounts = await listAccounts(tokenOf(auth));
+ if (accounts.length === 0) {
+ return { valid: false, error: 'This token cannot see any Workable account.' };
+ }
+ return { valid: true };
+ } catch (error) {
+ if (error instanceof WorkableApiError && (error.status === 401 || error.status === 403)) {
+ return { valid: false, error: 'Invalid API access token.' };
+ }
+ return { valid: false, error: error instanceof Error ? error.message : 'Could not reach Workable.' };
+ }
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/common/client.ts b/packages/pieces/community/workable/src/lib/common/client.ts
new file mode 100644
index 00000000000..a263985ac5a
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/common/client.ts
@@ -0,0 +1,299 @@
+import { httpClient, HttpMessageBody, HttpMethod, HttpRequest, QueryParams } from '@activepieces/pieces-common';
+
+export class WorkableApiError extends Error {
+ readonly status: number;
+ readonly responseBody: unknown;
+
+ constructor({ message, status, responseBody }: { message: string; status: number; responseBody: unknown }) {
+ super(message);
+ this.name = 'WorkableApiError';
+ this.status = status;
+ this.responseBody = responseBody;
+ }
+}
+
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+export function tokenOf(auth: unknown): string {
+ const raw = typeof auth === 'string' ? auth : isRecord(auth) ? auth['secret_text'] : undefined;
+ const token = typeof raw === 'string' ? raw.trim() : '';
+ if (token.length === 0) {
+ throw new Error('The Workable connection has no API access token.');
+ }
+ return token;
+}
+
+export function normalizeSubdomain(value: unknown): string | undefined {
+ if (value === undefined || value === null) {
+ return undefined;
+ }
+ if (typeof value !== 'string') {
+ throw new Error('Account Subdomain must be text, for example "acme" for acme.workable.com.');
+ }
+ const trimmed = value.trim().toLowerCase();
+ if (trimmed.length === 0) {
+ return undefined;
+ }
+ if (!SUBDOMAIN_PATTERN.test(trimmed)) {
+ throw new Error(
+ `Account Subdomain "${value}" is not valid. Enter only the subdomain, for example "acme" for acme.workable.com.`,
+ );
+ }
+ return trimmed;
+}
+
+export function encodeId({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'number' && Number.isFinite(value) ? String(value) : typeof value === 'string' ? value.trim() : '';
+ if (text.length === 0) {
+ throw new Error(`${label} is required.`);
+ }
+ if (text === '.' || text === '..' || /[/\\?#]/.test(text)) {
+ throw new Error(`${label} "${text}" is not a valid Workable ID.`);
+ }
+ return encodeURIComponent(text);
+}
+
+export function baseUrlFor(subdomain: string): string {
+ return `https://${subdomain}.workable.com/spi/v3`;
+}
+
+export function isSameApiUrl({ subdomain, candidate }: { subdomain: string; candidate: string }): boolean {
+ try {
+ const target = new URL(candidate);
+ const base = new URL(baseUrlFor(subdomain));
+ return (
+ target.protocol === 'https:' &&
+ target.origin === base.origin &&
+ target.username === '' &&
+ target.password === '' &&
+ (target.pathname === base.pathname || target.pathname.startsWith(`${base.pathname}/`)) &&
+ !target.pathname.split('/').some((segment) => segment === '..' || segment === '.')
+ );
+ } catch {
+ return false;
+ }
+}
+
+export function cursorFromPaging({ subdomain, body }: { subdomain: string; body: unknown }): string | null {
+ const paging = isRecord(body) ? body['paging'] : undefined;
+ const next = isRecord(paging) ? paging['next'] : undefined;
+ if (typeof next !== 'string' || next.length === 0) {
+ return null;
+ }
+ if (!isSameApiUrl({ subdomain, candidate: next })) {
+ throw new Error('Workable returned a next-page link for a different host, so it was not followed.');
+ }
+ const sinceId = new URL(next).searchParams.get('since_id');
+ return sinceId === null || sinceId.length === 0 ? null : sinceId;
+}
+
+function errorDetail(responseBody: unknown): string | undefined {
+ let parsed = responseBody;
+ if (typeof parsed === 'string') {
+ const trimmed = parsed.trim();
+ if (trimmed.length === 0) {
+ return undefined;
+ }
+ try {
+ parsed = JSON.parse(trimmed);
+ } catch {
+ return trimmed.startsWith('<') ? undefined : trimmed.slice(0, 500);
+ }
+ }
+ if (!isRecord(parsed)) {
+ return undefined;
+ }
+ const validation = parsed['validation_errors'];
+ if (isRecord(validation)) {
+ const parts = Object.entries(validation).map(([field, messages]) =>
+ `${field}: ${Array.isArray(messages) ? messages.map(String).join(', ') : String(messages)}`,
+ );
+ if (parts.length > 0) {
+ return parts.join('; ').slice(0, 500);
+ }
+ }
+ const single = parsed['error'] ?? parsed['message'];
+ return typeof single === 'string' ? single.slice(0, 500) : undefined;
+}
+
+const STATUS_MESSAGES: Record<number, string> = {
+ 400: 'Workable rejected the request as invalid',
+ 401: 'Workable rejected the API access token. Generate a new token in Settings → Integrations and update the connection',
+ 403: 'Workable denied access. The token may lack the scope for this step (r_jobs, r_candidates, w_candidates or w_comments)',
+ 404: 'Workable could not find the resource. Check the ID or shortcode and the account subdomain',
+ 409: 'Workable reported a conflict with the current state of the resource',
+ 422: 'Workable could not process the request',
+ 429: 'Workable rate limit reached (10 requests per 10 seconds for account tokens). Retry later',
+};
+
+export function buildWorkableError({ status, responseBody }: { status: number; responseBody: unknown }): WorkableApiError {
+ const base =
+ STATUS_MESSAGES[status] ??
+ (status >= 500
+ ? 'Workable returned a server error. Retry later'
+ : status >= 300 && status < 400
+ ? 'Workable answered with an unexpected redirect, which was not followed'
+ : 'Workable request failed');
+ const detail = errorDetail(responseBody);
+ const message = detail === undefined ? `${base} (HTTP ${status}).` : `${base} (HTTP ${status}): ${detail}`;
+ return new WorkableApiError({ message, status, responseBody });
+}
+
+function readHttpErrorResponse(error: unknown): { status: number; body: unknown } | undefined {
+ if (!isRecord(error) && !(error instanceof Error)) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ if (!isRecord(response)) {
+ return undefined;
+ }
+ const status = response['status'];
+ if (typeof status !== 'number') {
+ return undefined;
+ }
+ return { status, body: response['body'] };
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function assertPath(path: string): void {
+ if (
+ !path.startsWith('/') ||
+ path.startsWith('//') ||
+ path.includes('?') ||
+ path.includes('#') ||
+ path.includes('\\') ||
+ path.split('/').some((segment) => segment === '..' || segment === '.')
+ ) {
+ throw new Error(`Refusing to call Workable with an unexpected path: ${path}`);
+ }
+}
+
+async function send<T extends HttpMessageBody>({
+ token,
+ url,
+ method,
+ query,
+ body,
+}: {
+ token: string;
+ url: string;
+ method: HttpMethod;
+ query?: WorkableQuery;
+ body?: unknown;
+}): Promise<{ status: number; body: T }> {
+ const queryParams: QueryParams = {};
+ for (const [key, value] of Object.entries(query ?? {})) {
+ if (value !== undefined && value !== null && value !== '') {
+ queryParams[key] = String(value);
+ }
+ }
+ const request: HttpRequest = {
+ method,
+ url,
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
+ queryParams,
+ body,
+ followRedirects: false,
+ redactBodyInErrors: true,
+ timeout: REQUEST_TIMEOUT_MS,
+ };
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const response = await httpClient.sendRequest<T>(request);
+ if (response.status >= 300) {
+ throw buildWorkableError({ status: response.status, responseBody: response.body });
+ }
+ return { status: response.status, body: response.body };
+ } catch (error) {
+ if (error instanceof WorkableApiError) {
+ throw error;
+ }
+ const httpError = readHttpErrorResponse(error);
+ if (httpError === undefined) {
+ throw error;
+ }
+ if (httpError.status === 429 && attempt < MAX_RATE_LIMIT_RETRIES) {
+ await sleep(RATE_LIMIT_WINDOW_MS);
+ continue;
+ }
+ throw buildWorkableError({ status: httpError.status, responseBody: httpError.body });
+ }
+ }
+}
+
+export async function listAccounts(token: string): Promise<Record<string, unknown>[]> {
+ const response = await send<Record<string, unknown>>({ token, url: `${ROOT_URL}/accounts`, method: HttpMethod.GET });
+ const accounts = isRecord(response.body) ? response.body['accounts'] : undefined;
+ return Array.isArray(accounts) ? accounts.filter(isRecord) : [];
+}
+
+export async function resolveSubdomain({ token, subdomain }: { token: string; subdomain?: unknown }): Promise<string> {
+ const given = normalizeSubdomain(subdomain);
+ if (given !== undefined) {
+ return given;
+ }
+ const accounts = await listAccounts(token);
+ const first = accounts.map((account) => normalizeSubdomainOrUndefined(account['subdomain'])).find((value) => value !== undefined);
+ if (first === undefined) {
+ throw new Error('This Workable token cannot see any account. Check that the token belongs to an active Workable account.');
+ }
+ return first;
+}
+
+function normalizeSubdomainOrUndefined(value: unknown): string | undefined {
+ try {
+ return normalizeSubdomain(value);
+ } catch {
+ return undefined;
+ }
+}
+
+export function createWorkableClient({ auth, subdomain }: { auth: unknown; subdomain?: unknown }): WorkableClient {
+ const token = tokenOf(auth);
+ let resolved: Promise<string> | undefined;
+ const getSubdomain = (): Promise<string> => {
+ if (resolved === undefined) {
+ resolved = resolveSubdomain({ token, subdomain });
+ resolved.catch(() => {
+ resolved = undefined;
+ });
+ }
+ return resolved;
+ };
+ return {
+ token,
+ getSubdomain,
+ async request<T extends HttpMessageBody = HttpMessageBody>({ method, path, query, body }: WorkableCallParams): Promise<T> {
+ assertPath(path);
+ const sub = await getSubdomain();
+ const response = await send<T>({ token, url: `${baseUrlFor(sub)}${path}`, method, query, body });
+ return response.body;
+ },
+ };
+}
+
+export type WorkableQuery = Record<string, string | number | boolean | undefined | null>;
+
+export type WorkableCallParams = {
+ method: HttpMethod;
+ path: string;
+ query?: WorkableQuery;
+ body?: unknown;
+};
+
+export type WorkableClient = {
+ token: string;
+ getSubdomain: () => Promise<string>;
+ request: <T extends HttpMessageBody = HttpMessageBody>(params: WorkableCallParams) => Promise<T>;
+};
+
+export const ROOT_URL = 'https://workable.com/spi/v3';
+const SUBDOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
+const REQUEST_TIMEOUT_MS = 30000;
+const MAX_RATE_LIMIT_RETRIES = 2;
+const RATE_LIMIT_WINDOW_MS = 10000;
diff --git a/packages/pieces/community/workable/src/lib/common/get-subdomain.ts b/packages/pieces/community/workable/src/lib/common/get-subdomain.ts
deleted file mode 100644
index 6ec1b213a8e..00000000000
--- a/packages/pieces/community/workable/src/lib/common/get-subdomain.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { httpClient, HttpMethod } from "@activepieces/pieces-common";
-
-export async function getAccountSubdomain(accessToken: string){
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: "https://workable.com/spi/v3/accounts",
- headers: {
- Authorization: `Bearer ${accessToken}`,
- Accept: 'application/json'
- }
- });
- console.log("this is response" + response.body.accounts[0].subdomain);
-
- return response.body.accounts[0]?.subdomain;
-}
\ No newline at end of file
diff --git a/packages/pieces/community/workable/src/lib/common/operations.ts b/packages/pieces/community/workable/src/lib/common/operations.ts
new file mode 100644
index 00000000000..ea87142315f
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/common/operations.ts
@@ -0,0 +1,141 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createWorkableClient, cursorFromPaging, encodeId, WorkableApiError, WorkableClient } from './client';
+import { workableValues } from './values';
+
+const v = workableValues;
+
+function unwrap({ body, key }: { body: unknown; key: string }): Record<string, unknown> {
+ const record = v.rec(body);
+ return v.rec(key in record ? record[key] : record);
+}
+
+async function moveCandidate({
+ client,
+ candidateId,
+ memberId,
+ targetStage,
+}: {
+ client: WorkableClient;
+ candidateId: unknown;
+ memberId: unknown;
+ targetStage: unknown;
+}) {
+ const id = encodeId({ value: candidateId, label: 'Candidate ID' });
+ const member = v.optionalText(memberId);
+ const stage = v.optionalText(targetStage);
+ if (member === undefined) {
+ throw new Error('Acting Member ID is required. Find it with Get Members.');
+ }
+ if (stage === undefined) {
+ throw new Error('Target Stage is required. Use a stage slug from Get Stages, for example "phone-screen".');
+ }
+ await client.request({ method: HttpMethod.POST, path: `/candidates/${id}/move`, body: { member_id: member, target_stage: stage } });
+ return { success: true, candidate_id: decodeURIComponent(id), target_stage: stage };
+}
+
+function buildCandidate(input: CandidateInput): Record<string, unknown> {
+ const candidate: Record<string, unknown> = {};
+ const firstname = v.optionalText(input.firstname);
+ const lastname = v.optionalText(input.lastname);
+ const email = v.optionalText(input.email);
+ if (firstname === undefined || lastname === undefined) {
+ throw new Error('First Name and Last Name are both required.');
+ }
+ if (email === undefined) {
+ throw new Error('Email is required by Workable.');
+ }
+ candidate['firstname'] = firstname;
+ candidate['lastname'] = lastname;
+ candidate['email'] = email;
+ for (const key of ['headline', 'summary', 'phone', 'address', 'cover_letter', 'resume_url'] as const) {
+ const value = v.optionalText(input[key]);
+ if (value !== undefined) {
+ candidate[key] = value;
+ }
+ }
+ const resumeUrl = candidate['resume_url'];
+ if (typeof resumeUrl === 'string' && !/^https?:\/\//i.test(resumeUrl)) {
+ throw new Error('Resume URL must start with http:// or https://.');
+ }
+ const skills = v.stringList({ value: input.skills, label: 'Skills' });
+ if (skills !== undefined && skills.length > 0) {
+ candidate['skills'] = skills;
+ }
+ const tags = v.stringList({ value: input.tags, label: 'Tags' });
+ if (tags !== undefined && tags.length > 0) {
+ candidate['tags'] = tags;
+ }
+ return candidate;
+}
+
+async function createCandidate({ client, jobShortcode, stage, sourced, input }: CreateCandidateParams) {
+ const candidate = buildCandidate(input);
+ const shortcode = v.optionalText(jobShortcode);
+ const stageSlug = v.optionalText(stage);
+ const path = shortcode === undefined ? '/talent_pool/candidates' : `/jobs/${encodeId({ value: shortcode, label: 'Job Shortcode' })}/candidates`;
+ try {
+ const body = await client.request({
+ method: HttpMethod.POST,
+ path,
+ query: { stage: stageSlug },
+ body: { sourced: sourced !== false, candidate },
+ });
+ return { ...unwrap({ body, key: 'candidate' }), talent_pool: shortcode === undefined };
+ } catch (error) {
+ if (error instanceof WorkableApiError && error.status === 422 && /already (exists|being used)/i.test(error.message)) {
+ throw new WorkableApiError({
+ message: `${error.message.replace(/\.?$/, '.')} Use List Candidates with this email to find the existing candidate, then Update Candidate or Copy Candidate to Job.`,
+ status: error.status,
+ responseBody: error.responseBody,
+ });
+ }
+ throw error;
+ }
+}
+
+async function listPage({
+ client,
+ path,
+ key,
+ query,
+ limit,
+ cursor,
+}: {
+ client: WorkableClient;
+ path: string;
+ key: string;
+ query: Record<string, string | number | undefined>;
+ limit: unknown;
+ cursor: unknown;
+}) {
+ const pageSize = v.integer({ value: limit, label: 'Limit', min: 1, max: 100 }) ?? 50;
+ const sinceId = v.optionalText(cursor);
+ const body = await client.request({ method: HttpMethod.GET, path, query: { ...query, limit: pageSize, since_id: sinceId } });
+ const items = v.records(v.rec(body)[key]);
+ const nextCursor = cursorFromPaging({ subdomain: await client.getSubdomain(), body });
+ return { [key]: items, count: items.length, nextCursor, hasMore: nextCursor !== null };
+}
+
+export const workableOps = { unwrap, moveCandidate, createCandidate, buildCandidate, listPage, client: createWorkableClient };
+
+export type CandidateInput = {
+ firstname?: unknown;
+ lastname?: unknown;
+ email?: unknown;
+ headline?: unknown;
+ summary?: unknown;
+ phone?: unknown;
+ address?: unknown;
+ cover_letter?: unknown;
+ resume_url?: unknown;
+ skills?: unknown;
+ tags?: unknown;
+};
+
+type CreateCandidateParams = {
+ client: WorkableClient;
+ jobShortcode: unknown;
+ stage: unknown;
+ sourced: unknown;
+ input: CandidateInput;
+};
diff --git a/packages/pieces/community/workable/src/lib/common/props.ts b/packages/pieces/community/workable/src/lib/common/props.ts
new file mode 100644
index 00000000000..c2c7a7f3554
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/common/props.ts
@@ -0,0 +1,197 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { createWorkableClient, cursorFromPaging, encodeId, WorkableClient } from './client';
+import { workableValues } from './values';
+
+const v = workableValues;
+
+export const accountSubdomainProp = Property.ShortText({
+ displayName: 'Account Subdomain',
+ description:
+ 'Only needed when your token can see several Workable accounts. Enter the subdomain, for example "acme" for acme.workable.com. Empty uses the first account.',
+ required: false,
+});
+
+export async function fetchAllPages({
+ client,
+ path,
+ key,
+ query = {},
+}: {
+ client: WorkableClient;
+ path: string;
+ key: string;
+ query?: Record<string, string | number | undefined>;
+}): Promise<{ items: Record<string, unknown>[]; truncated: boolean }> {
+ const subdomain = await client.getSubdomain();
+ const items: Record<string, unknown>[] = [];
+ let sinceId: string | null = null;
+ for (let page = 0; page < MAX_DROPDOWN_PAGES; page++) {
+ const body = await client.request({ method: HttpMethod.GET, path, query: { ...query, limit: 100, since_id: sinceId ?? undefined } });
+ items.push(...v.records(v.rec(body)[key]));
+ sinceId = cursorFromPaging({ subdomain, body });
+ if (sinceId === null) {
+ return { items, truncated: false };
+ }
+ }
+ return { items, truncated: true };
+}
+
+function failure(error: unknown) {
+ return {
+ disabled: true,
+ placeholder: error instanceof Error ? `Could not load from Workable: ${error.message}`.slice(0, 300) : 'Could not load from Workable.',
+ options: [],
+ };
+}
+
+const notConnected = { disabled: true, placeholder: 'Connect your Workable account first.', options: [] };
+
+export function jobDropdown({ displayName, description, required }: { displayName: string; description: string; required: boolean }) {
+ return Property.Dropdown({
+ auth: workableAuth,
+ displayName,
+ description,
+ required,
+ refreshers: ['account_subdomain'],
+ options: async ({ auth, account_subdomain }) => {
+ if (!auth) {
+ return notConnected;
+ }
+ try {
+ const client = createWorkableClient({ auth, subdomain: account_subdomain });
+ const { items, truncated } = await fetchAllPages({ client, path: '/jobs', key: 'jobs' });
+ const options = items
+ .filter((job) => v.str(job['shortcode']) !== null)
+ .map((job) => {
+ const shortcode = v.str(job['shortcode']) ?? '';
+ const state = v.str(job['state']);
+ return {
+ label: `${v.str(job['title']) ?? shortcode} (${shortcode}${state ? `, ${state}` : ''})`,
+ value: shortcode,
+ };
+ });
+ return {
+ disabled: false,
+ options,
+ placeholder: truncated ? 'Showing the first 5,000 jobs. Use the AI version or Custom API Call for others.' : undefined,
+ };
+ } catch (error) {
+ return failure(error);
+ }
+ },
+ });
+}
+
+export function stageDropdown({ required, description }: { required: boolean; description: string }) {
+ return Property.Dropdown({
+ auth: workableAuth,
+ displayName: 'Stage',
+ description,
+ required,
+ refreshers: ['account_subdomain', 'job'],
+ options: async ({ auth, account_subdomain, job }) => {
+ if (!auth) {
+ return notConnected;
+ }
+ if (typeof job !== 'string' || job.length === 0) {
+ return { disabled: true, placeholder: 'Select a job first.', options: [] };
+ }
+ try {
+ const client = createWorkableClient({ auth, subdomain: account_subdomain });
+ const body = await client.request({ method: HttpMethod.GET, path: `/jobs/${encodeId({ value: job, label: 'Job' })}/stages` });
+ return {
+ disabled: false,
+ options: v
+ .records(v.rec(body)['stages'])
+ .filter((stage) => v.str(stage['slug']) !== null)
+ .map((stage) => ({ label: v.str(stage['name']) ?? v.str(stage['slug']) ?? '', value: v.str(stage['slug']) ?? '' })),
+ };
+ } catch (error) {
+ return failure(error);
+ }
+ },
+ });
+}
+
+export function memberDropdown({ description }: { description: string }) {
+ return Property.Dropdown({
+ auth: workableAuth,
+ displayName: 'Acting Member',
+ description,
+ required: true,
+ refreshers: ['account_subdomain'],
+ options: async ({ auth, account_subdomain }) => {
+ if (!auth) {
+ return notConnected;
+ }
+ try {
+ const client = createWorkableClient({ auth, subdomain: account_subdomain });
+ const { items, truncated } = await fetchAllPages({ client, path: '/members', key: 'members' });
+ return {
+ disabled: false,
+ options: items
+ .filter((member) => v.str(member['id']) !== null)
+ .map((member) => ({
+ label: `${v.str(member['name']) ?? v.str(member['id'])}${v.str(member['email']) ? ` <${v.str(member['email'])}>` : ''}`,
+ value: v.str(member['id']) ?? '',
+ })),
+ placeholder: truncated ? 'Showing the first 5,000 members.' : undefined,
+ };
+ } catch (error) {
+ return failure(error);
+ }
+ },
+ });
+}
+
+export function memberIdText({ description }: { description: string }) {
+ return Property.ShortText({ displayName: 'Acting Member ID', description, required: true });
+}
+
+export const candidateIdProp = Property.ShortText({
+ displayName: 'Candidate ID',
+ description: 'The Workable candidate ID, for example "ce4da98". Find it with List Candidates or in the candidate URL.',
+ required: true,
+});
+
+const MAX_DROPDOWN_PAGES = 50;
+
+export function candidateFieldProps() {
+ return {
+ firstname: Property.ShortText({ displayName: 'First Name', required: true }),
+ lastname: Property.ShortText({ displayName: 'Last Name', required: true }),
+ email: Property.ShortText({ displayName: 'Email', description: 'Workable requires an email and refuses a second candidate with the same email on one job.', required: true }),
+ headline: Property.ShortText({ displayName: 'Headline', required: false }),
+ summary: Property.LongText({ displayName: 'Summary', required: false }),
+ phone: Property.ShortText({ displayName: 'Phone', required: false }),
+ address: Property.ShortText({ displayName: 'Address', required: false }),
+ cover_letter: Property.LongText({ displayName: 'Cover Letter', required: false }),
+ resume_url: Property.ShortText({ displayName: 'Resume URL', description: 'Public URL of the resume file. Workable downloads it.', required: false }),
+ skills: Property.Array({ displayName: 'Skills', required: false }),
+ tags: Property.Array({ displayName: 'Tags', required: false }),
+ sourced: Property.Checkbox({
+ displayName: 'Sourced',
+ description: 'On (default): the candidate is added as sourced and gets no email. Off: added as an applicant, and Workable sends the thank-you email.',
+ required: false,
+ defaultValue: true,
+ }),
+ };
+}
+
+export function candidateInputFrom(props: Record<string, unknown>) {
+ return {
+ firstname: props['firstname'],
+ lastname: props['lastname'],
+ email: props['email'],
+ headline: props['headline'],
+ summary: props['summary'],
+ phone: props['phone'],
+ address: props['address'],
+ cover_letter: props['cover_letter'],
+ resume_url: props['resume_url'],
+ skills: props['skills'],
+ tags: props['tags'],
+ };
+}
diff --git a/packages/pieces/community/workable/src/lib/common/schemas.ts b/packages/pieces/community/workable/src/lib/common/schemas.ts
new file mode 100644
index 00000000000..1584ea1fc83
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/common/schemas.ts
@@ -0,0 +1,263 @@
+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
+
+function f({ key, label, format }: { key: string; label: string; format?: OutputSchemaField['format'] }): OutputSchemaField {
+ return format === undefined ? { key, label } : { key, label, format };
+}
+
+const jobRefFields: OutputSchemaField[] = [f({ key: 'shortcode', label: 'Job Shortcode' }), f({ key: 'title', label: 'Job Title' })];
+
+const candidateSummaryFields: OutputSchemaField[] = [
+ f({ key: 'id', label: 'Candidate ID' }),
+ f({ key: 'name', label: 'Name' }),
+ f({ key: 'firstname', label: 'First Name' }),
+ f({ key: 'lastname', label: 'Last Name' }),
+ f({ key: 'headline', label: 'Headline' }),
+ f({ key: 'email', label: 'Email', format: 'email' }),
+ f({ key: 'phone', label: 'Phone' }),
+ f({ key: 'stage', label: 'Stage' }),
+ f({ key: 'stage_kind', label: 'Stage Kind' }),
+ f({ key: 'disqualified', label: 'Disqualified', format: 'boolean' }),
+ f({ key: 'disqualification_reason', label: 'Disqualification Reason' }),
+ f({ key: 'sourced', label: 'Sourced', format: 'boolean' }),
+ f({ key: 'domain', label: 'Source Domain' }),
+ f({ key: 'profile_url', label: 'Profile URL', format: 'url' }),
+ { key: 'job', label: 'Job', children: jobRefFields },
+ f({ key: 'created_at', label: 'Created At', format: 'datetime' }),
+ f({ key: 'updated_at', label: 'Updated At', format: 'datetime' }),
+];
+
+const candidateFields: OutputSchemaField[] = [
+ ...candidateSummaryFields,
+ f({ key: 'address', label: 'Address' }),
+ f({ key: 'summary', label: 'Summary' }),
+ f({ key: 'cover_letter', label: 'Cover Letter' }),
+ f({ key: 'resume_url', label: 'Resume URL', format: 'url' }),
+ f({ key: 'image_url', label: 'Image URL', format: 'image' }),
+ f({ key: 'outbound_mailbox', label: 'Outbound Mailbox', format: 'email' }),
+ { key: 'tags', label: 'Tags' },
+ { key: 'skills', label: 'Skills', labelKey: 'name', listItems: [f({ key: 'name', label: 'Skill' })] },
+ {
+ key: 'social_profiles',
+ label: 'Social Profiles',
+ labelKey: 'type',
+ listItems: [f({ key: 'type', label: 'Type' }), f({ key: 'url', label: 'URL', format: 'url' })],
+ },
+ {
+ key: 'experience_entries',
+ label: 'Experience',
+ labelKey: 'company',
+ listItems: [
+ f({ key: 'title', label: 'Title' }),
+ f({ key: 'company', label: 'Company' }),
+ f({ key: 'start_date', label: 'Start Date', format: 'date' }),
+ f({ key: 'end_date', label: 'End Date', format: 'date' }),
+ f({ key: 'current', label: 'Current', format: 'boolean' }),
+ ],
+ },
+ {
+ key: 'education_entries',
+ label: 'Education',
+ labelKey: 'school',
+ listItems: [
+ f({ key: 'school', label: 'School' }),
+ f({ key: 'degree', label: 'Degree' }),
+ f({ key: 'field_of_study', label: 'Field of Study' }),
+ f({ key: 'start_date', label: 'Start Date', format: 'date' }),
+ f({ key: 'end_date', label: 'End Date', format: 'date' }),
+ ],
+ },
+];
+
+const jobFields: OutputSchemaField[] = [
+ f({ key: 'id', label: 'Job ID' }),
+ f({ key: 'shortcode', label: 'Shortcode' }),
+ f({ key: 'title', label: 'Title' }),
+ f({ key: 'full_title', label: 'Full Title' }),
+ f({ key: 'code', label: 'Job Code' }),
+ f({ key: 'state', label: 'State' }),
+ f({ key: 'department', label: 'Department' }),
+ f({ key: 'url', label: 'Job URL', format: 'url' }),
+ f({ key: 'application_url', label: 'Application URL', format: 'url' }),
+ f({ key: 'shortlink', label: 'Short Link', format: 'url' }),
+ {
+ key: 'location',
+ label: 'Location',
+ children: [
+ f({ key: 'location_str', label: 'Location' }),
+ f({ key: 'country', label: 'Country' }),
+ f({ key: 'country_code', label: 'Country Code' }),
+ f({ key: 'region', label: 'Region' }),
+ f({ key: 'city', label: 'City' }),
+ f({ key: 'zip_code', label: 'ZIP Code' }),
+ f({ key: 'telecommuting', label: 'Remote', format: 'boolean' }),
+ ],
+ },
+ f({ key: 'created_at', label: 'Created At', format: 'datetime' }),
+];
+
+const jobDetailFields: OutputSchemaField[] = [
+ ...jobFields,
+ f({ key: 'description', label: 'Description', format: 'html' }),
+ f({ key: 'requirements', label: 'Requirements', format: 'html' }),
+ f({ key: 'benefits', label: 'Benefits', format: 'html' }),
+ f({ key: 'employment_type', label: 'Employment Type' }),
+ f({ key: 'industry', label: 'Industry' }),
+ f({ key: 'function', label: 'Function' }),
+ f({ key: 'experience', label: 'Experience' }),
+ f({ key: 'education', label: 'Education' }),
+ f({ key: 'keywords', label: 'Keywords' }),
+];
+
+const memberFields: OutputSchemaField[] = [
+ f({ key: 'id', label: 'Member ID' }),
+ f({ key: 'name', label: 'Name' }),
+ f({ key: 'headline', label: 'Headline' }),
+ f({ key: 'email', label: 'Email', format: 'email' }),
+ f({ key: 'role', label: 'Role' }),
+ f({ key: 'active', label: 'Active', format: 'boolean' }),
+];
+
+const stageFields: OutputSchemaField[] = [
+ f({ key: 'slug', label: 'Stage Slug' }),
+ f({ key: 'name', label: 'Name' }),
+ f({ key: 'kind', label: 'Kind' }),
+ f({ key: 'position', label: 'Position', format: 'number' }),
+];
+
+function page({ key, label, labelKey, itemFields }: { key: string; label: string; labelKey: string; itemFields: OutputSchemaField[] }): OutputSchema {
+ return {
+ fields: [
+ { key, label, labelKey, listItems: itemFields },
+ f({ key: 'count', label: 'Items Returned', format: 'number' }),
+ {
+ key: 'nextCursor',
+ label: 'Next Cursor',
+ description: 'Pass this as Cursor to get the next page. Empty when there are no more results.',
+ },
+ f({ key: 'hasMore', label: 'Has More', format: 'boolean' }),
+ ],
+ };
+}
+
+function plainList({ key, label, labelKey, itemFields }: { key: string; label: string; labelKey: string; itemFields: OutputSchemaField[] }): OutputSchema {
+ return {
+ fields: [{ key, label, labelKey, listItems: itemFields }, f({ key: 'count', label: 'Items Returned', format: 'number' })],
+ };
+}
+
+export const workableSchemas = {
+ candidate: { fields: candidateFields } satisfies OutputSchema,
+ candidateWebhook: {
+ fields: [
+ ...candidateFields,
+ f({ key: 'event_type', label: 'Event Type' }),
+ f({ key: 'fired_at', label: 'Fired At', format: 'datetime' }),
+ ],
+ } satisfies OutputSchema,
+ createdCandidate: {
+ fields: [...candidateFields, f({ key: 'talent_pool', label: 'Added to Talent Pool', format: 'boolean' })],
+ } satisfies OutputSchema,
+ job: { fields: jobDetailFields } satisfies OutputSchema,
+ candidates: page({ key: 'candidates', label: 'Candidates', labelKey: 'name', itemFields: candidateSummaryFields }),
+ jobs: page({ key: 'jobs', label: 'Jobs', labelKey: 'title', itemFields: jobFields }),
+ members: page({ key: 'members', label: 'Members', labelKey: 'name', itemFields: memberFields }),
+ stages: plainList({ key: 'stages', label: 'Stages', labelKey: 'name', itemFields: stageFields }),
+ recruiters: plainList({
+ key: 'recruiters',
+ label: 'Recruiters',
+ labelKey: 'name',
+ itemFields: [f({ key: 'id', label: 'Recruiter ID' }), f({ key: 'name', label: 'Name' }), f({ key: 'email', label: 'Email', format: 'email' })],
+ }),
+ disqualificationReasons: plainList({
+ key: 'reasons',
+ label: 'Disqualification Reasons',
+ labelKey: 'description',
+ itemFields: [
+ f({ key: 'id', label: 'Reason ID' }),
+ f({ key: 'description', label: 'Reason' }),
+ f({ key: 'candidate_withdrew', label: 'Candidate Withdrew', format: 'boolean' }),
+ f({ key: 'position', label: 'Position', format: 'number' }),
+ ],
+ }),
+ questions: plainList({
+ key: 'questions',
+ label: 'Questions',
+ labelKey: 'body',
+ itemFields: [
+ f({ key: 'key', label: 'Question Key' }),
+ f({ key: 'body', label: 'Question' }),
+ f({ key: 'type', label: 'Type' }),
+ f({ key: 'required', label: 'Required', format: 'boolean' }),
+ { key: 'choices', label: 'Choices', labelKey: 'body', listItems: [f({ key: 'id', label: 'Choice ID' }), f({ key: 'body', label: 'Choice' })] },
+ ],
+ }),
+ activities: plainList({
+ key: 'activities',
+ label: 'Activities',
+ labelKey: 'action',
+ itemFields: [
+ f({ key: 'id', label: 'Activity ID' }),
+ f({ key: 'action', label: 'Action' }),
+ f({ key: 'stage_name', label: 'Stage' }),
+ { key: 'target_stage', label: 'Target Stage', children: [f({ key: 'slug', label: 'Stage Slug' }), f({ key: 'name', label: 'Stage Name' })] },
+ f({ key: 'body', label: 'Body' }),
+ { key: 'member', label: 'Member', children: [f({ key: 'id', label: 'Member ID' }), f({ key: 'name', label: 'Name' })] },
+ f({ key: 'created_at', label: 'Created At', format: 'datetime' }),
+ ],
+ }),
+ accounts: plainList({
+ key: 'accounts',
+ label: 'Accounts',
+ labelKey: 'name',
+ itemFields: [
+ f({ key: 'id', label: 'Account ID' }),
+ f({ key: 'name', label: 'Name' }),
+ f({ key: 'subdomain', label: 'Subdomain' }),
+ f({ key: 'description', label: 'Description' }),
+ f({ key: 'website_url', label: 'Website URL', format: 'url' }),
+ ],
+ }),
+ moved: {
+ fields: [
+ f({ key: 'success', label: 'Success', format: 'boolean' }),
+ f({ key: 'candidate_id', label: 'Candidate ID' }),
+ f({ key: 'target_stage', label: 'Target Stage' }),
+ ],
+ } satisfies OutputSchema,
+ rated: {
+ fields: [
+ f({ key: 'success', label: 'Success', format: 'boolean' }),
+ f({ key: 'candidate_id', label: 'Candidate ID' }),
+ f({ key: 'scale', label: 'Scale' }),
+ f({ key: 'grade', label: 'Grade', format: 'number' }),
+ ],
+ } satisfies OutputSchema,
+ commented: {
+ fields: [f({ key: 'success', label: 'Success', format: 'boolean' }), f({ key: 'candidate_id', label: 'Candidate ID' })],
+ } satisfies OutputSchema,
+ disqualified: {
+ fields: [
+ f({ key: 'success', label: 'Success', format: 'boolean' }),
+ f({ key: 'candidate_id', label: 'Candidate ID' }),
+ f({ key: 'disqualified', label: 'Disqualified', format: 'boolean' }),
+ ],
+ } satisfies OutputSchema,
+ tags: {
+ fields: [
+ f({ key: 'candidate_id', label: 'Candidate ID' }),
+ { key: 'tags', label: 'Tags' },
+ { key: 'added', label: 'Tags Added' },
+ ],
+ } satisfies OutputSchema,
+ copied: {
+ fields: [
+ f({ key: 'source_candidate_id', label: 'Source Candidate ID' }),
+ f({ key: 'target_job_shortcode', label: 'Target Job Shortcode' }),
+ {
+ key: 'candidate',
+ label: 'Copied Candidate',
+ children: [f({ key: 'id', label: 'New Candidate ID' }), f({ key: 'url', label: 'API URL', format: 'url' })],
+ },
+ ],
+ } satisfies OutputSchema,
+};
diff --git a/packages/pieces/community/workable/src/lib/common/values.ts b/packages/pieces/community/workable/src/lib/common/values.ts
new file mode 100644
index 00000000000..6a07b3168dd
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/common/values.ts
@@ -0,0 +1,101 @@
+import { isRecord } from './client';
+
+function rec(value: unknown): Record<string, unknown> {
+ return isRecord(value) ? value : {};
+}
+
+function list(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : [];
+}
+
+function records(value: unknown): Record<string, unknown>[] {
+ return list(value).filter(isRecord);
+}
+
+function str(value: unknown): string | null {
+ if (typeof value === 'string') {
+ return value;
+ }
+ if (typeof value === 'number' && Number.isFinite(value)) {
+ return String(value);
+ }
+ return null;
+}
+
+function optionalText(value: unknown): string | undefined {
+ if (value === undefined || value === null) {
+ return undefined;
+ }
+ const text = typeof value === 'string' ? value.trim() : String(value).trim();
+ return text.length === 0 ? undefined : text;
+}
+
+function stringList({ value, label }: { value: unknown; label: string }): string[] | undefined {
+ if (value === undefined || value === null) {
+ return undefined;
+ }
+ let items: unknown[];
+ if (Array.isArray(value)) {
+ items = value;
+ } else if (typeof value === 'string') {
+ const trimmed = value.trim();
+ if (trimmed.startsWith('[')) {
+ try {
+ const parsed: unknown = JSON.parse(trimmed);
+ items = Array.isArray(parsed) ? parsed : [trimmed];
+ } catch {
+ items = trimmed.split(',');
+ }
+ } else {
+ items = trimmed.length === 0 ? [] : trimmed.split(',');
+ }
+ } else {
+ throw new Error(`${label} must be a list of text values.`);
+ }
+ const result: string[] = [];
+ for (const item of items) {
+ const text = isRecord(item) ? optionalText(Object.values(item)[0]) : optionalText(item);
+ if (text !== undefined && !result.includes(text)) {
+ result.push(text);
+ }
+ }
+ return result;
+}
+
+function integer({ value, label, min, max }: { value: unknown; label: string; min: number; max: number }): number | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const parsed = typeof value === 'string' ? Number(value.trim()) : value;
+ if (typeof parsed !== 'number' || !Number.isInteger(parsed) || parsed < min || parsed > max) {
+ throw new Error(`${label} must be a whole number from ${min} to ${max}.`);
+ }
+ return parsed;
+}
+
+function bool(value: unknown): boolean | undefined {
+ if (Array.isArray(value)) {
+ return bool(value[0]);
+ }
+ if (value === true || value === 'true') {
+ return true;
+ }
+ if (value === false || value === 'false') {
+ return false;
+ }
+ return undefined;
+}
+
+function isoDate({ value, label }: { value: unknown; label: string }): string | undefined {
+ const text = optionalText(value);
+ if (text === undefined) {
+ return undefined;
+ }
+ const time = Date.parse(text);
+ if (Number.isNaN(time)) {
+ throw new Error(`${label} must be a date, for example 2026-10-01 or 2026-10-01T09:00:00Z.`);
+ }
+ return new Date(time).toISOString();
+}
+
+export const workableValues = { rec, list, records, str, optionalText, stringList, integer, bool, isoDate };
diff --git a/packages/pieces/community/workable/src/lib/common/webhooks.ts b/packages/pieces/community/workable/src/lib/common/webhooks.ts
index f45d614a743..3adfe976f86 100644
--- a/packages/pieces/community/workable/src/lib/common/webhooks.ts
+++ b/packages/pieces/community/workable/src/lib/common/webhooks.ts
@@ -1,45 +1,212 @@
-import { HttpMethod, httpClient, HttpRequest} from '@activepieces/pieces-common';
-
-export const workableCommon = {
- subscribeWebhook: async (
- subdomain: string,
- accessToken: string,
- webhookUrl: string,
- event: string,
- args: Record<string, any> = {}
- ) => {
- const request: HttpRequest = {
- method: HttpMethod.POST,
- url: `https://${subdomain}.workable.com/spi/v3/subscriptions`,
- headers: {
- Authorization: `Bearer ${accessToken}`,
- Accept: 'application/json',
- },
- body: {
- target: webhookUrl,
- event,
- args,
- }
- };
- const response = await httpClient.sendRequest<{id: string}>(request);
- return response.body;
+import { createHash, createHmac, timingSafeEqual } from 'crypto';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createWorkableClient, encodeId, isRecord, normalizeSubdomain, tokenOf, WorkableApiError } from './client';
+import { workableValues } from './values';
+
+const v = workableValues;
+
+async function enable({ auth, subdomain, webhookUrl, store, config, filters }: EnableParams): Promise<void> {
+ const client = createWorkableClient({ auth, subdomain });
+ const accountId = await client.getSubdomain();
+ const body = {
+ target: webhookUrl,
+ event: config.event,
+ args: {
+ account_id: accountId,
+ job_shortcode: v.optionalText(filters.jobShortcode) ?? '',
+ stage_slug: v.optionalText(filters.stageSlug) ?? '',
},
+ };
+ let created: unknown;
+ try {
+ created = await client.request({ method: HttpMethod.POST, path: '/subscriptions', body });
+ } catch (error) {
+ if (!(error instanceof WorkableApiError) || error.status !== 409) {
+ throw error;
+ }
+ await removeSubscriptionsForTarget({ client, webhookUrl });
+ created = await client.request({ method: HttpMethod.POST, path: '/subscriptions', body });
+ }
+ const id = v.str(v.rec(created)['id']);
+ if (id === null) {
+ throw new Error('Workable did not return the ID of the created webhook subscription.');
+ }
+ try {
+ await store.put(config.storeKey, { webhookId: id, subdomain: accountId });
+ } catch (error) {
+ await deleteSubscription({ client, id }).catch(() => undefined);
+ throw error;
+ }
+}
+
+async function removeSubscriptionsForTarget({ client, webhookUrl }: { client: ReturnType<typeof createWorkableClient>; webhookUrl: string }) {
+ const listed = await client.request({ method: HttpMethod.GET, path: '/subscriptions' });
+ const subscriptions = Array.isArray(listed) ? v.records(listed) : v.records(v.rec(listed)['subscriptions']);
+ for (const subscription of subscriptions) {
+ const id = v.str(subscription['id']);
+ if (id !== null && subscription['target'] === webhookUrl) {
+ await deleteSubscription({ client, id });
+ }
+ }
+}
+
+async function deleteSubscription({ client, id }: { client: ReturnType<typeof createWorkableClient>; id: string }): Promise<void> {
+ try {
+ await client.request({ method: HttpMethod.DELETE, path: `/subscriptions/${encodeId({ value: id, label: 'Subscription ID' })}` });
+ } catch (error) {
+ if (error instanceof WorkableApiError && error.status === 404) {
+ return;
+ }
+ throw error;
+ }
+}
+
+async function disable({ auth, subdomain, store, config }: DisableParams): Promise<void> {
+ const stored = v.rec(await store.get<unknown>(config.storeKey));
+ const id = v.str(stored['webhookId']);
+ if (id !== null) {
+ const storedSubdomain = typeof stored['subdomain'] === 'string' ? stored['subdomain'] : undefined;
+ const client = createWorkableClient({ auth, subdomain: storedSubdomain ?? subdomain });
+ await deleteSubscription({ client, id });
+ }
+ await store.delete(config.storeKey);
+ await store.delete(config.deliveriesKey);
+}
+
+function headerValue({ headers, name }: { headers: unknown; name: string }): string | undefined {
+ if (!isRecord(headers)) {
+ return undefined;
+ }
+ const match = Object.entries(headers).find(([key]) => key.toLowerCase() === name);
+ const value = match?.[1];
+ const single = Array.isArray(value) ? value[0] : value;
+ return typeof single === 'string' && single.trim().length > 0 ? single.trim() : undefined;
+}
+
+function safeEqual({ a, b }: { a: string; b: string }): boolean {
+ const left = Buffer.from(a, 'utf8');
+ const right = Buffer.from(b, 'utf8');
+ return left.length === right.length && timingSafeEqual(left, right);
+}
+
+function verifySignature({ token, rawBody, headers }: { token: string; rawBody: unknown; headers: unknown }): boolean {
+ if (typeof rawBody !== 'string' && !Buffer.isBuffer(rawBody)) {
+ return false;
+ }
+ const received = headerValue({ headers, name: SIGNATURE_HEADER });
+ if (received === undefined) {
+ return false;
+ }
+ const signature = received.startsWith('sha256=') ? received.slice('sha256='.length) : received;
+ const digest = createHmac('sha256', token).update(rawBody).digest();
+ return safeEqual({ a: signature.toLowerCase(), b: digest.toString('hex') }) || safeEqual({ a: signature, b: digest.toString('base64') });
+}
- unsubscribeWebhook: async (
- subdomain: string,
- accessToken: string,
- subscriptionId: string
- ) => {
- const request: HttpRequest = {
- method: HttpMethod.DELETE,
- url: `https://${subdomain}.workable.com/spi/v3/subscriptions/${subscriptionId}`,
- headers: {
- Authorization: `Bearer ${accessToken}`,
- Accept: 'application/json'
- }
- }
-
- return await httpClient.sendRequest(request);
+function parseBody({ rawBody, body }: { rawBody: unknown; body: unknown }): Record<string, unknown> | undefined {
+ if (typeof rawBody === 'string' || Buffer.isBuffer(rawBody)) {
+ try {
+ const parsed: unknown = JSON.parse(rawBody.toString());
+ return isRecord(parsed) ? parsed : undefined;
+ } catch {
+ return undefined;
}
+ }
+ return isRecord(body) ? body : undefined;
+}
+
+function isWithinWindow({ firedAt, nowMs }: { firedAt: unknown; nowMs: number }): boolean {
+ const text = v.str(firedAt);
+ if (text === null) {
+ return true;
+ }
+ const time = Date.parse(text);
+ if (Number.isNaN(time)) {
+ return true;
+ }
+ return nowMs - time <= REPLAY_WINDOW_MS && time - nowMs <= CLOCK_SKEW_MS;
+}
+
+async function receive({ auth, payload, store, config, nowMs }: ReceiveParams): Promise<Record<string, unknown> | undefined> {
+ if (!verifySignature({ token: tokenOf(auth), rawBody: payload.rawBody, headers: payload.headers })) {
+ return undefined;
+ }
+ const envelope = parseBody({ rawBody: payload.rawBody, body: payload.body });
+ if (envelope === undefined) {
+ return undefined;
+ }
+ const eventType = v.str(envelope['event_type']);
+ if (eventType !== null && eventType !== config.event) {
+ return undefined;
+ }
+ if (!isWithinWindow({ firedAt: envelope['fired_at'], nowMs })) {
+ return undefined;
+ }
+ const rawText = Buffer.isBuffer(payload.rawBody) ? payload.rawBody : Buffer.from(String(payload.rawBody), 'utf8');
+ const deliveryKey = v.str(envelope['id']) ?? createHash('sha256').update(rawText).digest('hex');
+ const seen = v.list(await store.get<unknown>(config.deliveriesKey)).filter((item): item is string => typeof item === 'string');
+ if (seen.includes(deliveryKey)) {
+ return undefined;
+ }
+ await store.put(config.deliveriesKey, [...seen, deliveryKey].slice(-MAX_REMEMBERED_DELIVERIES));
+ return { ...v.rec(envelope['data']), event_type: eventType ?? config.event, fired_at: envelope['fired_at'] ?? null };
+}
+
+async function sample({ auth, subdomain, config, filters }: SampleParams): Promise<Record<string, unknown>[]> {
+ const client = createWorkableClient({ auth, subdomain });
+ const shortcode = v.optionalText(filters.jobShortcode);
+ const stage = v.optionalText(filters.stageSlug);
+ const since = new Date(Date.now() - SAMPLE_LOOKBACK_MS).toISOString();
+ const query = {
+ shortcode,
+ stage: shortcode === undefined ? undefined : stage,
+ limit: 100,
+ [config.event === 'candidate_moved' ? 'updated_after' : 'created_after']: since,
+ };
+ const listed = await client.request({ method: HttpMethod.GET, path: '/candidates', query });
+ const newest = v.records(v.rec(listed)['candidates']).slice(-SAMPLE_SIZE).reverse();
+ const result: Record<string, unknown>[] = [];
+ for (const item of newest) {
+ const id = v.str(item['id']);
+ if (id === null) {
+ continue;
+ }
+ const full = await client.request({ method: HttpMethod.GET, path: `/candidates/${encodeId({ value: id, label: 'Candidate ID' })}` });
+ const record = v.rec(v.rec(full)['candidate'] ?? full);
+ result.push({ ...record, event_type: config.event, fired_at: record['updated_at'] ?? null });
+ }
+ return result;
+}
+
+export const WEBHOOK_INSTRUCTIONS = `This trigger creates a Workable webhook subscription when the flow is published and removes it when the flow is turned off.
+
+Every delivery is checked against the **X-Workable-Signature** HMAC, signed with your API access token. Deliveries without a valid signature are ignored, and Workable retries of the same event run the flow only once.`;
+
+export const workableWebhook = { enable, disable, receive, sample, verifySignature, normalizeSubdomain };
+
+export type WebhookStore = {
+ get: <T>(key: string) => Promise<T | null>;
+ put: <T>(key: string, value: T) => Promise<T>;
+ delete: (key: string) => Promise<void>;
+};
+
+export type WebhookConfig = { event: 'candidate_created' | 'candidate_moved'; storeKey: string; deliveriesKey: string };
+
+type Filters = { jobShortcode?: unknown; stageSlug?: unknown };
+
+type EnableParams = { auth: unknown; subdomain?: unknown; webhookUrl: string; store: WebhookStore; config: WebhookConfig; filters: Filters };
+type DisableParams = { auth: unknown; subdomain?: unknown; store: WebhookStore; config: WebhookConfig };
+type ReceiveParams = {
+ auth: unknown;
+ payload: { body: unknown; rawBody?: unknown; headers?: unknown };
+ store: WebhookStore;
+ config: WebhookConfig;
+ nowMs: number;
+};
+type SampleParams = { auth: unknown; subdomain?: unknown; config: WebhookConfig; filters: Filters };
-}
\ No newline at end of file
+const SIGNATURE_HEADER = 'x-workable-signature';
+const MAX_REMEMBERED_DELIVERIES = 500;
+const REPLAY_WINDOW_MS = 6 * 60 * 60 * 1000;
+const CLOCK_SKEW_MS = 5 * 60 * 1000;
+const SAMPLE_LOOKBACK_MS = 90 * 24 * 60 * 60 * 1000;
+const SAMPLE_SIZE = 3;
diff --git a/packages/pieces/community/workable/src/lib/triggers/candidate-stage-changed.ts b/packages/pieces/community/workable/src/lib/triggers/candidate-stage-changed.ts
new file mode 100644
index 00000000000..62bfb798e5e
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/triggers/candidate-stage-changed.ts
@@ -0,0 +1,66 @@
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
+import { workableAuth } from '../auth';
+import { accountSubdomainProp } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { WEBHOOK_INSTRUCTIONS, WebhookConfig, workableWebhook } from '../common/webhooks';
+import { candidateSample } from './sample';
+
+const config: WebhookConfig = {
+ event: 'candidate_moved',
+ storeKey: '_candidate_stage_changed',
+ deliveriesKey: '_candidate_stage_changed_deliveries',
+};
+
+export const candidateStageChanged = createTrigger({
+ auth: workableAuth,
+ name: 'candidate_stage_changed',
+ classification: 'READ',
+ displayName: 'Candidate Stage Changed',
+ description: 'Triggers when a candidate is moved to another stage. Can be filtered by job and target stage.',
+ aiMetadata: {
+ description:
+ 'Fires once each time a Workable candidate is moved to another pipeline stage (candidate_moved event). The payload is the candidate as it is when Workable sends it, with the new stage. Can be limited to one job shortcode and/or one target stage slug. Deliveries are checked against the X-Workable-Signature HMAC.',
+ },
+ props: {
+ instructions: Property.MarkDown({ value: WEBHOOK_INSTRUCTIONS }),
+ account_subdomain: accountSubdomainProp,
+ shortcode: Property.ShortText({
+ displayName: 'Job Shortcode',
+ description: 'Shortcode of a job. Leave empty to trigger for all jobs.',
+ required: false,
+ }),
+ stage_slug: Property.ShortText({
+ displayName: 'Stage Slug',
+ description: "Stage slug, for example 'applied'. Only moves into this stage. Leave empty to trigger for all stages.",
+ required: false,
+ }),
+ },
+ sampleData: { ...candidateSample, stage: 'Phone Screen', updated_at: '2026-10-21T14:02:00Z', event_type: 'candidate_moved', fired_at: '2026-10-21T14:02:01Z' },
+ outputSchema: workableSchemas.candidateWebhook,
+ type: TriggerStrategy.WEBHOOK,
+ async onEnable(context) {
+ await workableWebhook.enable({
+ auth: context.auth,
+ subdomain: context.propsValue.account_subdomain,
+ webhookUrl: context.webhookUrl,
+ store: context.store,
+ config,
+ filters: { jobShortcode: context.propsValue.shortcode, stageSlug: context.propsValue.stage_slug },
+ });
+ },
+ async onDisable(context) {
+ await workableWebhook.disable({ auth: context.auth, subdomain: context.propsValue.account_subdomain, store: context.store, config });
+ },
+ async test(context) {
+ return workableWebhook.sample({
+ auth: context.auth,
+ subdomain: context.propsValue.account_subdomain,
+ config,
+ filters: { jobShortcode: context.propsValue.shortcode, stageSlug: context.propsValue.stage_slug },
+ });
+ },
+ async run(context) {
+ const delivery = await workableWebhook.receive({ auth: context.auth, payload: context.payload, store: context.store, config, nowMs: Date.now() });
+ return delivery === undefined ? [] : [delivery];
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/triggers/new-candidate.ts b/packages/pieces/community/workable/src/lib/triggers/new-candidate.ts
index 3d178d79ed5..630b729b53b 100644
--- a/packages/pieces/community/workable/src/lib/triggers/new-candidate.ts
+++ b/packages/pieces/community/workable/src/lib/triggers/new-candidate.ts
@@ -1,129 +1,66 @@
-
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
import { workableAuth } from '../auth';
-import { createTrigger, Property, TriggerStrategy, WebhookResponse } from '@activepieces/pieces-framework';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
-import { getAccountSubdomain } from '../common/get-subdomain';
-import { workableCommon } from '../common/webhooks';
-
-interface WebhookInformation {
- webhookId: string;
-}
+import { accountSubdomainProp } from '../common/props';
+import { workableSchemas } from '../common/schemas';
+import { WEBHOOK_INSTRUCTIONS, WebhookConfig, workableWebhook } from '../common/webhooks';
+import { candidateSample } from './sample';
-interface WorkableWebhookPayload {
- data: any;
- event_type: string;
- fired_at: string;
- id: string;
- resource_type: string;
-}
+const config: WebhookConfig = {
+ event: 'candidate_created',
+ storeKey: '_new_candidate_created',
+ deliveriesKey: '_new_candidate_created_deliveries',
+};
export const newCandidate = createTrigger({
- auth: workableAuth,
- name: 'newCandidate',
- classification: 'READ',
- displayName: 'New Candidate',
- description: 'Triggers when new candidate submits application. Can be filtered by specific job and/or hiring pipeline stage.',
- aiMetadata: {
- description: 'Fires when a new candidate is created in Workable (a candidate_created event), representing a newly submitted application. Can be scoped to a single job shortcode and/or a single pipeline stage slug, or left unfiltered to fire for all jobs and stages.',
- },
- props: {
- shortcode: Property.ShortText({
- displayName: "Shortcode",
- description: "Shortcode of specific job. Leave empty to trigger for all jobs.",
- required: false
- }),
- stage_slug: Property.ShortText({
- displayName: "Stage Slug",
- description: "Stage slug to filter by specific hiring pipeline stage (e.g., 'applied', 'phone_screen', 'interview', 'offer'). Leave empty to trigger for all stages.",
- required: false
- })
- },
- sampleData: {
- id: '123',
- name: 'John Doe',
- firstname: 'John',
- lastname: 'Doe',
- headline: 'Software Engineer',
- account: {
- subdomain: 'example',
- name: 'Example Inc.'
- },
- job: {
- shortcode: 'ENG123',
- title: 'Software Engineer'
- },
- stage: 'applied',
- disqualified: false,
- disqualification_reason: '',
- sourced: false,
- profile_url: 'https://example.workable.com/candidates/123',
- email: '[email protected]',
- domain: 'example.com',
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString(),
- },
- type: TriggerStrategy.WEBHOOK,
- async onEnable(context){
- const accessToken = context.auth.secret_text;
- const subdomain = await getAccountSubdomain(accessToken);
-
- const shortcode = context.propsValue.shortcode || '';
- const stageSlug = context.propsValue.stage_slug || '';
- const webhookUrl = context.webhookUrl;
- const event = "candidate_created";
-
- const subscription = await workableCommon.subscribeWebhook(
- subdomain,
- accessToken,
- webhookUrl,
- event,
- {job_shortcode: shortcode, stage_slug: stageSlug}
- );
-
- await context.store?.put<WebhookInformation>('_new_candidate_created', {
- webhookId: subscription.id,
- })
- },
- async onDisable(context){
- // implement webhook deletion logic
- const accessToken = context.auth.secret_text;
-
- const webhookInfo = await context.store.get<WebhookInformation>('_new_candidate_created');
-
- if(webhookInfo?.webhookId) {
- const subdomain = await getAccountSubdomain(accessToken);
- await workableCommon.unsubscribeWebhook(subdomain, accessToken, webhookInfo.webhookId);
- }
- },
- async test(context){
- const accessToken = context.auth.secret_text;
- const subdomain = await getAccountSubdomain(accessToken);
- const shortcode = context.propsValue.shortcode || '';
- const stageSlug = context.propsValue.stage_slug || '';
-
- const queryParams: any = {};
- if (shortcode) {
- queryParams.shortcode = shortcode;
- }
- if (stageSlug) {
- queryParams.stage = stageSlug;
- }
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `https://${subdomain}.workable.com/spi/v3/candidates/`,
- headers: {
- Authorization: `Bearer ${accessToken}`,
- Accept: "application/json"
- },
- queryParams: queryParams
- });
-
- const candidates = response.body.candidates?.slice(0, 3) ?? [];
- return candidates;
- },
- async run(context){
- const payload = context.payload.body as WorkableWebhookPayload;
- return [payload.data]
- }
-})
\ No newline at end of file
+ auth: workableAuth,
+ name: 'newCandidate',
+ classification: 'READ',
+ displayName: 'New Candidate',
+ description: 'Triggers when a new candidate is added. Can be filtered by job and pipeline stage.',
+ aiMetadata: {
+ description:
+ 'Fires once for each new Workable candidate (candidate_created event), for applications and sourced candidates alike. Can be limited to one job shortcode and/or one stage slug. Deliveries are checked against the X-Workable-Signature HMAC.',
+ },
+ props: {
+ instructions: Property.MarkDown({ value: WEBHOOK_INSTRUCTIONS }),
+ account_subdomain: accountSubdomainProp,
+ shortcode: Property.ShortText({
+ displayName: 'Job Shortcode',
+ description: 'Shortcode of a job. Leave empty to trigger for all jobs.',
+ required: false,
+ }),
+ stage_slug: Property.ShortText({
+ displayName: 'Stage Slug',
+ description: "Stage slug, for example 'applied'. Leave empty to trigger for all stages.",
+ required: false,
+ }),
+ },
+ sampleData: { ...candidateSample, event_type: 'candidate_created', fired_at: '2026-10-20T09:15:02Z' },
+ outputSchema: workableSchemas.candidateWebhook,
+ type: TriggerStrategy.WEBHOOK,
+ async onEnable(context) {
+ await workableWebhook.enable({
+ auth: context.auth,
+ subdomain: context.propsValue.account_subdomain,
+ webhookUrl: context.webhookUrl,
+ store: context.store,
+ config,
+ filters: { jobShortcode: context.propsValue.shortcode, stageSlug: context.propsValue.stage_slug },
+ });
+ },
+ async onDisable(context) {
+ await workableWebhook.disable({ auth: context.auth, subdomain: context.propsValue.account_subdomain, store: context.store, config });
+ },
+ async test(context) {
+ return workableWebhook.sample({
+ auth: context.auth,
+ subdomain: context.propsValue.account_subdomain,
+ config,
+ filters: { jobShortcode: context.propsValue.shortcode, stageSlug: context.propsValue.stage_slug },
+ });
+ },
+ async run(context) {
+ const delivery = await workableWebhook.receive({ auth: context.auth, payload: context.payload, store: context.store, config, nowMs: Date.now() });
+ return delivery === undefined ? [] : [delivery];
+ },
+});
diff --git a/packages/pieces/community/workable/src/lib/triggers/sample.ts b/packages/pieces/community/workable/src/lib/triggers/sample.ts
new file mode 100644
index 00000000000..444903d6f7f
--- /dev/null
+++ b/packages/pieces/community/workable/src/lib/triggers/sample.ts
@@ -0,0 +1,28 @@
+export const candidateSample = {
+ id: 'ce4da98',
+ name: 'Lakita Marrero',
+ firstname: 'Lakita',
+ lastname: 'Marrero',
+ headline: 'Operations Manager',
+ account: { subdomain: 'groove-tech', name: 'Groove Tech' },
+ job: { shortcode: 'GROOV005', title: 'Operations Manager' },
+ stage: 'Applied',
+ disqualified: false,
+ disqualification_reason: null,
+ sourced: true,
+ profile_url: 'https://groove-tech.workable.com/backend/jobs/128/browser/applied/candidate/4721',
+ email: '[email protected]',
+ domain: 'workable.com',
+ phone: '+1 555 0100',
+ address: 'Boston, MA',
+ summary: 'Operations manager with 8 years of experience.',
+ cover_letter: null,
+ resume_url: null,
+ tags: ['referral'],
+ skills: [{ name: 'operations' }],
+ social_profiles: [{ type: 'linkedin', url: 'https://www.linkedin.com/in/example' }],
+ experience_entries: [],
+ education_entries: [],
+ created_at: '2026-10-20T09:15:00Z',
+ updated_at: '2026-10-20T09:20:00Z',
+};
diff --git a/packages/pieces/community/workable/test/actions.test.ts b/packages/pieces/community/workable/test/actions.test.ts
new file mode 100644
index 00000000000..aa8aae4c0f2
--- /dev/null
+++ b/packages/pieces/community/workable/test/actions.test.ts
@@ -0,0 +1,310 @@
+import { addCandidateTags } from '../src/lib/actions/add-candidate-tags';
+import { addComment } from '../src/lib/actions/add-comment';
+import { createCandidateAi } from '../src/lib/actions/ai/create-candidate-ai';
+import { moveCandidateAi } from '../src/lib/actions/ai/move-candidate-ai';
+import { copyCandidateToJob } from '../src/lib/actions/copy-candidate-to-job';
+import { createCandidate } from '../src/lib/actions/create-candidate';
+import { disqualifyCandidate } from '../src/lib/actions/disqualify-candidate';
+import { getCandidate } from '../src/lib/actions/get-candidate';
+import { getCandidateActivities } from '../src/lib/actions/get-candidate-activities';
+import { getJob } from '../src/lib/actions/get-job';
+import { getMembers } from '../src/lib/actions/get-members';
+import { getStages } from '../src/lib/actions/get-stages';
+import { listAccounts } from '../src/lib/actions/list-accounts';
+import { listCandidates } from '../src/lib/actions/list-candidates';
+import { listDisqualificationReasons } from '../src/lib/actions/list-disqualification-reasons';
+import { listJobQuestions } from '../src/lib/actions/list-job-questions';
+import { listJobs } from '../src/lib/actions/list-jobs';
+import { listRecruiters } from '../src/lib/actions/list-recruiters';
+import { moveCandidate } from '../src/lib/actions/move-candidate';
+import { rateCandidate } from '../src/lib/actions/rate-candidate';
+import { revertDisqualification } from '../src/lib/actions/revert-disqualification';
+import { updateCandidate } from '../src/lib/actions/update-candidate';
+import { workable, workableCustomApiCall } from '../src/index';
+import { accountsReply, BASE, mockHttp, runAction, SUB } from './helpers';
+
+const S = { account_subdomain: SUB };
+
+describe('piece metadata', () => {
+ it('has the planned audiences and an outputSchema on every action and trigger', () => {
+ const actions = Object.values(workable.actions()).filter((a) => a.name !== 'custom_api_call');
+ expect(actions).toHaveLength(22);
+ const by = (aud: string) => actions.filter((a) => a.audience === aud).map((a) => a.name).sort();
+ expect(by('human')).toEqual(['create_candidate', 'moveCandidate']);
+ expect(by('ai')).toEqual(['create_candidate_ai', 'move_candidate_ai']);
+ expect(by('both')).toHaveLength(18);
+ for (const action of actions) {
+ expect(action.outputSchema, action.name).toBeDefined();
+ expect(action.aiMetadata?.description, action.name).toBeTruthy();
+ expect(action.classification, action.name).toBeDefined();
+ }
+ for (const trigger of Object.values(workable.triggers())) {
+ expect(trigger.outputSchema, trigger.name).toBeDefined();
+ }
+ });
+});
+
+describe('read actions', () => {
+ it('getCandidate resolves the subdomain once, encodes the ID and unwraps', async () => {
+ const requests = mockHttp([accountsReply, { body: { candidate: { id: 'a b' } } }]);
+ expect(await runAction(getCandidate)({ id: 'a b' })).toEqual({ id: 'a b' });
+ expect(requests.map((r) => r.url)).toEqual(['https://workable.com/spi/v3/accounts', `${BASE}/candidates/a%20b`]);
+ });
+
+ it('getJob sends include_fields only when asked', async () => {
+ const requests = mockHttp([{ body: { shortcode: 'J1' } }, { body: { shortcode: 'J1' } }]);
+ await runAction(getJob)({ ...S, shortcode: 'J1' });
+ await runAction(getJob)({ ...S, shortcode: 'J1', include_description: true });
+ expect(requests[0].url).toBe(`${BASE}/jobs/J1`);
+ expect(requests[0].queryParams).toEqual({});
+ expect(requests[1].queryParams).toEqual({ include_fields: 'description,requirements,benefits' });
+ });
+
+ it('getMembers returns a page with cursor', async () => {
+ const requests = mockHttp([{ body: { members: [{ id: 'm1' }], paging: { next: `${BASE}/members?since_id=m1&limit=1` } } }]);
+ const result = await runAction(getMembers)({ ...S, role: 'admin', limit: 1 });
+ expect(requests[0].queryParams).toEqual({ role: 'admin', limit: '1' });
+ expect(result).toEqual({ members: [{ id: 'm1' }], count: 1, nextCursor: 'm1', hasMore: true });
+ });
+
+ it('getMembers refuses a limit over 100 before any request', async () => {
+ const requests = mockHttp([]);
+ await expect(runAction(getMembers)({ ...S, limit: 500 })).rejects.toThrow('1 to 100');
+ expect(requests).toHaveLength(0);
+ });
+
+ it('getStages lists job or account stages', async () => {
+ const requests = mockHttp([{ body: { stages: [{ slug: 'applied' }] } }, { body: { stages: [] } }]);
+ expect(await runAction(getStages)({ ...S, shortcode: 'J1' })).toEqual({ stages: [{ slug: 'applied' }], count: 1 });
+ await runAction(getStages)({ ...S });
+ expect(requests.map((r) => r.url)).toEqual([`${BASE}/jobs/J1/stages`, `${BASE}/stages`]);
+ });
+
+ it('listCandidates sends filters and cursor', async () => {
+ const requests = mockHttp([{ body: { candidates: [{ id: 'c1' }], paging: {} } }]);
+ const result = await runAction(listCandidates)({
+ ...S,
+ email: '[email protected]',
+ shortcode: 'J1',
+ stage: 'applied',
+ created_after: '2026-10-01',
+ cursor: 'c0',
+ limit: '20',
+ });
+ expect(requests[0].url).toBe(`${BASE}/candidates`);
+ expect(requests[0].queryParams).toEqual({
+ email: '[email protected]',
+ shortcode: 'J1',
+ stage: 'applied',
+ created_after: '2026-10-01T00:00:00.000Z',
+ limit: '20',
+ since_id: 'c0',
+ });
+ expect(result).toEqual({ candidates: [{ id: 'c1' }], count: 1, nextCursor: null, hasMore: false });
+ });
+
+ it('listCandidates needs a job for a stage filter', async () => {
+ mockHttp([]);
+ await expect(runAction(listCandidates)({ ...S, stage: 'applied' })).rejects.toThrow('needs a Job Shortcode');
+ });
+
+ it('listJobs filters by state', async () => {
+ const requests = mockHttp([{ body: { jobs: [{ shortcode: 'J1' }] } }]);
+ expect(await runAction(listJobs)({ ...S, state: 'published' })).toMatchObject({ jobs: [{ shortcode: 'J1' }], hasMore: false });
+ expect(requests[0].queryParams).toEqual({ state: 'published', limit: '50' });
+ });
+
+ it('listDisqualificationReasons, listRecruiters, listJobQuestions, getCandidateActivities', async () => {
+ const requests = mockHttp([
+ { body: { disqualification_reasons: [{ id: 'r1', name: 'Too junior' }] } },
+ { body: { recruiters: [{ id: 'x' }] } },
+ { body: { questions: [{ key: 'q1' }] } },
+ { body: { activities: [{ id: 'a1' }] } },
+ ]);
+ expect(await runAction(listDisqualificationReasons)(S)).toEqual({ reasons: [{ id: 'r1', name: 'Too junior' }], count: 1 });
+ expect(await runAction(listRecruiters)({ ...S, shortcode: 'J1' })).toEqual({ recruiters: [{ id: 'x' }], count: 1 });
+ expect(await runAction(listJobQuestions)({ ...S, shortcode: 'J1' })).toEqual({ questions: [{ key: 'q1' }], count: 1 });
+ expect(await runAction(getCandidateActivities)({ ...S, id: 'c1' })).toEqual({ activities: [{ id: 'a1' }], count: 1 });
+ expect(requests.map((r) => r.url)).toEqual([
+ `${BASE}/disqualification_reasons`,
+ `${BASE}/jobs/J1/recruiters`,
+ `${BASE}/jobs/J1/questions`,
+ `${BASE}/candidates/c1/activities`,
+ ]);
+ });
+
+ it('listAccounts returns every account', async () => {
+ mockHttp([{ body: { accounts: [{ subdomain: 'a' }, { subdomain: 'b' }] } }]);
+ expect(await runAction(listAccounts)({})).toEqual({ accounts: [{ subdomain: 'a' }, { subdomain: 'b' }], count: 2 });
+ });
+});
+
+describe('write actions', () => {
+ it('moveCandidate (human) and move_candidate_ai post the same body and return the ID', async () => {
+ const requests = mockHttp([{ status: 202, body: ' ' }, { status: 202, body: ' ' }]);
+ const human = await runAction(moveCandidate)({ ...S, id: 'c1', job: 'J1', target_stage: 'interview', member_id: 'm1' });
+ const ai = await runAction(moveCandidateAi)({ ...S, id: 'c1', target_stage: 'interview', member_id: 'm1' });
+ expect(human).toEqual({ success: true, candidate_id: 'c1', target_stage: 'interview' });
+ expect(ai).toEqual(human);
+ for (const r of requests) {
+ expect(r.method).toBe('POST');
+ expect(r.url).toBe(`${BASE}/candidates/c1/move`);
+ expect(r.body).toEqual({ member_id: 'm1', target_stage: 'interview' });
+ }
+ });
+
+ it('rateCandidate validates the grade per scale before any request', async () => {
+ const requests = mockHttp([{ status: 201, body: '' }]);
+ await expect(runAction(rateCandidate)({ ...S, id: 'c1', member_id: 'm1', comment: 'ok', scale: 'thumbs', grade: 3 })).rejects.toThrow('0 to 2');
+ await expect(runAction(rateCandidate)({ ...S, id: 'c1', member_id: 'm1', comment: 'ok', scale: 'stars', grade: 1.5 })).rejects.toThrow('whole number');
+ expect(requests).toHaveLength(0);
+ const result = await runAction(rateCandidate)({ ...S, id: 'c1', member_id: 'm1', comment: 'ok', scale: 'numbers', grade: '9' });
+ expect(result).toEqual({ success: true, candidate_id: 'c1', scale: 'numbers', grade: 9 });
+ expect(requests[0].body).toEqual({ member_id: 'm1', comment: 'ok', scale: 'numbers', grade: 9 });
+ });
+
+ const candidateProps = {
+ firstname: 'Jane',
+ lastname: 'Doe',
+ email: '[email protected]',
+ headline: '',
+ skills: ['Go', 'go', 'Rust'],
+ tags: [],
+ };
+
+ it('create_candidate posts to the job with stage and sourced true', async () => {
+ const requests = mockHttp([{ status: 201, body: { status: 'created', candidate: { id: 'c9' } } }]);
+ const result = await runAction(createCandidate)({ ...S, job: 'J1', stage: 'applied', ...candidateProps });
+ expect(requests[0].url).toBe(`${BASE}/jobs/J1/candidates`);
+ expect(requests[0].queryParams).toEqual({ stage: 'applied' });
+ expect(requests[0].body).toEqual({
+ sourced: true,
+ candidate: { firstname: 'Jane', lastname: 'Doe', email: '[email protected]', skills: ['Go', 'go', 'Rust'] },
+ });
+ expect(result).toEqual({ id: 'c9', talent_pool: false });
+ });
+
+ it('create_candidate_ai without a job goes to the talent pool and ignores stage', async () => {
+ const requests = mockHttp([{ status: 201, body: { candidate: { id: 'c10' } } }]);
+ const result = await runAction(createCandidateAi)({ ...S, stage: 'applied', sourced: false, ...candidateProps });
+ expect(requests[0].url).toBe(`${BASE}/talent_pool/candidates`);
+ expect(requests[0].queryParams).toEqual({});
+ expect(requests[0].body).toMatchObject({ sourced: false });
+ expect(result).toEqual({ id: 'c10', talent_pool: true });
+ });
+
+ it('create_candidate explains duplicates and checks required fields', async () => {
+ mockHttp([{ error: { status: 422, body: { error: 'Validation failed', validation_errors: { email: ['candidate already exists'] } } } }]);
+ await expect(runAction(createCandidateAi)({ ...S, job_shortcode: 'J1', ...candidateProps })).rejects.toThrow('Use List Candidates');
+ await expect(runAction(createCandidateAi)({ ...S, firstname: 'A', lastname: 'B' })).rejects.toThrow('Email is required');
+ await expect(runAction(createCandidateAi)({ ...S, ...candidateProps, resume_url: 'file:///etc/passwd' })).rejects.toThrow('http');
+ });
+
+ it('update_candidate sends only given fields, clears on request, refuses empty', async () => {
+ const requests = mockHttp([{ body: { candidate: { id: 'c1' } } }]);
+ await expect(runAction(updateCandidate)({ ...S, id: 'c1' })).rejects.toThrow('Nothing to update');
+ await expect(runAction(updateCandidate)({ ...S, id: 'c1', phone: '1', clear_fields: ['phone'] })).rejects.toThrow('both set and cleared');
+ expect(requests).toHaveLength(0);
+ const result = await runAction(updateCandidate)({ ...S, id: 'c1', phone: '+1 555', headline: '', clear_fields: ['summary'] });
+ expect(requests[0].method).toBe('PATCH');
+ expect(requests[0].url).toBe(`${BASE}/candidates/c1`);
+ expect(requests[0].body).toEqual({ candidate: { phone: '+1 555', summary: '' } });
+ expect(result).toEqual({ id: 'c1' });
+ });
+
+ it('add_comment posts body and policy', async () => {
+ const requests = mockHttp([{ status: 201, body: '' }]);
+ expect(await runAction(addComment)({ ...S, id: 'c1', member_id: 'm1', body: 'Hi', policy: ['simple'] })).toEqual({ success: true, candidate_id: 'c1' });
+ expect(requests[0].url).toBe(`${BASE}/candidates/c1/comments`);
+ expect(requests[0].body).toEqual({ member_id: 'm1', comment: { body: 'Hi', policy: ['simple'] } });
+ });
+
+ it('disqualify checks the note length and revert posts member_id', async () => {
+ const requests = mockHttp([{ body: ' ' }, { body: ' ' }]);
+ await expect(runAction(disqualifyCandidate)({ ...S, id: 'c1', member_id: 'm1', disqualify_note: 'x'.repeat(257) })).rejects.toThrow('at most 256');
+ expect(await runAction(disqualifyCandidate)({ ...S, id: 'c1', member_id: 'm1', disqualify_reason_id: 'r1', withdrew: true })).toEqual({
+ success: true,
+ candidate_id: 'c1',
+ disqualified: true,
+ });
+ expect(requests[0].body).toEqual({ member_id: 'm1', disqualify_reason_id: 'r1', withdrew: true });
+ expect(await runAction(revertDisqualification)({ ...S, id: 'c1', member_id: 'm1' })).toMatchObject({ disqualified: false });
+ expect(requests[1].url).toBe(`${BASE}/candidates/c1/revert`);
+ expect(requests[1].body).toEqual({ member_id: 'm1' });
+ });
+
+ it('add_candidate_tags keeps existing tags and skips the PUT when nothing is new', async () => {
+ const requests = mockHttp([
+ { body: { candidate: { tags: ['Referral'] } } },
+ { status: 202, body: { tags: ['Referral', 'senior'] } },
+ { body: { candidate: { tags: ['Referral', 'senior'] } } },
+ ]);
+ expect(await runAction(addCandidateTags)({ ...S, id: 'c1', tags: ['referral', 'senior'] })).toEqual({
+ candidate_id: 'c1',
+ tags: ['Referral', 'senior'],
+ added: ['senior'],
+ });
+ expect(requests[1].method).toBe('PUT');
+ expect(requests[1].body).toEqual({ tags: ['Referral', 'senior'] });
+ expect(await runAction(addCandidateTags)({ ...S, id: 'c1', tags: ['senior'] })).toMatchObject({ added: [] });
+ expect(requests).toHaveLength(3);
+ });
+
+ it('copy_candidate_to_job posts the target and returns the new candidate', async () => {
+ const requests = mockHttp([{ status: 201, body: { candidate: { id: 'c2' } } }]);
+ expect(await runAction(copyCandidateToJob)({ ...S, id: 'c1', member_id: 'm1', target_job_shortcode: 'J2', target_stage: 'applied' })).toEqual({
+ source_candidate_id: 'c1',
+ target_job_shortcode: 'J2',
+ candidate: { id: 'c2' },
+ });
+ expect(requests[0].url).toBe(`${BASE}/candidates/c1/copy`);
+ expect(requests[0].body).toEqual({ member_id: 'm1', target_job_shortcode: 'J2', target_stage: 'applied' });
+ });
+
+ it('copy_candidate_to_job uses the first stage of the target job when no stage is given', async () => {
+ const requests = mockHttp([{ body: { stages: [{ slug: 'sourced' }, { slug: 'applied' }] } }, { status: 201, body: { candidate: { id: 'c2' } } }]);
+ await runAction(copyCandidateToJob)({ ...S, id: 'c1', member_id: 'm1', target_job_shortcode: 'J2' });
+ expect(requests[0].url).toBe(`${BASE}/jobs/J2/stages`);
+ expect(requests[1].body).toEqual({ member_id: 'm1', target_job_shortcode: 'J2', target_stage: 'sourced' });
+ });
+
+ it('add_candidate_tags reports the tags Workable actually saved', async () => {
+ mockHttp([{ body: { candidate: { tags: [] } } }, { status: 202, body: { tags: ['ap'] } }]);
+ expect(await runAction(addCandidateTags)({ ...S, id: 'c1', tags: ['ap-live'] })).toEqual({ candidate_id: 'c1', tags: ['ap'], added: ['ap'] });
+ });
+
+ it('create_candidate explains the live duplicate-email message', async () => {
+ mockHttp([{ error: { status: 422, body: { validation_errors: { email: ['This email address is already being used by another candidate'] } } } }]);
+ await expect(runAction(createCandidateAi)({ ...S, job_shortcode: 'J1', ...candidateProps })).rejects.toThrow('Use List Candidates');
+ });
+
+ it('rateCandidate explains a refused second rating', async () => {
+ mockHttp([{ error: { status: 422, body: '' } }]);
+ await expect(runAction(rateCandidate)({ ...S, id: 'c1', member_id: 'm1', comment: 'ok', scale: 'stars', grade: 3 })).rejects.toThrow('one rating per member');
+ });
+});
+
+describe('custom API call', () => {
+ const base = { method: 'GET', headers: {}, queryParams: {}, body_type: 'none', failsafe: false };
+
+ it('resolves relative paths against the account subdomain', async () => {
+ const requests = mockHttp([accountsReply, { body: { jobs: [] } }]);
+ await runAction(workableCustomApiCall)({ ...base, url: { url: '/jobs' } });
+ expect(requests).toHaveLength(2);
+ const sent = requests[1];
+ expect(sent.url).toBe(`${BASE}/jobs`);
+ expect(sent.headers?.['Authorization']).toBe('Bearer test-token-123');
+ });
+
+ it('uses the same runner for test steps as for runs', () => {
+ expect(workableCustomApiCall.test).toBe(workableCustomApiCall.run);
+ });
+
+ it('refuses to send the token to another host', async () => {
+ const requests = mockHttp([]);
+ await expect(
+ runAction(workableCustomApiCall)({ ...base, account_subdomain: SUB, url: { url: 'https://acme.workable.com.evil.io/spi/v3/jobs' } }),
+ ).rejects.toThrow('only sends your token');
+ expect(requests).toHaveLength(0);
+ });
+});
diff --git a/packages/pieces/community/workable/test/client.test.ts b/packages/pieces/community/workable/test/client.test.ts
new file mode 100644
index 00000000000..8cf832f4503
--- /dev/null
+++ b/packages/pieces/community/workable/test/client.test.ts
@@ -0,0 +1,100 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import {
+ createWorkableClient,
+ cursorFromPaging,
+ encodeId,
+ isSameApiUrl,
+ normalizeSubdomain,
+ WorkableApiError,
+} from '../src/lib/common/client';
+import { workableAuth } from '../src/lib/auth';
+import { accountsReply, AUTH, BASE, mockHttp, SUB } from './helpers';
+
+describe('client', () => {
+ it('looks up the subdomain once per client and sends bearer auth', async () => {
+ const requests = mockHttp([accountsReply, { body: { jobs: [] } }, { body: { jobs: [] } }]);
+ const client = createWorkableClient({ auth: AUTH });
+ await client.request({ method: HttpMethod.GET, path: '/jobs' });
+ await client.request({ method: HttpMethod.GET, path: '/jobs' });
+ expect(requests.map((r) => r.url)).toEqual(['https://workable.com/spi/v3/accounts', `${BASE}/jobs`, `${BASE}/jobs`]);
+ expect(requests[1].headers).toEqual({ Authorization: 'Bearer test-token-123', Accept: 'application/json' });
+ expect(requests[1].followRedirects).toBe(false);
+ expect(requests[1].redactBodyInErrors).toBe(true);
+ });
+
+ it('skips /accounts when a subdomain is given', async () => {
+ const requests = mockHttp([{ body: {} }]);
+ await createWorkableClient({ auth: AUTH, subdomain: ' Other ' }).request({ method: HttpMethod.GET, path: '/jobs' });
+ expect(requests[0].url).toBe('https://other.workable.com/spi/v3/jobs');
+ });
+
+ it('fails clearly when the token sees no account', async () => {
+ mockHttp([{ body: { accounts: [] } }]);
+ await expect(createWorkableClient({ auth: AUTH }).request({ method: HttpMethod.GET, path: '/jobs' })).rejects.toThrow('cannot see any account');
+ });
+
+ it('rejects bad subdomains, IDs and paths', async () => {
+ expect(() => normalizeSubdomain('evil.com/x')).toThrow('not valid');
+ expect(() => normalizeSubdomain('a.b')).toThrow('not valid');
+ expect(encodeId({ value: 'a b', label: 'ID' })).toBe('a%20b');
+ expect(() => encodeId({ value: '..', label: 'ID' })).toThrow('not a valid');
+ expect(() => encodeId({ value: '1/../x', label: 'ID' })).toThrow('not a valid');
+ expect(() => encodeId({ value: '', label: 'ID' })).toThrow('ID is required');
+ mockHttp([]);
+ await expect(createWorkableClient({ auth: AUTH, subdomain: SUB }).request({ method: HttpMethod.GET, path: '/a/../b' })).rejects.toThrow('unexpected path');
+ });
+
+ it('only accepts next-page links on the same host and prefix', () => {
+ expect(isSameApiUrl({ subdomain: SUB, candidate: `${BASE}/candidates?since_id=5` })).toBe(true);
+ expect(isSameApiUrl({ subdomain: SUB, candidate: 'https://acme.workable.com.evil.io/spi/v3/candidates' })).toBe(false);
+ expect(isSameApiUrl({ subdomain: SUB, candidate: 'https://[email protected]/spi/v3/x' })).toBe(false);
+ expect(isSameApiUrl({ subdomain: SUB, candidate: 'http://acme.workable.com/spi/v3/x' })).toBe(false);
+ expect(isSameApiUrl({ subdomain: SUB, candidate: 'https://acme.workable.com/other' })).toBe(false);
+ expect(cursorFromPaging({ subdomain: SUB, body: { paging: { next: `${BASE}/candidates?limit=2&since_id=abc` } } })).toBe('abc');
+ expect(cursorFromPaging({ subdomain: SUB, body: {} })).toBeNull();
+ expect(() => cursorFromPaging({ subdomain: SUB, body: { paging: { next: 'https://evil.io/spi/v3/candidates?since_id=1' } } })).toThrow('different host');
+ });
+
+ it('wraps errors with responseBody and readable validation errors', async () => {
+ mockHttp([{ error: { status: 422, body: { error: 'Validation failed', validation_errors: { email: ['candidate already exists'] } } } }]);
+ const error = await createWorkableClient({ auth: AUTH, subdomain: SUB })
+ .request({ method: HttpMethod.POST, path: '/jobs/X/candidates' })
+ .catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(WorkableApiError);
+ expect(error).toMatchObject({ message: expect.stringContaining('email: candidate already exists') });
+ expect(error).toHaveProperty('responseBody', { error: 'Validation failed', validation_errors: { email: ['candidate already exists'] } });
+ expect(error).not.toHaveProperty('body');
+ });
+
+ it('retries 429 at most twice, waiting one 10 s rate-limit window each time', async () => {
+ vi.useFakeTimers();
+ try {
+ const requests = mockHttp([
+ { error: { status: 429, body: '' } },
+ { error: { status: 429, body: '' } },
+ { error: { status: 429, body: '' } },
+ ]);
+ const promise = createWorkableClient({ auth: AUTH, subdomain: SUB }).request({ method: HttpMethod.GET, path: '/jobs' }).catch((e: unknown) => e);
+ await vi.advanceTimersByTimeAsync(9999);
+ expect(requests).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(10001);
+ const error = await promise;
+ expect(requests).toHaveLength(3);
+ expect(error).toMatchObject({ status: 429 });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('validate() reports invalid credentials only on 401/403', async () => {
+ const validate = (p: { auth: string }) => Reflect.apply(workableAuth.validate ?? (() => undefined), workableAuth, [p]);
+ mockHttp([{ error: { status: 401, body: { error: 'Not authorized' } } }]);
+ expect(await validate({ auth: 'x' })).toEqual({ valid: false, error: 'Invalid API access token.' });
+ vi.restoreAllMocks();
+ mockHttp([{ error: { status: 500, body: '' } }]);
+ expect((await validate({ auth: 'x' })).error).toContain('server error');
+ vi.restoreAllMocks();
+ mockHttp([accountsReply]);
+ expect(await validate({ auth: 'x' })).toEqual({ valid: true });
+ });
+});
diff --git a/packages/pieces/community/workable/test/helpers.ts b/packages/pieces/community/workable/test/helpers.ts
new file mode 100644
index 00000000000..ca08979fdab
--- /dev/null
+++ b/packages/pieces/community/workable/test/helpers.ts
@@ -0,0 +1,56 @@
+/// <reference types="vitest/globals" />
+import { HttpRequest, HttpResponse, httpClient } from '@activepieces/pieces-common';
+import { AppConnectionType } from '@activepieces/pieces-framework';
+import { createMockActionContext } from '../../../framework/src/lib/test';
+
+export const TOKEN = 'test-token-123';
+export const SUB = 'acme';
+export const BASE = 'https://acme.workable.com/spi/v3';
+export const AUTH = { type: AppConnectionType.SECRET_TEXT, secret_text: TOKEN };
+
+export type Reply = { status?: number; body: unknown } | { error: { status: number; body: unknown } };
+
+export function mockHttp(replies: Reply[]): HttpRequest[] {
+ const requests: HttpRequest[] = [];
+ const queue = [...replies];
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request: HttpRequest): Promise<HttpResponse> => {
+ requests.push(request);
+ const reply = queue.shift();
+ if (!reply) {
+ throw new Error(`unexpected request ${request.method} ${request.url}`);
+ }
+ if ('error' in reply) {
+ throw Object.assign(new Error(`Request failed with status ${reply.error.status}`), {
+ response: { status: reply.error.status, body: reply.error.body },
+ });
+ }
+ return { status: reply.status ?? 200, headers: {}, body: reply.body };
+ });
+ return requests;
+}
+
+export const accountsReply: Reply = { body: { accounts: [{ id: '1', name: 'Acme', subdomain: SUB }] } };
+
+export function memoryStore(initial: Record<string, unknown> = {}) {
+ const data = new Map<string, unknown>(Object.entries(initial));
+ return {
+ data,
+ put: async <T>(key: string, value: T): Promise<T> => {
+ data.set(key, value);
+ return value;
+ },
+ get: async <T>(key: string): Promise<T | null> => (data.has(key) ? JSON.parse(JSON.stringify(data.get(key))) : null),
+ delete: async (key: string): Promise<void> => {
+ data.delete(key);
+ },
+ };
+}
+
+export function runAction(action: { run: (ctx: never) => Promise<unknown> }) {
+ return (propsValue: Record<string, unknown>) =>
+ Reflect.apply(action.run, action, [{ ...createMockActionContext({ propsValue }), auth: AUTH }]);
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
diff --git a/packages/pieces/community/workable/test/triggers.test.ts b/packages/pieces/community/workable/test/triggers.test.ts
new file mode 100644
index 00000000000..9edacbf066c
--- /dev/null
+++ b/packages/pieces/community/workable/test/triggers.test.ts
@@ -0,0 +1,150 @@
+import { createHmac } from 'crypto';
+import { candidateStageChanged } from '../src/lib/triggers/candidate-stage-changed';
+import { newCandidate } from '../src/lib/triggers/new-candidate';
+import { accountsReply, AUTH, BASE, memoryStore, mockHttp, SUB, TOKEN } from './helpers';
+
+const HOOK = 'https://cloud.example.com/api/v1/webhooks/flow1';
+
+type Trigger = typeof newCandidate;
+
+function on(trigger: Trigger) {
+ const call = (hook: 'run' | 'onEnable' | 'onDisable' | 'test') => (extra: Record<string, unknown>) =>
+ Reflect.apply(trigger[hook], trigger, [{ auth: AUTH, webhookUrl: HOOK, propsValue: {}, ...extra }]);
+ return { run: call('run'), onEnable: call('onEnable'), onDisable: call('onDisable'), test: call('test') };
+}
+
+function signed({ body, token = TOKEN, encoding = 'hex' }: { body: unknown; token?: string; encoding?: 'hex' | 'base64' }) {
+ const rawBody = JSON.stringify(body);
+ const signature = createHmac('sha256', token).update(rawBody).digest(encoding);
+ return { body, rawBody, headers: { 'x-workable-signature': signature } };
+}
+
+function envelope(extra: Record<string, unknown> = {}) {
+ return {
+ id: 'evt-1',
+ event_type: 'candidate_created',
+ resource_type: 'candidate',
+ fired_at: new Date().toISOString(),
+ data: { id: 'c1', name: 'Jane Doe' },
+ ...extra,
+ };
+}
+
+describe('webhook lifecycle', () => {
+ it('onEnable sends account_id in args and stores the ID with the subdomain', async () => {
+ const requests = mockHttp([accountsReply, { status: 201, body: { id: 42 } }]);
+ const store = memoryStore();
+ await on(newCandidate).onEnable({ store, propsValue: { shortcode: 'J1' } });
+ expect(requests[1].url).toBe(`${BASE}/subscriptions`);
+ expect(requests[1].body).toEqual({
+ target: HOOK,
+ event: 'candidate_created',
+ args: { account_id: SUB, job_shortcode: 'J1', stage_slug: '' },
+ });
+ expect(store.data.get('_new_candidate_created')).toEqual({ webhookId: '42', subdomain: SUB });
+ });
+
+ it('onEnable on 409 deletes the old subscription for this URL and retries', async () => {
+ const requests = mockHttp([
+ { error: { status: 409, body: { error: 'exists' } } },
+ { body: { subscriptions: [{ id: 7, target: HOOK }, { id: 8, target: 'https://other' }] } },
+ { status: 204, body: '' },
+ { status: 201, body: { id: 9 } },
+ ]);
+ const store = memoryStore();
+ await on(candidateStageChanged).onEnable({ store, propsValue: { account_subdomain: SUB, stage_slug: 'offer' } });
+ expect(requests.map((r) => `${r.method} ${r.url}`)).toEqual([
+ `POST ${BASE}/subscriptions`,
+ `GET ${BASE}/subscriptions`,
+ `DELETE ${BASE}/subscriptions/7`,
+ `POST ${BASE}/subscriptions`,
+ ]);
+ expect(requests[0].body).toMatchObject({ event: 'candidate_moved' });
+ expect(store.data.get('_candidate_stage_changed')).toEqual({ webhookId: '9', subdomain: SUB });
+ });
+
+ it('onEnable deletes the subscription when store.put fails', async () => {
+ const requests = mockHttp([{ status: 201, body: { id: 5 } }, { status: 204, body: '' }]);
+ const store = { ...memoryStore(), put: async () => Promise.reject(new Error('store down')) };
+ await expect(on(newCandidate).onEnable({ store, propsValue: { account_subdomain: SUB } })).rejects.toThrow('store down');
+ expect(`${requests[1].method} ${requests[1].url}`).toBe(`DELETE ${BASE}/subscriptions/5`);
+ });
+
+ it('onDisable treats 404 as deleted and clears the store keys, also for the old store format', async () => {
+ const requests = mockHttp([accountsReply, { error: { status: 404, body: { error: 'Not found' } } }]);
+ const store = memoryStore({ _new_candidate_created: { webhookId: '42' }, _new_candidate_created_deliveries: ['x'] });
+ await on(newCandidate).onDisable({ store });
+ expect(requests[1].url).toBe(`${BASE}/subscriptions/42`);
+ expect(store.data.size).toBe(0);
+ });
+
+ it('onDisable rethrows other errors and keeps the key', async () => {
+ mockHttp([{ error: { status: 500, body: '' } }]);
+ const store = memoryStore({ _new_candidate_created: { webhookId: '42', subdomain: SUB } });
+ await expect(on(newCandidate).onDisable({ store })).rejects.toThrow('server error');
+ expect(store.data.has('_new_candidate_created')).toBe(true);
+ });
+});
+
+describe('webhook deliveries', () => {
+ it('accepts a valid hex or base64 HMAC and returns the candidate', async () => {
+ mockHttp([]);
+ const store = memoryStore();
+ const first = await on(newCandidate).run({ store, payload: signed({ body: envelope() }) });
+ expect(first).toEqual([expect.objectContaining({ id: 'c1', name: 'Jane Doe', event_type: 'candidate_created' })]);
+ const second = await on(newCandidate).run({ store, payload: signed({ body: envelope({ id: 'evt-2' }), encoding: 'base64' }) });
+ expect(second).toHaveLength(1);
+ });
+
+ it('rejects missing, wrong-key and tampered signatures', async () => {
+ mockHttp([]);
+ const store = memoryStore();
+ const missing = { ...signed({ body: envelope() }), headers: {} };
+ expect(await on(newCandidate).run({ store, payload: missing })).toEqual([]);
+ expect(await on(newCandidate).run({ store, payload: signed({ body: envelope(), token: 'other' }) })).toEqual([]);
+ const tampered = { ...signed({ body: envelope() }), rawBody: JSON.stringify(envelope({ data: { id: 'evil' } })) };
+ expect(await on(newCandidate).run({ store, payload: tampered })).toEqual([]);
+ const noRaw = { body: envelope(), headers: signed({ body: envelope() }).headers };
+ expect(await on(newCandidate).run({ store, payload: noRaw })).toEqual([]);
+ });
+
+ it('dedupes retries by event ID and bounds the store', async () => {
+ mockHttp([]);
+ const store = memoryStore({ _new_candidate_created_deliveries: Array.from({ length: 500 }, (_, i) => `old-${i}`) });
+ const payload = signed({ body: envelope() });
+ expect(await on(newCandidate).run({ store, payload })).toHaveLength(1);
+ expect(await on(newCandidate).run({ store, payload })).toEqual([]);
+ const seen: unknown = store.data.get('_new_candidate_created_deliveries');
+ if (!Array.isArray(seen)) throw new Error('deliveries not stored');
+ expect(seen).toHaveLength(500);
+ expect(seen[seen.length - 1]).toBe('evt-1');
+ });
+
+ it('drops events outside the 6 hour window and other event types', async () => {
+ mockHttp([]);
+ const store = memoryStore();
+ const old = signed({ body: envelope({ fired_at: new Date(Date.now() - 7 * 60 * 60 * 1000).toISOString() }) });
+ expect(await on(newCandidate).run({ store, payload: old })).toEqual([]);
+ const lagged = signed({ body: envelope({ id: 'evt-lag', fired_at: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString() }) });
+ expect(await on(newCandidate).run({ store, payload: lagged })).toHaveLength(1);
+ const moved = signed({ body: envelope({ id: 'evt-3', event_type: 'candidate_moved' }) });
+ expect(await on(newCandidate).run({ store, payload: moved })).toEqual([]);
+ expect(await on(candidateStageChanged).run({ store: memoryStore(), payload: moved })).toHaveLength(1);
+ });
+
+ it('test() returns the newest full candidates in the run() shape', async () => {
+ const requests = mockHttp([
+ { body: { candidates: [{ id: 'c1' }, { id: 'c2' }] } },
+ { body: { candidate: { id: 'c2', updated_at: '2026-10-20T00:00:00Z' } } },
+ { body: { candidate: { id: 'c1', updated_at: '2026-10-19T00:00:00Z' } } },
+ ]);
+ const result = await on(newCandidate).test({ store: memoryStore(), propsValue: { account_subdomain: SUB, shortcode: 'J1', stage_slug: 'applied' } });
+ expect(requests[0].url).toBe(`${BASE}/candidates`);
+ expect(requests[0].queryParams).toMatchObject({ shortcode: 'J1', stage: 'applied', limit: '100' });
+ expect(requests[0].queryParams).toHaveProperty('created_after');
+ expect(result).toEqual([
+ { id: 'c2', updated_at: '2026-10-20T00:00:00Z', event_type: 'candidate_created', fired_at: '2026-10-20T00:00:00Z' },
+ { id: 'c1', updated_at: '2026-10-19T00:00:00Z', event_type: 'candidate_created', fired_at: '2026-10-19T00:00:00Z' },
+ ]);
+ });
+});
diff --git a/packages/pieces/community/workable/vitest.config.ts b/packages/pieces/community/workable/vitest.config.ts
new file mode 100644
index 00000000000..ba8ade4a178
--- /dev/null
+++ b/packages/pieces/community/workable/vitest.config.ts
@@ -0,0 +1,17 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: 'node',
+ },
+ 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'),
+ },
+ },
+})