Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import {
StoreScope,
Validators,
} from '@openops/blocks-framework';
import { buildWrapperUrl } from '@openops/common';
import {
buildWrapperUrl,
followUpFormProperty,
resolveButtonForm,
} from '@openops/common';
import { networkUtls, SharedSystemProp, system } from '@openops/server-shared';
import { ExecutionType } from '@openops/shared';
import { chatExists } from '../common/chat-exists';
Expand Down Expand Up @@ -69,31 +73,7 @@ export const requestActionMessageAction = createAction({
],
},
}),
followUpQuestion: Property.ShortText({
displayName: 'Follow-up question',
description:
'Optionally ask a follow-up question in a popup window when this button is clicked.',
required: false,
}),
answerFormat: Property.StaticDropdown({
displayName: 'Answer format',
description: 'Only used when a follow-up question is set.',
required: false,
defaultValue: 'text',
options: {
options: [
{ label: 'Text', value: 'text' },
{ label: 'Email', value: 'email' },
{ label: 'Number', value: 'number' },
],
},
}),
noAnswerOption: Property.ShortText({
displayName: 'No answer option',
description:
"Optional text for a secondary choice when the person can't answer.",
required: false,
}),
followUpForm: followUpFormProperty,
},
}),
timeoutInDays: Property.Number({
Expand Down Expand Up @@ -146,33 +126,32 @@ export const requestActionMessageAction = createAction({
.getOrThrow(SharedSystemProp.FRONTEND_URL)
.replace(/\/$/, '');

const preparedActions: TeamsMessageButton[] = actions.map((action) => {
const resumeUrl = context.generateResumeUrl(
{
queryParams: {
executionCorrelationId: context.run.pauseId,
button: action.buttonText,
// Resolved before anything is sent, so an invalid form fails the step
// instead of reaching the recipient.
const forms = actions.map((action) => resolveButtonForm(action, header));

const preparedActions: TeamsMessageButton[] = actions.map(
(action, index) => {
const resumeUrl = context.generateResumeUrl(
{
queryParams: {
executionCorrelationId: context.run.pauseId,
button: action.buttonText,
},
},
},
apiUrl,
);
return {
...action,
resumeUrl: buildWrapperUrl({
frontendUrl,
isTest: context.run.isTest,
resumeUrl,
followUp: action.followUpQuestion
? {
question: action.followUpQuestion,
answerFormat: action.answerFormat,
noAnswerOption: action.noAnswerOption,
title: header,
}
: undefined,
}),
};
});
apiUrl,
);
return {
...action,
resumeUrl: buildWrapperUrl({
frontendUrl,
isTest: context.run.isTest,
resumeUrl,
form: forms[index],
}),
};
},
);

const result = await sendChatOrChannelMessage({
accessToken: context.auth.access_token,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
export type TeamsMessageAction = {
import { ButtonFormSettings } from '@openops/common';

export type TeamsMessageAction = ButtonFormSettings & {
buttonText: string;
buttonStyle: string;
followUpQuestion?: string;
answerFormat?: string;
noAnswerOption?: string;
};

export type TeamsMessageButton = TeamsMessageAction & { resumeUrl?: string };
Expand Down
140 changes: 140 additions & 0 deletions packages/blocks/microsoft-teams/test/request-action-message.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
jest.mock('@openops/server-shared', () => {
const actual = jest.requireActual('@openops/server-shared');
return {
...actual,
system: {
...actual.system,
getOrThrow: jest.fn().mockReturnValue('https://app.openops.com/'),
},
networkUtls: {
...actual.networkUtls,
getPublicUrl: jest.fn().mockResolvedValue('https://api.openops.com'),
},
};
});

const sendChatOrChannelMessageMock = jest
.fn()
.mockResolvedValue({ id: 'message-1' });
jest.mock('../src/lib/common/send-chat-or-channel-message', () => ({
sendChatOrChannelMessage: sendChatOrChannelMessageMock,
}));

jest.mock('../src/lib/common/wait-for-interaction', () => ({
waitForInteraction: jest.fn().mockResolvedValue({}),
}));

import { ExecutionType } from '@openops/shared';
import { requestActionMessageAction } from '../src/lib/actions/request-action-message';

function buildContext(extraAction: Record<string, unknown>): any {
return {
executionType: ExecutionType.BEGIN,
auth: { access_token: 'token' },
propsValue: {
chatOrChannel: { id: 'chat-1', type: 'chat' },
header: 'Cost savings opportunity: vol-123',
message: 'Message',
actions: [
{ buttonText: 'Dismiss', buttonStyle: 'destructive' },
{ buttonText: 'Follow up', buttonStyle: 'default', ...extraAction },
],
timeoutInDays: 3,
},
run: { pauseId: 'pause-1', isTest: false },
currentExecutionPath: 'step_1',
store: { put: jest.fn() },
generateResumeUrl: jest.fn(
({ queryParams }: any) =>
`https://api.openops.com/v1/flow-runs/run-1/requests/pause-1?${new URLSearchParams(queryParams)}`,
),
};
}

function readForm(url: string): unknown {
const encoded = new URL(url).searchParams.get('form') ?? '';
return JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8'));
}

function sentButtons(): { buttonText: string; resumeUrl: string }[] {
return sendChatOrChannelMessageMock.mock.calls[0][0].actions;
}

describe('microsoft teams requestActionMessageAction', () => {
beforeEach(() => {
jest.clearAllMocks();
});

test('sends a plain button to the resume page', async () => {
await requestActionMessageAction.run(buildContext({}));

expect(sentButtons()[1].resumeUrl).toContain(
'/html/resume_execution.html?',
);
});

test('turns a single follow-up question from an older flow into a one-field form', async () => {
await requestActionMessageAction.run(
buildContext({
followUpQuestion: "What is the correct owner's email?",
answerFormat: 'email',
noAnswerOption: "I don't know the owner",
}),
);

const url = sentButtons()[1].resumeUrl;
expect(new URL(url).searchParams.has('question')).toBe(false);
expect(readForm(url)).toEqual({
title: 'Cost savings opportunity: vol-123',
fields: [
{
name: 'answer',
label: "What is the correct owner's email?",
type: 'email',
required: true,
},
],
skipLabel: "I don't know the owner",
});
});

test('sends a form button with the form in its link and no heading unless the form has a title', async () => {
await requestActionMessageAction.run(
buildContext({
followUpForm: {
fields: [
{
name: 'reason',
label: 'Exception reason',
type: 'select',
options: ['VendorSet'],
},
],
},
}),
);

const url = sentButtons()[1].resumeUrl;
expect(new URL(url).pathname).toBe('/html/collect_input.html');
expect(readForm(url)).toEqual({
fields: [
{
name: 'reason',
label: 'Exception reason',
type: 'select',
options: ['VendorSet'],
required: true,
},
],
});
});

test('fails before sending when the form is invalid', async () => {
await expect(
requestActionMessageAction.run(
buildContext({ followUpForm: { fields: [{ name: 'path' }] } }),
),
).rejects.toThrow(/Invalid follow-up form/);
expect(sendChatOrChannelMessageMock).not.toHaveBeenCalled();
});
});
48 changes: 30 additions & 18 deletions packages/blocks/slack/src/lib/actions/request-action-message.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { createAction, StoreScope } from '@openops/blocks-framework';
import { buildWrapperUrl } from '@openops/common';
import {
buildWrapperUrl,
ButtonFormSettings,
FollowUpForm,
MAX_BUTTON_URL_LENGTH,
resolveButtonForm,
} from '@openops/common';
import { networkUtls, SharedSystemProp, system } from '@openops/server-shared';
import {
assertNotNullOrUndefined,
Expand Down Expand Up @@ -112,9 +118,14 @@ const sendMessageAskingForAction = async (
const enableSlackInteractions =
system.getBoolean(SharedSystemProp.SLACK_ENABLE_INTERACTIONS) ?? true;

// Resolved before anything is sent, so an invalid form fails the step
// instead of reaching the recipient.
actions.forEach((action: SlackActionDefinition) => {
action.form = resolveButtonForm(action, headerText);
});

const buttonsNeedingUrl = actions.filter(
(action: SlackActionDefinition) =>
!enableSlackInteractions || action.followUpQuestion,
(action: SlackActionDefinition) => !enableSlackInteractions || action.form,
);

if (buttonsNeedingUrl.length) {
Expand All @@ -123,7 +134,7 @@ const sendMessageAskingForAction = async (
.getOrThrow(SharedSystemProp.FRONTEND_URL)
.replace(/\/$/, '');

buttonsNeedingUrl.forEach((action: SlackActionDefinition) => {
for (const action of buttonsNeedingUrl as SlackActionDefinition[]) {
const resumeUrl = context.generateResumeUrl(
{
queryParams: {
Expand All @@ -140,22 +151,25 @@ const sendMessageAskingForAction = async (
frontendUrl,
isTest: context.run.isTest,
resumeUrl,
followUp: action.followUpQuestion
? {
question: action.followUpQuestion,
answerFormat: action.answerFormat,
noAnswerOption: action.noAnswerOption,
title: headerText,
}
: undefined,
form: action.form,
});
});
// Slack rejects the whole message when a button URL is longer, so the
// recipient would get nothing; fail the step with the reason instead.
if (action.url.length > MAX_BUTTON_URL_LENGTH) {
const advice = action.form
? ' Shorten its follow-up form, for example the list of options.'
: '';
throw new Error(
`The link of button "${action.buttonText}" is too long for Slack (${action.url.length} of ${MAX_BUTTON_URL_LENGTH} characters).${advice}`,
);
}
}
}

// Stored normalized because Slack interaction payloads return button text
// in emoji-shortcode form, which is what the interactions endpoint compares.
const followUpActions = actions
.filter((action: SlackActionDefinition) => action.followUpQuestion)
.filter((action: SlackActionDefinition) => action.form)
.map((action: SlackActionDefinition) =>
normalizeEmojiString(action.buttonText),
);
Expand Down Expand Up @@ -203,14 +217,12 @@ interface ConfirmationPrompt {
confirm: SlackText;
}

interface SlackActionDefinition {
interface SlackActionDefinition extends ButtonFormSettings {
buttonText: string;
buttonStyle: string;
confirmationPrompt: boolean;
confirmationPromptText: string;
followUpQuestion?: string;
answerFormat?: string;
noAnswerOption?: string;
form?: FollowUpForm;
url?: string;
}

Expand Down
27 changes: 2 additions & 25 deletions packages/blocks/slack/src/lib/common/props.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
Property,
Validators,
} from '@openops/blocks-framework';
import { followUpFormProperty } from '@openops/common';
import { getSlackChannels, getSlackUsers } from './slack-api-request';

export const slackChannel = Property.Dropdown({
Expand Down Expand Up @@ -158,31 +159,7 @@ export const actions = Property.Array({
description: '',
required: false,
}),
followUpQuestion: Property.ShortText({
displayName: 'Follow-up question',
description:
'Optionally ask a follow-up question in a popup window when this button is clicked.',
required: false,
}),
answerFormat: Property.StaticDropdown({
displayName: 'Answer format',
description: 'Only used when a follow-up question is set.',
required: false,
defaultValue: 'text',
options: {
options: [
{ label: 'Text', value: 'text' },
{ label: 'Email', value: 'email' },
{ label: 'Number', value: 'number' },
],
},
}),
noAnswerOption: Property.ShortText({
displayName: 'No answer option',
description:
"Optional text for a secondary choice when the person can't answer.",
required: false,
}),
followUpForm: followUpFormProperty,
},
});

Expand Down
Loading
Loading