Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dest/escalation-policies: use destinations for EP step form #3717

Merged
merged 29 commits into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
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
3 changes: 3 additions & 0 deletions graphql2/graphqlapp/destinationdisplayinfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ func (a *Destination) DisplayInfo(ctx context.Context, obj *graphql2.Destination
func (a *Query) DestinationDisplayInfo(ctx context.Context, dest graphql2.DestinationInput) (*graphql2.DestinationDisplayInfo, error) {
app := (*App)(a)
cfg := config.FromContext(ctx)
if err := app.ValidateDestination(ctx, "input", &dest); err != nil {
return nil, err
}
switch dest.Type {
case destTwilioSMS:
n, err := phonenumbers.Parse(dest.FieldValue(fieldPhoneNumber), "")
Expand Down
147 changes: 147 additions & 0 deletions web/src/app/escalation-policies/PolicyStepFormDest.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import React from 'react'
import type { Meta, StoryObj } from '@storybook/react'
import PolicyStepFormDest, { FormValue } from './PolicyStepFormDest'
import { expect, userEvent, waitFor, within } from '@storybook/test'
import { handleDefaultConfig, handleExpFlags } from '../storybook/graphql'
import { HttpResponse, graphql } from 'msw'
import { useArgs } from '@storybook/preview-api'
import { DestFieldValueError } from '../util/errtypes'

const VALID_PHONE = '+12225558989'
const VALID_PHONE2 = '+13335558989'
const INVALID_PHONE = '+15555'

const meta = {
title: 'escalation-policies/PolicyStepFormDest',
component: PolicyStepFormDest,
render: function Component(args) {
const [, setArgs] = useArgs()
const onChange = (newValue: FormValue): void => {
if (args.onChange) args.onChange(newValue)
setArgs({ value: newValue })
}
return <PolicyStepFormDest {...args} onChange={onChange} />
},
tags: ['autodocs'],
parameters: {
msw: {
handlers: [
handleDefaultConfig,
handleExpFlags('dest-types'),
graphql.query('ValidateDestination', ({ variables: vars }) => {
return HttpResponse.json({
data: {
destinationFieldValidate: vars.input.value === VALID_PHONE,
},
})
}),
graphql.query('DestDisplayInfo', ({ variables: vars }) => {
switch (vars.input.values[0].value) {
case VALID_PHONE:
case VALID_PHONE2:
return HttpResponse.json({
data: {
destinationDisplayInfo: {
text:
vars.input.values[0].value === VALID_PHONE
? 'VALID_CHIP_1'
: 'VALID_CHIP_2',
iconURL: 'builtin://phone-voice',
iconAltText: 'Voice Call',
},
},
})

default:
return HttpResponse.json({
errors: [
{
message: 'generic error',
},
{
path: ['destinationDisplayInfo', 'input'],
message: 'invalid phone number',
extensions: {
code: 'INVALID_DEST_FIELD_VALUE',
fieldID: 'phone-number',
},
} satisfies DestFieldValueError,
],
})
}
}),
],
},
},
} satisfies Meta<typeof PolicyStepFormDest>

export default meta
type Story = StoryObj<typeof meta>
export const Empty: Story = {
args: {
value: {
delayMinutes: 15,
actions: [],
},
},
}

export const WithExistingActions: Story = {
args: {
value: {
delayMinutes: 15,
actions: [
{
type: 'single-field',
values: [{ fieldID: 'phone-number', value: VALID_PHONE }],
},
{
type: 'single-field',
values: [{ fieldID: 'phone-number', value: VALID_PHONE2 }],
},
],
},
},
}

export const ManageActions: Story = {
args: {
value: {
delayMinutes: 15,
actions: [],
},
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement)
const phoneInput = await canvas.findByLabelText('Phone Number')

await userEvent.clear(phoneInput)
await userEvent.type(phoneInput, INVALID_PHONE)
await userEvent.click(await canvas.findByText('Add Action'))

await waitFor(async () => {
await expect(await canvas.findByLabelText('Phone Number')).toBeInvalid()
await expect(await canvas.findByText('generic error')).toBeVisible()
await expect(
await canvas.findByText('Invalid phone number'),
).toBeVisible()
})

await userEvent.clear(phoneInput)

// Editing the input should clear the error
await expect(await canvas.findByLabelText('Phone Number')).not.toBeInvalid()

await userEvent.type(phoneInput, VALID_PHONE)

await userEvent.click(await canvas.findByText('Add Action'))

// should result in chip
await expect(await canvas.findByText('VALID_CHIP_1')).toBeVisible()

// Delete the chip
await userEvent.click(await canvas.findByTestId('CancelIcon'))

await expect(await canvas.findByText('No actions')).toBeVisible()
},
}
197 changes: 197 additions & 0 deletions web/src/app/escalation-policies/PolicyStepFormDest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
import React, { useState, ReactNode, useEffect } from 'react'
import { FormContainer, FormField } from '../forms'
import Grid from '@mui/material/Grid'

import NumberField from '../util/NumberField'
import { DestinationInput, FieldValueInput } from '../../schema'
import DestinationInputChip from '../util/DestinationInputChip'
import { Button, TextField, Typography } from '@mui/material'
import { renderMenuItem } from '../selection/DisableableMenuItem'
import DestinationField from '../selection/DestinationField'
import { useEPTargetTypes } from '../util/RequireConfig'
import { gql, useClient, CombinedError } from 'urql'
import {
DestFieldValueError,
KnownError,
isDestFieldError,
} from '../util/errtypes'
import { splitErrorsByPath } from '../util/errutil'
import DialogContentError from '../dialogs/components/DialogContentError'
import makeStyles from '@mui/styles/makeStyles'

const useStyles = makeStyles(() => {
return {
errorContainer: {
flexGrow: 0,
overflowY: 'visible',
},
}
})

export type FormValue = {
delayMinutes: number
actions: DestinationInput[]
}

export type PolicyStepFormDestProps = {
value: FormValue
errors?: (KnownError | DestFieldValueError)[]
disabled?: boolean
onChange: (value: FormValue) => void
}

const query = gql`
query DestDisplayInfo($input: DestinationInput!) {
destinationDisplayInfo(input: $input) {
text
iconURL
iconAltText
linkURL
}
}
`

export default function PolicyStepFormDest(
props: PolicyStepFormDestProps,
): ReactNode {
const types = useEPTargetTypes()
const classes = useStyles()
const [destType, setDestType] = useState(types[0].type)
const [values, setValues] = useState<FieldValueInput[]>([])
const validationClient = useClient()
const [err, setErr] = useState<CombinedError | null>(null)
const [destErrors, otherErrs] = splitErrorsByPath(err || props.errors, [
'destinationDisplayInfo.input',
])

useEffect(() => {
setErr(null)
}, [props.value])

function handleDelete(a: DestinationInput): void {
if (!props.onChange) return
props.onChange({
...props.value,
actions: props.value.actions.filter((b) => a !== b),
})
}

function renderErrors(): React.JSX.Element[] {
return otherErrs.map((err, idx) => (
<DialogContentError
error={err.message || err}
key={idx}
noPadding
className={classes.errorContainer}
/>
))
}

return (
<FormContainer
value={props.value}
onChange={(newValue: FormValue) => {
if (!props.onChange) return
props.onChange(newValue)
}}
errors={props.errors}
>
<Grid container spacing={2}>
<Grid item xs={12}>
{props.value.actions.map((a, idx) => (
<DestinationInputChip
key={idx}
value={a}
onDelete={props.disabled ? undefined : () => handleDelete(a)}
/>
))}
{props.value.actions.length === 0 && (
<Typography variant='body2' color='textSecondary'>
No actions
</Typography>
)}
</Grid>
<Grid item xs={12}>
<TextField
select
fullWidth
disabled={props.disabled}
value={destType}
onChange={(e) => setDestType(e.target.value)}
>
{types.map((t) =>
renderMenuItem({
label: t.name,
value: t.type,
disabled: !t.enabled,
disabledMessage: t.enabled ? '' : t.disabledMessage,
}),
)}
</TextField>
</Grid>
<Grid item xs={12}>
<DestinationField
destType={destType}
value={values}
disabled={props.disabled}
onChange={(newValue: FieldValueInput[]) => {
setErr(null)
setValues(newValue)
}}
destFieldErrors={destErrors.filter(isDestFieldError)}
/>
</Grid>
<Grid container item xs={12} justifyContent='flex-end'>
{otherErrs && renderErrors()}
<Button
variant='contained'
onClick={() => {
if (!props.onChange) return
validationClient
.query(query, {
input: {
type: destType,
values,
},
})
.toPromise()
.then((res) => {
if (res.error) {
setErr(res.error)
return
}
setValues([])
props.onChange({
...props.value,
actions: props.value.actions.concat({
type: destType,
values,
}),
})
})
}}
>
Add Action
</Button>
</Grid>
<Grid item xs={12}>
<FormField
component={NumberField}
disabled={props.disabled}
fullWidth
label='Delay (minutes)'
name='delayMinutes'
required
min={1}
max={9000}
hint={
props.value.delayMinutes === 0
? 'This will cause the step to immediately escalate'
: `This will cause the step to escalate after ${props.value.delayMinutes}m`
}
/>
</Grid>
</Grid>
</FormContainer>
)
}
4 changes: 3 additions & 1 deletion web/src/app/selection/DestinationInputDirect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ const noSuspense = { suspense: false }
function trimPrefix(value: string, prefix: string): string {
if (!prefix) return value
if (!value) return value
if (value.startsWith(prefix)) return value.slice(prefix.length)
while (value.startsWith(prefix)) {
value = value.slice(prefix.length)
}
return value
}

Expand Down
Loading
Loading