diff --git a/packages/blocks/microsoft-teams/src/lib/actions/request-action-message.ts b/packages/blocks/microsoft-teams/src/lib/actions/request-action-message.ts index af15d438ee..9006922875 100644 --- a/packages/blocks/microsoft-teams/src/lib/actions/request-action-message.ts +++ b/packages/blocks/microsoft-teams/src/lib/actions/request-action-message.ts @@ -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'; @@ -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({ @@ -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, diff --git a/packages/blocks/microsoft-teams/src/lib/common/generate-message-with-buttons.ts b/packages/blocks/microsoft-teams/src/lib/common/generate-message-with-buttons.ts index 6387678aa0..aef042f39f 100644 --- a/packages/blocks/microsoft-teams/src/lib/common/generate-message-with-buttons.ts +++ b/packages/blocks/microsoft-teams/src/lib/common/generate-message-with-buttons.ts @@ -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 }; diff --git a/packages/blocks/microsoft-teams/test/request-action-message.test.ts b/packages/blocks/microsoft-teams/test/request-action-message.test.ts new file mode 100644 index 0000000000..8272981813 --- /dev/null +++ b/packages/blocks/microsoft-teams/test/request-action-message.test.ts @@ -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): 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(); + }); +}); diff --git a/packages/blocks/slack/src/lib/actions/request-action-message.ts b/packages/blocks/slack/src/lib/actions/request-action-message.ts index ddaa73746e..1bfa3afd95 100644 --- a/packages/blocks/slack/src/lib/actions/request-action-message.ts +++ b/packages/blocks/slack/src/lib/actions/request-action-message.ts @@ -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, @@ -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) { @@ -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: { @@ -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), ); @@ -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; } diff --git a/packages/blocks/slack/src/lib/common/props.ts b/packages/blocks/slack/src/lib/common/props.ts index d48a058f7a..8a17b67766 100644 --- a/packages/blocks/slack/src/lib/common/props.ts +++ b/packages/blocks/slack/src/lib/common/props.ts @@ -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({ @@ -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, }, }); diff --git a/packages/blocks/slack/test/request-action-message.test.ts b/packages/blocks/slack/test/request-action-message.test.ts index 5c26a21e21..0c293e0f3d 100644 --- a/packages/blocks/slack/test/request-action-message.test.ts +++ b/packages/blocks/slack/test/request-action-message.test.ts @@ -343,7 +343,7 @@ describe('requestActionMessageAction', () => { ); }); - describe('follow-up question buttons', () => { + describe('follow-up question buttons from flows built before forms existed', () => { beforeEach(() => { jest.clearAllMocks(); waitForInteractionMock.mockImplementation(async (messageObj: any) => @@ -386,10 +386,22 @@ describe('requestActionMessageAction', () => { expect(followUpButton.url).toContain('/html/collect_input.html?'); const params = new URL(followUpButton.url).searchParams; - expect(params.get('question')).toBe("What is the correct owner's email?"); - expect(params.get('format')).toBe('email'); - expect(params.get('noAnswerOption')).toBe("I don't know the owner"); - expect(params.get('title')).toBe('Header Text'); + const form = JSON.parse( + Buffer.from(params.get('form') ?? '', 'base64url').toString('utf8'), + ); + expect(params.has('question')).toBe(false); + expect(form).toEqual({ + title: 'Header Text', + fields: [ + { + name: 'answer', + label: "What is the correct owner's email?", + type: 'email', + required: true, + }, + ], + skipLabel: "I don't know the owner", + }); expect(params.get('redirectUrl')).toContain( 'executionCorrelationId=pause_123', ); @@ -441,6 +453,136 @@ describe('requestActionMessageAction', () => { }); }); + describe('follow-up form buttons', () => { + beforeEach(() => { + jest.clearAllMocks(); + waitForInteractionMock.mockImplementation(async (messageObj: any) => + Promise.resolve({ ...messageObj }), + ); + slackSendMessageMock.mockImplementation(async (message: any) => + Promise.resolve(message), + ); + }); + + const exceptionForm = { + title: 'Request an exception', + fields: [ + { + name: 'reason', + label: 'Exception reason', + type: 'select', + options: ['VendorSet'], + }, + { name: 'justification', label: 'Justification', type: 'textarea' }, + ], + }; + + function buildContextWithForm(followUpForm: unknown): any { + const mockContext = buildMockContext('Header Text', true); + mockContext.propsValue.actions.push({ + buttonText: 'Add exception', + buttonStyle: '', + followUpForm, + }); + mockContext.run.isTest = false; + mockContext.generateResumeUrl.mockImplementation( + ({ queryParams }: any) => + `https://example.com/resume?${new URLSearchParams(queryParams)}`, + ); + return mockContext; + } + + function readForm(url: string): any { + const encoded = new URL(url).searchParams.get('form') ?? ''; + return JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')); + } + + function formButtonUrl(result: any): string { + const actionBlock = result.blocks.find((b: any) => b.type === 'actions'); + return actionBlock.elements[1].url; + } + + test('should give the form button a collect_input url carrying the form', async () => { + getBooleanMock.mockReturnValueOnce(true); + + const result = (await requestActionMessageAction.run( + buildContextWithForm(exceptionForm), + )) as any; + + const actionBlock = result.blocks.find((b: any) => b.type === 'actions'); + expect(actionBlock.elements[0].url).not.toBeDefined(); + expect(formButtonUrl(result)).toContain('/html/collect_input.html?'); + expect(readForm(formButtonUrl(result))).toEqual({ + title: 'Request an exception', + fields: [ + { + name: 'reason', + label: 'Exception reason', + type: 'select', + options: ['VendorSet'], + required: true, + }, + { + name: 'justification', + label: 'Justification', + type: 'textarea', + required: true, + }, + ], + }); + expect(result.eventPayload.followUpActions).toEqual(['Add exception']); + }); + + test('should not add a heading to a form that has no title', async () => { + getBooleanMock.mockReturnValueOnce(true); + + const result = (await requestActionMessageAction.run( + buildContextWithForm({ ...exceptionForm, title: undefined }), + )) as any; + + expect(readForm(formButtonUrl(result)).title).toBeUndefined(); + }); + + test('should fail before sending when the form makes the button link longer than Slack allows', async () => { + getBooleanMock.mockReturnValueOnce(true); + const options = Array.from({ length: 200 }, (_, i) => `Reason-${i}`); + + await expect( + requestActionMessageAction.run( + buildContextWithForm({ + fields: [ + { name: 'reason', label: 'Reason', type: 'select', options }, + ], + }), + ), + ).rejects.toThrow( + /The link of button "Add exception" is too long for Slack \(\d+ of 3000 characters\)\. Shorten its follow-up form/, + ); + expect(slackSendMessageMock).not.toHaveBeenCalled(); + }); + + test('should treat an empty form setting as a plain button', async () => { + getBooleanMock.mockReturnValueOnce(true); + + const result = (await requestActionMessageAction.run( + buildContextWithForm({}), + )) as any; + + const actionBlock = result.blocks.find((b: any) => b.type === 'actions'); + expect(actionBlock.elements[1].url).not.toBeDefined(); + expect(result.eventPayload.followUpActions).toEqual([]); + }); + + test('should fail before sending when the form is invalid', async () => { + getBooleanMock.mockReturnValueOnce(true); + + await expect( + requestActionMessageAction.run(buildContextWithForm({ fields: [] })), + ).rejects.toThrow(/Invalid follow-up form/); + expect(slackSendMessageMock).not.toHaveBeenCalled(); + }); + }); + describe('RESUME execution', () => { test('should throw an error when there is no message stored in the store', async () => { const mockContextWithHeader = buildMockContext('This is a header', true); diff --git a/packages/openops/src/index.ts b/packages/openops/src/index.ts index 7fcaf47a96..e768b60dd7 100644 --- a/packages/openops/src/index.ts +++ b/packages/openops/src/index.ts @@ -71,6 +71,7 @@ export * from './lib/axios-wrapper'; export * from './lib/build-wrapper-url'; export * from './lib/cloud-cli-common'; export * from './lib/dry-run-property'; +export * from './lib/follow-up-form'; export * from './lib/google-cloud/auth'; export * from './lib/google-cloud/bq-column-types'; diff --git a/packages/openops/src/lib/build-wrapper-url.ts b/packages/openops/src/lib/build-wrapper-url.ts index a872ed193f..6fb3fd583c 100644 --- a/packages/openops/src/lib/build-wrapper-url.ts +++ b/packages/openops/src/lib/build-wrapper-url.ts @@ -1,58 +1,51 @@ +import { encodeFollowUpForm, FollowUpForm } from './follow-up-form'; + const RESUME_PAGE = 'resume_execution.html'; const COLLECT_INPUT_PAGE = 'collect_input.html'; -const ANSWER_FORMATS = new Set(['text', 'email', 'number']); -const DEFAULT_ANSWER_FORMAT = 'text'; +// Slack rejects a whole message when one of its button URLs is longer than +// this. It is the strictest limit known for a channel, so anything that +// sizes a form (the Slack block, a settings check) should use it. +export const MAX_BUTTON_URL_LENGTH = 3000; + +// The heading is display-only on the form; cutting it keeps the link well +// under MAX_BUTTON_URL_LENGTH. +const MAX_TITLE_LENGTH = 150; -export type ButtonFollowUp = { - question: string; - answerFormat?: string; - noAnswerOption?: string; - title?: string; -}; +function cutTitle(title: string): string { + return title.length > MAX_TITLE_LENGTH + ? `${title.slice(0, MAX_TITLE_LENGTH - 1)}…` + : title; +} -// The collect-input page sends the answer back as the `answer` resume query -// param, surfaced in the step output as parameters.answer. +// Builds the link behind a message button. A button with a form opens the +// collect-input page, which reads the whole form from the link and sends +// each answer back as a resume query param, surfaced in the step output as +// parameters.. Any other button opens the page that resumes the +// flow directly. export function buildWrapperUrl({ frontendUrl, isTest, resumeUrl, - followUp, + form, }: { frontendUrl: string; isTest: boolean; resumeUrl: string; - followUp?: ButtonFollowUp; + form?: FollowUpForm; }): string { - const question = followUp?.question?.trim(); - - if (!question) { - return `${frontendUrl}/html/${RESUME_PAGE}?isTest=${isTest}&redirectUrl=${encodeURIComponent( - resumeUrl, - )}`; - } - - const format = - followUp?.answerFormat && ANSWER_FORMATS.has(followUp.answerFormat) - ? followUp.answerFormat - : DEFAULT_ANSWER_FORMAT; - - const params = new URLSearchParams({ - isTest: String(isTest), - question, - format, - redirectUrl: resumeUrl, - }); - - const noAnswerOption = followUp?.noAnswerOption?.trim(); - if (noAnswerOption) { - params.set('noAnswerOption', noAnswerOption); - } - - const title = followUp?.title?.trim(); - if (title) { - params.set('title', title); + if (form) { + const params = new URLSearchParams({ + isTest: String(isTest), + form: encodeFollowUpForm( + form.title ? { ...form, title: cutTitle(form.title) } : form, + ), + redirectUrl: resumeUrl, + }); + return `${frontendUrl}/html/${COLLECT_INPUT_PAGE}?${params.toString()}`; } - return `${frontendUrl}/html/${COLLECT_INPUT_PAGE}?${params.toString()}`; + return `${frontendUrl}/html/${RESUME_PAGE}?isTest=${isTest}&redirectUrl=${encodeURIComponent( + resumeUrl, + )}`; } diff --git a/packages/openops/src/lib/follow-up-form.ts b/packages/openops/src/lib/follow-up-form.ts new file mode 100644 index 0000000000..8f89ca9e5a --- /dev/null +++ b/packages/openops/src/lib/follow-up-form.ts @@ -0,0 +1,225 @@ +import { Property } from '@openops/blocks-framework'; + +export const FOLLOW_UP_FIELD_TYPES = [ + 'text', + 'email', + 'number', + 'select', + 'textarea', +] as const; + +export type FollowUpFieldType = (typeof FOLLOW_UP_FIELD_TYPES)[number]; + +export type FollowUpFormField = { + name: string; + label: string; + type: FollowUpFieldType; + required: boolean; + options?: string[]; + hint?: string; +}; + +// A form shown on the collect-input page when a message button is clicked. +// Each answer comes back to the flow as parameters.. +export type FollowUpForm = { + title?: string; + subtitle?: string; + fields: FollowUpFormField[]; + skipLabel?: string; +}; + +// The resume link already carries these params for routing; an answer with +// the same name would overwrite them. +export const RESERVED_FOLLOW_UP_FIELD_NAMES = new Set([ + 'button', + 'path', + 'executionCorrelationId', + 'isTest', + 'actionClicked', + 'actionType', + 'userName', + '__proto__', + 'constructor', + 'prototype', +]); + +type RawField = Partial>; +type RawForm = Partial>; + +const FIELD_NAME_REGEX = /^[A-Za-z]\w{0,39}$/; +const MAX_FIELDS = 10; + +function fail(reason: string): never { + throw new Error(`Invalid follow-up form: ${reason}`); +} + +function optionalText(value: unknown): string | undefined { + if (typeof value !== 'string') { + return undefined; + } + const trimmed = value.trim(); + return trimmed || undefined; +} + +function parseOptions(name: string, value: unknown): string[] { + // Numbers are accepted and shown as text; an answer always comes back to + // the flow as text anyway. + const options = Array.isArray(value) + ? value + .filter((v) => typeof v === 'string' || typeof v === 'number') + .map((v) => String(v).trim()) + : []; + const unique = [...new Set(options.filter(Boolean))]; + if (!unique.length) { + fail(`dropdown field "${name}" has no values`); + } + return unique; +} + +function parseField(value: unknown, index: number): FollowUpFormField { + const raw = (value ?? {}) as RawField; + const name = typeof raw.name === 'string' ? raw.name.trim() : ''; + if (!FIELD_NAME_REGEX.test(name)) { + fail( + `field ${index + 1} needs a name of letters, digits and underscores, starting with a letter`, + ); + } + if (RESERVED_FOLLOW_UP_FIELD_NAMES.has(name)) { + fail(`field name "${name}" is reserved`); + } + + const label = optionalText(raw.label); + if (!label) { + fail(`field "${name}" has no label`); + } + + const type = raw.type as FollowUpFieldType; + if (!FOLLOW_UP_FIELD_TYPES.includes(type)) { + fail(`field "${name}" has an unknown type "${String(raw.type)}"`); + } + + const field: FollowUpFormField = { + name, + label, + type, + required: raw.required !== false, + }; + if (type === 'select') { + field.options = parseOptions(name, raw.options); + } + const hint = optionalText(raw.hint); + if (hint) { + field.hint = hint; + } + return field; +} + +export function parseFollowUpForm(value: unknown): FollowUpForm { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + fail('expected an object with a list of fields'); + } + const raw = value as RawForm; + if (!Array.isArray(raw.fields) || !raw.fields.length) { + fail('it needs at least one field'); + } + if (raw.fields.length > MAX_FIELDS) { + fail(`it can have at most ${MAX_FIELDS} fields`); + } + + const fields = raw.fields.map((field, index) => parseField(field, index)); + const names = fields.map((field) => field.name); + const duplicate = names.find((name, i) => names.indexOf(name) !== i); + if (duplicate) { + fail(`two fields are named "${duplicate}"`); + } + + const form: FollowUpForm = { fields }; + const title = optionalText(raw.title); + const subtitle = optionalText(raw.subtitle); + const skipLabel = optionalText(raw.skipLabel); + if (title) { + form.title = title; + } + if (subtitle) { + form.subtitle = subtitle; + } + if (skipLabel) { + form.skipLabel = skipLabel; + } + return form; +} + +// base64url keeps the link shorter than percent-encoded JSON, which matters +// because Slack rejects a message whose button URL exceeds 3,000 characters. +export function encodeFollowUpForm(form: FollowUpForm): string { + return Buffer.from(JSON.stringify(form), 'utf8').toString('base64url'); +} + +// What a message button can carry about its form. The last three are the +// settings buttons had before forms existed. +export type ButtonFormSettings = { + followUpForm?: unknown; + followUpQuestion?: string; + answerFormat?: string; + noAnswerOption?: string; +}; + +const LEGACY_ANSWER_FORMATS = ['text', 'email', 'number'] as const; + +// Flows built before forms existed still send a single follow-up question, +// among them flows whose buttons are produced at run time by an earlier +// step. It becomes a one-field form whose answer keeps the name those flows +// read: parameters.answer. +// TODO: remove once no running flow sends followUpQuestion. +function legacyQuestionForm( + button: ButtonFormSettings, + header?: string, +): unknown { + const question = optionalText(button.followUpQuestion); + if (!question) { + return undefined; + } + const type = LEGACY_ANSWER_FORMATS.find( + (format) => format === button.answerFormat, + ); + return { + // The single-question page has always shown the message header. + title: header, + fields: [{ name: 'answer', label: question, type: type ?? 'text' }], + skipLabel: button.noAnswerOption, + }; +} + +function isEmptySetting(value: unknown): boolean { + const isEmptyObject = + typeof value === 'object' && + value !== null && + !Array.isArray(value) && + Object.keys(value).length === 0; + return value === undefined || value === null || value === '' || isEmptyObject; +} + +// Reads a message button's form. A button without one returns undefined. +// The message header is only used for buttons from flows built before forms +// existed. +export function resolveButtonForm( + button: ButtonFormSettings, + header?: string, +): FollowUpForm | undefined { + const value = isEmptySetting(button.followUpForm) + ? legacyQuestionForm(button, header) + : button.followUpForm; + if (isEmptySetting(value)) { + return undefined; + } + + return parseFollowUpForm(value); +} + +// The message-button setting in the Slack and Teams "Request Action" steps. +export const followUpFormProperty = Property.Json({ + displayName: 'Follow-up form', + description: + 'Optionally open a form when this button is clicked. Each answer is returned as parameters..', + required: false, +}); diff --git a/packages/openops/test/build-wrapper-url.test.ts b/packages/openops/test/build-wrapper-url.test.ts index 061cf553f6..b15b4746ee 100644 --- a/packages/openops/test/build-wrapper-url.test.ts +++ b/packages/openops/test/build-wrapper-url.test.ts @@ -1,4 +1,5 @@ import { buildWrapperUrl } from '../src/lib/build-wrapper-url'; +import { parseFollowUpForm } from '../src/lib/follow-up-form'; const baseParams = { frontendUrl: 'https://app.openops.com', @@ -9,8 +10,28 @@ const baseParams = { const encodedResumeUrl = encodeURIComponent(baseParams.resumeUrl); +const form = parseFollowUpForm({ + title: 'Request an exception', + subtitle: 'sqlserver-rds-dev', + fields: [ + { + name: 'reason', + label: 'Exception reason', + type: 'select', + options: ['VendorSet', 'Decommissioning'], + }, + { name: 'justification', label: 'Justification', type: 'textarea' }, + ], +}); + +// Mirrors how collect_input.html reads the form param. +function readForm(url: string): { title?: string } { + const encoded = new URL(url).searchParams.get('form') ?? ''; + return JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')); +} + describe('buildWrapperUrl', () => { - test('uses the default resume page when no follow-up question is given', () => { + test('uses the resume page for a button without a form', () => { const url = buildWrapperUrl(baseParams); expect(url).toBe( @@ -18,84 +39,48 @@ describe('buildWrapperUrl', () => { ); }); - test('uses the collect-input page when a follow-up question is given', () => { - const url = buildWrapperUrl({ - ...baseParams, - followUp: { - question: "What is the correct owner's email?", - answerFormat: 'email', - }, - }); + test('uses the collect-input page and carries the whole form in one param', () => { + const url = buildWrapperUrl({ ...baseParams, form }); const parsed = new URL(url); expect(parsed.origin).toBe('https://app.openops.com'); expect(parsed.pathname).toBe('/html/collect_input.html'); - expect(parsed.searchParams.get('question')).toBe( - "What is the correct owner's email?", - ); - expect(parsed.searchParams.get('format')).toBe('email'); - expect(parsed.searchParams.get('isTest')).toBe('false'); + expect([...parsed.searchParams.keys()]).toEqual([ + 'isTest', + 'form', + 'redirectUrl', + ]); + expect(parsed.searchParams.get('form')).toMatch(/^[A-Za-z0-9_-]+$/); expect(parsed.searchParams.get('redirectUrl')).toBe(baseParams.resumeUrl); + expect(readForm(url)).toEqual(form); }); - test('includes the message header as the form title when given', () => { - const url = buildWrapperUrl({ - ...baseParams, - followUp: { - question: 'Who owns this?', - title: 'Cost savings opportunity: vol-123', - }, - }); - - expect(new URL(url).searchParams.get('title')).toBe( - 'Cost savings opportunity: vol-123', - ); - }); - - test('includes the no-answer option when given', () => { - const url = buildWrapperUrl({ - ...baseParams, - followUp: { - question: "What is the correct owner's email?", - noAnswerOption: "I don't know the owner", - }, - }); - - expect(new URL(url).searchParams.get('noAnswerOption')).toBe( - "I don't know the owner", - ); - }); - - test('omits the no-answer option param when not given', () => { + test('keeps non-Latin text intact', () => { const url = buildWrapperUrl({ ...baseParams, - followUp: { question: 'Why was this dismissed?' }, + form: { ...form, subtitle: 'ресурс – 資源' }, }); - expect(new URL(url).searchParams.has('noAnswerOption')).toBe(false); + expect(readForm(url)).toEqual({ ...form, subtitle: 'ресурс – 資源' }); }); - test('ignores a follow-up with an empty question', () => { + test('cuts a long form heading so the link stays within Slack limits', () => { const url = buildWrapperUrl({ ...baseParams, - followUp: { question: ' ' }, + form: { ...form, title: 'x'.repeat(400) }, }); - expect(url).toContain('/html/resume_execution.html?'); + const title = readForm(url).title ?? ''; + expect(title).toHaveLength(150); + expect(title.endsWith('…')).toBe(true); }); - test('defaults the answer format to text for unknown formats', () => { - const url = buildWrapperUrl({ - ...baseParams, - followUp: { question: 'Why?', answerFormat: 'dropdown' }, - }); - - expect(new URL(url).searchParams.get('format')).toBe('text'); - }); - - test('passes isTest through', () => { - const url = buildWrapperUrl({ ...baseParams, isTest: true }); - - expect(url).toContain('isTest=true'); + test.each([true, false])('passes isTest=%p through', (isTest) => { + expect(buildWrapperUrl({ ...baseParams, isTest })).toContain( + `isTest=${isTest}`, + ); + expect(buildWrapperUrl({ ...baseParams, isTest, form })).toContain( + `isTest=${isTest}`, + ); }); }); diff --git a/packages/openops/test/collect-input-page.test.ts b/packages/openops/test/collect-input-page.test.ts new file mode 100644 index 0000000000..2824fafaf7 --- /dev/null +++ b/packages/openops/test/collect-input-page.test.ts @@ -0,0 +1,461 @@ +import { JSDOM } from 'jsdom'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { TextDecoder } from 'node:util'; +import { buildWrapperUrl } from '../src/lib/build-wrapper-url'; +import { + FOLLOW_UP_FIELD_TYPES, + parseFollowUpForm, + RESERVED_FOLLOW_UP_FIELD_NAMES, +} from '../src/lib/follow-up-form'; + +// The form page is a static file served by the frontend. These tests load it +// in a simulated browser with links built by buildWrapperUrl, so the link the +// blocks send and the page that reads it are checked together. +const PAGE_HTML = readFileSync( + join(__dirname, '../../react-ui/public/html/collect_input.html'), + 'utf8', +); + +const ORIGIN = 'https://app.example.test'; +const RESUME_URL = `${ORIGIN}/api/v1/flow-runs/run-1/requests/pause-1?button=Add%20exception&path=step_1`; + +const exceptionForm = parseFollowUpForm({ + title: 'Request an exception', + subtitle: 'sqlserver-rds-dev', + fields: [ + { + name: 'reason', + label: 'Exception reason', + type: 'select', + options: ['VendorSet', 'Decommissioning'], + }, + { + name: 'justification', + label: 'Justification', + type: 'textarea', + hint: 'Explain why', + }, + { name: 'ticket', label: 'Ticket', type: 'text', required: false }, + ], + skipLabel: 'Not sure', +}); + +const openPages: JSDOM[] = []; + +function openPage(url: string): Document { + const dom = new JSDOM(PAGE_HTML, { + url, + runScripts: 'dangerously', + beforeParse(window) { + // jsdom has no TextDecoder; every supported browser does. + Object.assign(window, { TextDecoder }); + }, + }); + openPages.push(dom); + return dom.window.document; +} + +function openForm(form: unknown, isTest = false): Document { + const params = new URLSearchParams({ + isTest: String(isTest), + form: Buffer.from(JSON.stringify(form), 'utf8').toString('base64url'), + redirectUrl: RESUME_URL, + }); + return openPage(`${ORIGIN}/html/collect_input.html?${params.toString()}`); +} + +function isShown(document: Document, id: string): boolean { + return !document.getElementById(id)?.classList.contains('hidden'); +} + +function control(document: Document, name: string): HTMLInputElement { + return document.querySelector(`[name="${name}"]`) as HTMLInputElement; +} + +function submit(document: Document): void { + const form = document.getElementById('input-form') as HTMLFormElement; + const SubmitEvent = document.defaultView?.Event as typeof Event; + form.dispatchEvent(new SubmitEvent('submit', { cancelable: true })); +} + +function shownErrors(document: Document): number { + return [...document.querySelectorAll('.error')].filter( + (error) => error.style.display === 'block', + ).length; +} + +function resumedWith(document: Document): Record | null { + const iframe = document.querySelector('iframe'); + if (!iframe) { + return null; + } + const url = new URL(iframe.src); + expect(`${url.origin}${url.pathname}`).toBe(RESUME_URL.split('?')[0]); + return Object.fromEntries(url.searchParams); +} + +afterEach(() => { + openPages.splice(0).forEach((dom) => dom.window.close()); +}); + +describe('collect_input.html', () => { + describe('with a form link built by buildWrapperUrl', () => { + const formUrl = buildWrapperUrl({ + frontendUrl: ORIGIN, + isTest: false, + resumeUrl: RESUME_URL, + form: exceptionForm, + }); + + test('shows the heading, the subtitle and one input per field', () => { + const document = openPage(formUrl); + + expect(isShown(document, 'form-view')).toBe(true); + expect(document.querySelector('#form-view h2')?.textContent).toBe( + 'Request an exception', + ); + expect(document.querySelector('.subtitle')?.textContent).toBe( + 'sqlserver-rds-dev', + ); + expect(control(document, 'reason').tagName).toBe('SELECT'); + expect( + [...document.querySelectorAll('select option')].map( + (option) => option.textContent, + ), + ).toEqual(['Select…', 'VendorSet', 'Decommissioning']); + expect(control(document, 'justification').tagName).toBe('TEXTAREA'); + expect(document.querySelector('.hint')?.textContent).toBe('Explain why'); + expect(control(document, 'ticket').type).toBe('text'); + // Required fields are marked; the optional one is not. + expect(document.querySelectorAll('.required-mark')).toHaveLength(2); + }); + + test('shows an error per empty required field and does not resume', () => { + const document = openPage(formUrl); + + submit(document); + + expect(shownErrors(document)).toBe(2); + expect(resumedWith(document)).toBeNull(); + expect(isShown(document, 'done-view')).toBe(false); + }); + + test('resumes the flow with one param per field, keeping the routing params', () => { + const document = openPage(formUrl); + control(document, 'reason').value = 'VendorSet'; + control(document, 'justification').value = ' Migrating in February '; + + submit(document); + + expect(resumedWith(document)).toEqual({ + button: 'Add exception', + path: 'step_1', + reason: 'VendorSet', + justification: 'Migrating in February', + ticket: '', + }); + expect(isShown(document, 'done-view')).toBe(true); + expect(isShown(document, 'form-view')).toBe(false); + }); + + test('sends every field back empty when the skip button is clicked', () => { + const document = openPage(formUrl); + const skipButton = document.getElementById('skip-button'); + expect(skipButton?.textContent).toBe('Not sure'); + + skipButton?.click(); + + expect(resumedWith(document)).toMatchObject({ + reason: '', + justification: '', + ticket: '', + }); + }); + + test('shows only the test notice in test mode', () => { + const document = openPage( + buildWrapperUrl({ + frontendUrl: ORIGIN, + isTest: true, + resumeUrl: RESUME_URL, + form: exceptionForm, + }), + ); + + expect(isShown(document, 'form-view')).toBe(false); + expect(document.getElementById('done-title')?.textContent).toContain( + 'Test succeeded', + ); + expect(resumedWith(document)).toBeNull(); + }); + }); + + describe('errors', () => { + function errorOf(document: Document, name: string): HTMLElement { + const id = control(document, name).id; + return document.getElementById(`${id}-error`) as HTMLElement; + } + + function type(document: Document, name: string, value: string): void { + const field = control(document, name); + field.value = value; + const InputEvent = document.defaultView?.Event as typeof Event; + field.dispatchEvent(new InputEvent('input', { bubbles: true })); + } + + const form = { + fields: [ + { name: 'email', label: 'Email', type: 'email', hint: 'Work email' }, + { name: 'months', label: 'Months', type: 'number' }, + { name: 'note', label: 'Note', type: 'text', required: false }, + ], + }; + + test('says what is wrong with each field', () => { + const document = openForm(form); + + submit(document); + + expect(errorOf(document, 'email').textContent).toBe( + 'This field is required.', + ); + expect(errorOf(document, 'months').textContent).toBe( + 'This field is required.', + ); + expect(errorOf(document, 'note').style.display).toBe('none'); + + type(document, 'email', 'not-an-email'); + expect(errorOf(document, 'email').textContent).toBe( + 'Enter a valid email address.', + ); + }); + + test('marks the invalid inputs and focuses the first one', () => { + const document = openForm(form); + + submit(document); + + expect(control(document, 'email').getAttribute('aria-invalid')).toBe( + 'true', + ); + expect(control(document, 'email').classList.contains('invalid')).toBe( + true, + ); + expect(control(document, 'note').hasAttribute('aria-invalid')).toBe( + false, + ); + expect(document.activeElement).toBe(control(document, 'email')); + }); + + test('clears an error as soon as the answer is corrected', () => { + const document = openForm(form); + submit(document); + + type(document, 'email', 'owner@example.com'); + + expect(errorOf(document, 'email').style.display).toBe('none'); + expect(control(document, 'email').hasAttribute('aria-invalid')).toBe( + false, + ); + // The other field keeps its error until it is corrected too. + expect(errorOf(document, 'months').style.display).toBe('block'); + }); + + test('shows no error while typing before the first submit', () => { + const document = openForm(form); + + type(document, 'email', 'not-an-email'); + + expect(errorOf(document, 'email').style.display).not.toBe('block'); + }); + + test('links each input to its hint and error for screen readers', () => { + const document = openForm(form); + const email = control(document, 'email'); + + expect(email.getAttribute('aria-describedby')).toBe( + `${email.id}-hint ${email.id}-error`, + ); + expect(email.required).toBe(true); + expect(control(document, 'note').required).toBe(false); + }); + }); + + test('has no heading and no skip button when the form sets neither', () => { + const document = openForm({ + fields: [{ name: 'note', label: 'Note', type: 'text' }], + }); + + expect(document.querySelector('#form-view h2')).toBeNull(); + expect(isShown(document, 'skip-section')).toBe(false); + // A single-field form shows no required mark. + expect(document.querySelector('.required-mark')).toBeNull(); + }); + + test.each([ + ['email', 'not-an-email', 'owner@example.com'], + ['number', 'twelve', '12'], + ])('checks the format of a %s field', (type, invalid, valid) => { + const document = openForm({ + fields: [{ name: 'value', label: 'Value', type }], + }); + + control(document, 'value').value = invalid; + submit(document); + expect(resumedWith(document)).toBeNull(); + + control(document, 'value').value = valid; + submit(document); + expect(resumedWith(document)).toMatchObject({ value: valid }); + }); + + test('accepts a dropdown value longer than the limit for typed text', () => { + const longOption = 'x'.repeat(300); + const document = openForm({ + fields: [ + { + name: 'reason', + label: 'Reason', + type: 'select', + options: [longOption], + }, + ], + }); + control(document, 'reason').value = longOption; + + submit(document); + + expect(resumedWith(document)).toMatchObject({ reason: longOption }); + }); + + describe('with a link sent before forms existed', () => { + const legacyUrl = `${ORIGIN}/html/collect_input.html?${new URLSearchParams({ + isTest: 'false', + question: "What is the correct owner's email?", + format: 'email', + redirectUrl: RESUME_URL, + noAnswerOption: "I don't know the owner", + title: 'Cost savings opportunity: vol-123', + }).toString()}`; + + test('shows the single question as before', () => { + const document = openPage(legacyUrl); + + expect(document.querySelector('#form-view h2')?.textContent).toBe( + 'Cost savings opportunity: vol-123', + ); + expect(document.querySelector('label')?.textContent).toBe( + "What is the correct owner's email?", + ); + expect(control(document, 'answer').type).toBe('email'); + expect(document.getElementById('skip-button')?.textContent).toBe( + "I don't know the owner", + ); + }); + + test('resumes with the answer in the "answer" param', () => { + const document = openPage(legacyUrl); + control(document, 'answer').value = 'owner@example.com'; + + submit(document); + + expect(resumedWith(document)).toMatchObject({ + answer: 'owner@example.com', + }); + }); + }); + + describe('invalid links', () => { + test('rejects a form that cannot be read', () => { + const params = new URLSearchParams({ + isTest: 'false', + form: 'not-a-form', + redirectUrl: RESUME_URL, + }); + const document = openPage( + `${ORIGIN}/html/collect_input.html?${params.toString()}`, + ); + + expect(isShown(document, 'invalid-view')).toBe(true); + expect(isShown(document, 'form-view')).toBe(false); + }); + + test('rejects a resume link to another site', () => { + const document = openPage( + buildWrapperUrl({ + frontendUrl: ORIGIN, + isTest: false, + resumeUrl: + 'https://evil.example.test/v1/flow-runs/run-1/requests/pause-1', + form: exceptionForm, + }), + ); + + expect(isShown(document, 'invalid-view')).toBe(true); + }); + + test('treats non-text heading values as missing', () => { + const document = openForm({ + title: 5, + subtitle: {}, + skipLabel: 7, + fields: [{ name: 'note', label: 'Note', type: 'text' }], + }); + + expect(isShown(document, 'form-view')).toBe(true); + expect(document.querySelector('#form-view h2')).toBeNull(); + expect(isShown(document, 'skip-section')).toBe(false); + }); + }); + + // The page repeats the rules of follow-up-form.ts, because it is a static + // file. These keep the two from drifting apart. + describe('agrees with parseFollowUpForm', () => { + test.each([...FOLLOW_UP_FIELD_TYPES])( + 'accepts the field type %s', + (type) => { + const document = openForm({ + fields: [{ name: 'value', label: 'Value', type, options: ['A'] }], + }); + + expect(isShown(document, 'form-view')).toBe(true); + expect(control(document, 'value')).not.toBeNull(); + }, + ); + + test.each([...RESERVED_FOLLOW_UP_FIELD_NAMES])( + 'rejects the reserved field name %s', + (name) => { + const document = openForm({ + fields: [{ name, label: 'Value', type: 'text' }], + }); + + expect(isShown(document, 'invalid-view')).toBe(true); + }, + ); + + test.each([ + ['an unknown type', [{ name: 'a', label: 'A', type: 'date' }]], + ['a name with spaces', [{ name: 'a b', label: 'A', type: 'text' }]], + ['a missing label', [{ name: 'a', label: ' ', type: 'text' }]], + [ + 'a dropdown without values', + [{ name: 'a', label: 'A', type: 'select' }], + ], + [ + 'two fields with one name', + [ + { name: 'a', label: 'A', type: 'text' }, + { name: 'a', label: 'B', type: 'text' }, + ], + ], + ['no fields', []], + ])('rejects %s, as parseFollowUpForm does', (_case, fields) => { + expect(() => parseFollowUpForm({ fields })).toThrow( + /Invalid follow-up form/, + ); + expect(isShown(openForm({ fields }), 'invalid-view')).toBe(true); + }); + }); +}); diff --git a/packages/openops/test/follow-up-form.test.ts b/packages/openops/test/follow-up-form.test.ts new file mode 100644 index 0000000000..42ad4c95b6 --- /dev/null +++ b/packages/openops/test/follow-up-form.test.ts @@ -0,0 +1,229 @@ +import { + parseFollowUpForm, + resolveButtonForm, +} from '../src/lib/follow-up-form'; + +const exceptionForm = { + title: 'Request an exception', + subtitle: 'sqlserver-rds-dev', + fields: [ + { + name: 'reason', + label: 'Exception reason', + type: 'select', + options: ['VendorSet', 'Decommissioning'], + }, + { + name: 'justification', + label: 'Justification', + type: 'textarea', + hint: 'Explain why this resource needs the exception', + }, + ], +}; + +describe('parseFollowUpForm', () => { + test('returns the form with every field required by default', () => { + expect(parseFollowUpForm(exceptionForm)).toEqual({ + title: 'Request an exception', + subtitle: 'sqlserver-rds-dev', + fields: [ + { + name: 'reason', + label: 'Exception reason', + type: 'select', + options: ['VendorSet', 'Decommissioning'], + required: true, + }, + { + name: 'justification', + label: 'Justification', + type: 'textarea', + hint: 'Explain why this resource needs the exception', + required: true, + }, + ], + }); + }); + + test('keeps an explicit optional field and the skip label', () => { + const form = parseFollowUpForm({ + fields: [ + { + name: 'answer', + label: 'Owner email', + type: 'email', + required: false, + }, + ], + skipLabel: "I don't know the owner", + }); + + expect(form.fields[0].required).toBe(false); + expect(form.skipLabel).toBe("I don't know the owner"); + }); + + test('trims text and drops empty and repeated dropdown values', () => { + const form = parseFollowUpForm({ + title: ' Heading ', + fields: [ + { + name: 'reason', + label: ' Reason ', + type: 'select', + options: [' A ', '', 'B', 'A'], + }, + ], + }); + + expect(form.title).toBe('Heading'); + expect(form.fields[0].label).toBe('Reason'); + expect(form.fields[0].options).toEqual(['A', 'B']); + }); + + test('turns number dropdown values into text', () => { + const form = parseFollowUpForm({ + fields: [ + { + name: 'months', + label: 'Months', + type: 'select', + options: [3, 6, '12'], + }, + ], + }); + + expect(form.fields[0].options).toEqual(['3', '6', '12']); + }); + + test.each([ + ['a form that is not an object', 'just text'], + ['a form without fields', { title: 'x' }], + ['a form with no fields', { fields: [] }], + [ + 'a field without a label', + { fields: [{ name: 'a', label: ' ', type: 'text' }] }, + ], + [ + 'a field with an unknown type', + { fields: [{ name: 'a', label: 'A', type: 'date' }] }, + ], + [ + 'a field name with spaces', + { fields: [{ name: 'a b', label: 'A', type: 'text' }] }, + ], + [ + 'two fields with the same name', + { + fields: [ + { name: 'a', label: 'A', type: 'text' }, + { name: 'a', label: 'B', type: 'text' }, + ], + }, + ], + [ + 'a dropdown without values', + { fields: [{ name: 'a', label: 'A', type: 'select', options: [] }] }, + ], + ])('rejects %s', (_case, value) => { + expect(() => parseFollowUpForm(value)).toThrow(/Invalid follow-up form/); + }); + + test.each(['button', 'path', 'actionClicked', 'userName', 'isTest'])( + 'rejects the field name %s, which the resume link already uses', + (name) => { + expect(() => + parseFollowUpForm({ fields: [{ name, label: 'A', type: 'text' }] }), + ).toThrow(`Invalid follow-up form: field name "${name}" is reserved`); + }, + ); +}); + +describe('resolveButtonForm', () => { + test.each([undefined, null, '', {}])( + 'treats a followUpForm of %p as no form', + (followUpForm) => { + expect(resolveButtonForm({ followUpForm }, 'Header')).toBeUndefined(); + }, + ); + + test('leaves a form without a title without a heading', () => { + const form = resolveButtonForm( + { + followUpForm: { + fields: [{ name: 'answer', label: 'Email', type: 'email' }], + }, + }, + 'Cost savings opportunity: vol-123', + ); + + expect(form?.title).toBeUndefined(); + }); + + test("keeps the form's own heading", () => { + const form = resolveButtonForm({ followUpForm: exceptionForm }, 'Header'); + + expect(form?.title).toBe('Request an exception'); + }); + + test('rejects an invalid form', () => { + expect(() => + resolveButtonForm({ followUpForm: { fields: [] } }, 'Header'), + ).toThrow(/Invalid follow-up form/); + }); + + describe('buttons from flows built before forms existed', () => { + test('turns the single follow-up question into a one-field form answered as "answer"', () => { + const form = resolveButtonForm( + { + followUpQuestion: "What is the correct owner's email?", + answerFormat: 'email', + noAnswerOption: "I don't know the owner", + }, + 'Cost savings opportunity: vol-123', + ); + + expect(form).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.each([undefined, 'dropdown'])( + 'uses a text field when the answer format is %p', + (answerFormat) => { + const form = resolveButtonForm({ + followUpQuestion: 'Why?', + answerFormat, + }); + + expect(form?.fields[0].type).toBe('text'); + expect(form?.skipLabel).toBeUndefined(); + }, + ); + + test('ignores an empty question', () => { + expect(resolveButtonForm({ followUpQuestion: ' ' })).toBeUndefined(); + }); + + test('prefers the form when a button has both', () => { + const form = resolveButtonForm({ + followUpForm: exceptionForm, + followUpQuestion: 'Ignored?', + }); + + expect(form?.fields.map((field) => field.name)).toEqual([ + 'reason', + 'justification', + ]); + }); + }); +}); diff --git a/packages/react-ui/public/html/collect_input.html b/packages/react-ui/public/html/collect_input.html index 832295c442..8affdeefad 100644 --- a/packages/react-ui/public/html/collect_input.html +++ b/packages/react-ui/public/html/collect_input.html @@ -10,11 +10,14 @@ body { font-family: 'Satoshi', sans-serif; margin: 0; - padding: 0; + /* Keeps the logo and the last button off the window edges when the + form is taller than the window. */ + padding: 32px 0; + box-sizing: border-box; display: flex; align-items: center; justify-content: center; - height: 100vh; + min-height: 100vh; background-color: #f9f9f9; color: #333; text-align: center; @@ -48,7 +51,9 @@ margin-bottom: 6px; } - input { + input, + select, + textarea { width: 100%; box-sizing: border-box; padding: 10px 12px; @@ -56,20 +61,73 @@ font-family: inherit; border: 1px solid #ccc; border-radius: 6px; - margin-bottom: 8px; } - input:focus { + select { + background-color: #fff; + color: #333; + } + + /* The "Select…" entry is not an answer, so it reads as a placeholder. */ + select.empty { + color: #767676; + } + + select.empty option { + color: #333; + } + + textarea { + resize: vertical; + } + + input:focus, + select:focus, + textarea:focus { outline: none; border-color: #6e41e2; } + .subtitle { + margin: 0 0 24px; + font-size: 0.95rem; + color: #666; + overflow-wrap: anywhere; + } + + .field { + margin-bottom: 16px; + } + + /* The hint and the error sit close to their own input, and well apart + from the next field. */ + .field .invalid, + .field .invalid:focus { + border-color: #c0392b; + } + + .required-mark { + color: #c0392b; + margin-left: 2px; + } + + .hint { + margin: 6px 0 0; + text-align: left; + font-size: 0.85rem; + color: #666; + } + .error { display: none; text-align: left; color: #c0392b; font-size: 0.85rem; - margin-bottom: 8px; + margin: 6px 0 0; + } + + #input-form > button { + margin-top: 8px; } button { @@ -126,11 +184,7 @@
- - -

Please enter a valid value.

+