You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by GitBox <gi...@apache.org> on 2020/12/09 18:20:04 UTC

[GitHub] [incubator-superset] riahk commented on a change in pull request #11770: feat: alerts/reports add/edit modal

riahk commented on a change in pull request #11770:
URL: https://github.com/apache/incubator-superset/pull/11770#discussion_r539539412



##########
File path: superset-frontend/src/views/CRUD/alert/AlertReportModal.tsx
##########
@@ -0,0 +1,1307 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import React, { FunctionComponent, useState, useEffect } from 'react';
+import { styled, t, SupersetClient } from '@superset-ui/core';
+import rison from 'rison';
+import { useSingleViewResource } from 'src/views/CRUD/hooks';
+
+import Icon from 'src/components/Icon';
+import Modal from 'src/common/components/Modal';
+import { Switch } from 'src/common/components/Switch';
+import { Select } from 'src/common/components/Select';
+import { Radio } from 'src/common/components/Radio';
+import { AsyncSelect } from 'src/components/Select';
+import withToasts from 'src/messageToasts/enhancers/withToasts';
+
+import Owner from 'src/types/Owner';
+import { AlertObject, Operator, Recipient, MetaObject } from './types';
+
+type SelectValue = {
+  value: string;
+  label: string;
+};
+
+interface AlertReportModalProps {
+  addDangerToast: (msg: string) => void;
+  alert?: AlertObject | null;
+  isReport?: boolean;
+  onAdd?: (alert?: AlertObject) => void;
+  onHide: () => void;
+  show: boolean;
+}
+
+const NOTIFICATION_METHODS: NotificationMethod[] = ['Email', 'Slack'];
+
+const CONDITIONS = [
+  {
+    label: '< (Smaller than)',
+    value: '<',
+  },
+  {
+    label: '> (Larger than)',
+    value: '>',
+  },
+  {
+    label: '<= (Smaller or equal)',
+    value: '<=',
+  },
+  {
+    label: '>= (Larger or equal)',
+    value: '>=',
+  },
+  {
+    label: '== (Is Equal)',
+    value: '==',
+  },
+  {
+    label: '!= (Is Not Equal)',
+    value: '!=',
+  },
+];
+
+const RETENTION_OPTIONS = [
+  {
+    label: 'None',
+    value: 0,
+  },
+  {
+    label: '30 days',
+    value: 30,
+  },
+  {
+    label: '60 days',
+    value: 60,
+  },
+  {
+    label: '90 days',
+    value: 90,
+  },
+];
+
+const DEFAULT_RETENTION = 90;
+
+const StyledIcon = styled(Icon)`
+  margin: auto ${({ theme }) => theme.gridUnit * 2}px auto 0;
+`;
+
+const StyledSectionContainer = styled.div`
+  display: flex;
+  flex-direction: column;
+
+  .header-section {
+    display: flex;
+    flex: 0 0 auto;
+    align-items: center;
+    width: 100%;
+    padding: ${({ theme }) => theme.gridUnit * 4}px;
+    border-bottom: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
+  }
+
+  .column-section {
+    display: flex;
+    flex: 1 1 auto;
+
+    .column {
+      flex: 1 1 auto;
+      min-width: 33.33%;
+      padding: ${({ theme }) => theme.gridUnit * 4}px;
+
+      .async-select {
+        margin: 10px 0 20px;
+      }
+
+      &.condition {
+        border-right: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
+      }
+
+      &.message {
+        border-left: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
+      }
+    }
+  }
+
+  .inline-container {
+    display: flex;
+    flex-direction: row;
+    align-items: center;
+
+    > div {
+      flex: 1 1 auto;
+    }
+
+    &.add-margin {
+      margin-bottom: 5px;
+    }
+
+    .styled-input {
+      margin: 0 0 0 10px;
+
+      input {
+        flex: 0 0 auto;
+      }
+    }
+  }
+
+  .hide-dropdown {
+    display: none;
+  }
+`;
+
+const StyledSectionTitle = styled.div`
+  margin: ${({ theme }) => theme.gridUnit * 2}px auto
+    ${({ theme }) => theme.gridUnit * 4}px auto;
+`;
+
+const StyledSwitchContainer = styled.div`
+  display: flex;
+  align-items: center;
+  margin-top: 10px;
+
+  .switch-label {
+    margin-left: 10px;
+  }
+`;
+
+const StyledInputContainer = styled.div`
+  flex: 1 1 auto;
+  margin: ${({ theme }) => theme.gridUnit * 2}px;
+  margin-top: 0;
+
+  .required {
+    margin-left: ${({ theme }) => theme.gridUnit / 2}px;
+    color: ${({ theme }) => theme.colors.error.base};
+  }
+
+  .input-container {
+    display: flex;
+    align-items: center;
+
+    label {
+      display: flex;
+      margin-right: ${({ theme }) => theme.gridUnit * 2}px;
+    }
+
+    i {
+      margin: 0 ${({ theme }) => theme.gridUnit}px;
+    }
+  }
+
+  input,
+  textarea,
+  .Select,
+  .ant-select {
+    flex: 1 1 auto;
+  }
+
+  textarea {
+    height: 160px;
+    resize: none;
+  }
+
+  input::placeholder,
+  textarea::placeholder,
+  .Select__placeholder {
+    color: ${({ theme }) => theme.colors.grayscale.light1};
+  }
+
+  textarea,
+  input[type='text'],
+  input[type='number'],
+  .Select__control,
+  .ant-select-single .ant-select-selector {
+    padding: ${({ theme }) => theme.gridUnit * 1.5}px
+      ${({ theme }) => theme.gridUnit * 2}px;
+    border-style: none;
+    border: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
+    border-radius: ${({ theme }) => theme.gridUnit}px;
+
+    &[name='description'] {
+      flex: 1 1 auto;
+    }
+  }
+
+  .Select__control {
+    padding: 2px 0;
+  }
+
+  .input-label {
+    margin-left: 10px;
+  }
+`;
+
+// Notification Method components
+const StyledNotificationAddButton = styled.div`
+  color: ${({ theme }) => theme.colors.primary.dark1};
+  cursor: pointer;
+
+  i {
+    margin-right: ${({ theme }) => theme.gridUnit * 2}px;
+  }
+
+  &.disabled {
+    color: ${({ theme }) => theme.colors.grayscale.light1};
+    cursor: default;
+  }
+`;
+
+const StyledNotificationMethod = styled.div`
+  margin-bottom: 10px;
+
+  .input-container {
+    textarea {
+      height: auto;
+    }
+  }
+
+  .inline-container {
+    margin-bottom: 10px;
+
+    .input-container {
+      margin-left: 10px;
+    }
+
+    > div {
+      margin: 0;
+    }
+
+    .delete-button {
+      margin-left: 10px;
+      padding-top: 3px;
+    }
+  }
+`;
+
+type NotificationAddStatus = 'active' | 'disabled' | 'hidden';
+
+interface NotificationMethodAddProps {
+  status: NotificationAddStatus;
+  onClick: () => void;
+}
+
+const NotificationMethodAdd: FunctionComponent<NotificationMethodAddProps> = ({
+  status = 'active',
+  onClick,
+}) => {
+  if (status === 'hidden') {
+    return null;
+  }
+
+  const checkStatus = () => {
+    if (status !== 'disabled') {
+      onClick();
+    }
+  };
+
+  return (
+    <StyledNotificationAddButton className={status} onClick={checkStatus}>
+      <i className="fa fa-plus" />{' '}
+      {status === 'active'
+        ? t('Add notification method')
+        : t('Add delivery method')}
+    </StyledNotificationAddButton>
+  );
+};
+
+type NotificationMethod = 'Email' | 'Slack';
+
+type NotificationSetting = {
+  method?: NotificationMethod;
+  recipients: string;
+  options: NotificationMethod[];
+};
+
+interface NotificationMethodProps {
+  setting?: NotificationSetting | null;
+  index: number;
+  onUpdate?: (index: number, updatedSetting: NotificationSetting) => void;
+  onRemove?: (index: number) => void;
+}
+
+const NotificationMethod: FunctionComponent<NotificationMethodProps> = ({
+  setting = null,
+  index,
+  onUpdate,
+  onRemove,
+}) => {
+  const { method, recipients, options } = setting || {};
+  const [recipientValue, setRecipientValue] = useState<string>(
+    recipients || '',
+  );
+
+  if (!setting) {
+    return null;
+  }
+
+  const onMethodChange = (method: NotificationMethod) => {
+    // Since we're swapping the method, reset the recipients
+    setRecipientValue('');
+
+    if (onUpdate) {
+      const updatedSetting = {
+        ...setting,
+        method,
+        recipients: '',
+      };
+
+      onUpdate(index, updatedSetting);
+    }
+  };
+
+  const onRecipientsChange = (
+    event: React.ChangeEvent<HTMLTextAreaElement>,
+  ) => {
+    const { target } = event;
+
+    setRecipientValue(target.value);
+
+    if (onUpdate) {
+      const updatedSetting = {
+        ...setting,
+        recipients: target.value,
+      };
+
+      onUpdate(index, updatedSetting);
+    }
+  };
+
+  // Set recipients
+  if (!!recipients && recipientValue !== recipients) {
+    setRecipientValue(recipients);
+  }
+
+  const methodOptions = (options || []).map((method: NotificationMethod) => {
+    return (
+      <Select.Option key={method} value={method}>
+        {method}
+      </Select.Option>
+    );
+  });
+
+  return (
+    <StyledNotificationMethod>
+      <div className="inline-container">
+        <StyledInputContainer>
+          <div className="input-container">
+            <Select
+              onChange={onMethodChange}
+              placeholder="Select Delivery Method"
+              defaultValue={method}
+              value={method}
+            >
+              {methodOptions}
+            </Select>
+          </div>
+        </StyledInputContainer>
+        {method !== undefined && !!onRemove ? (
+          <span
+            role="button"
+            tabIndex={0}
+            className="delete-button"
+            onClick={() => onRemove(index)}
+          >
+            <Icon name="trash" />
+          </span>
+        ) : null}
+      </div>
+      {method !== undefined ? (
+        <StyledInputContainer>
+          <div className="control-label">{t(method)}</div>
+          <div className="input-container">
+            <textarea
+              name="recipients"
+              value={recipientValue}
+              onChange={onRecipientsChange}
+            />
+          </div>
+        </StyledInputContainer>
+      ) : null}
+    </StyledNotificationMethod>
+  );
+};
+
+const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
+  addDangerToast,
+  onAdd,
+  onHide,
+  show,
+  alert = null,
+  isReport = false,
+}) => {
+  const [disableSave, setDisableSave] = useState<boolean>(true);
+  const [currentAlert, setCurrentAlert] = useState<AlertObject | null>();
+  const [isHidden, setIsHidden] = useState<boolean>(true);
+  const [contentType, setContentType] = useState<string>(
+    alert && alert.chart ? 'chart' : 'dashboard',
+  ); // Maybe make this always default to dashboard and don't update until alert is fetched
+  const [scheduleFormat, setScheduleFormat] = useState<string>(
+    'dropdown-format',
+  );
+
+  // Dropdown options
+  const [sourceOptions, setSourceOptions] = useState<MetaObject[]>([]);
+  const [dashboardOptions, setDashboardOptions] = useState<MetaObject[]>([]);
+  const [chartOptions, setChartOptions] = useState<MetaObject[]>([]);
+
+  const isEditMode = alert !== null;
+
+  // TODO: need to set status/settings list based on alert's notification settings
+  const [notificationAddState, setNotificationAddState] = useState<
+    NotificationAddStatus
+  >('active');
+  const [notificationSettings, setNotificationSettings] = useState<
+    NotificationSetting[]
+  >([]);
+
+  const onNotificationAdd = () => {
+    const settings: NotificationSetting[] = notificationSettings.slice();
+
+    settings.push({
+      recipients: '',
+      options: NOTIFICATION_METHODS, // Need better logic for this
+    });
+
+    setNotificationSettings(settings);
+    setNotificationAddState(
+      settings.length === NOTIFICATION_METHODS.length ? 'hidden' : 'disabled',
+    );
+  };
+
+  const updateNotificationSetting = (
+    index: number,
+    setting: NotificationSetting,
+  ) => {
+    const settings = notificationSettings.slice();
+
+    settings[index] = setting;
+    setNotificationSettings(settings);
+
+    if (setting.method !== undefined && notificationAddState !== 'hidden') {
+      setNotificationAddState('active');
+    }
+  };
+
+  const removeNotificationSetting = (index: number) => {
+    const settings = notificationSettings.slice();
+
+    settings.splice(index, 1);
+    setNotificationSettings(settings);
+    setNotificationAddState('active');
+  };
+
+  // Alert fetch logic
+  const {
+    state: { loading, resource },
+    fetchResource,
+    createResource,
+    updateResource,
+  } = useSingleViewResource<AlertObject>('report', t('report'), addDangerToast);
+
+  // Functions
+  const hide = () => {
+    setIsHidden(true);
+    onHide();
+  };
+
+  const onSave = () => {
+    // Notification Settings
+    const recipients: Recipient[] = [];
+
+    notificationSettings.forEach(setting => {
+      if (setting.method && setting.recipients.length) {
+        recipients.push({
+          recipient_config_json: {
+            target: setting.recipients,
+          },
+          type: setting.method,
+        });
+      }
+    });
+
+    const data: any = {
+      ...currentAlert,
+      chart: contentType === 'chart' ? currentAlert?.chart?.value : undefined,
+      dashboard:
+        contentType === 'dashboard'
+          ? currentAlert?.dashboard?.value
+          : undefined,
+      database: currentAlert?.database?.value,
+      owners: (currentAlert?.owners || []).map(
+        owner => (owner as MetaObject).value,
+      ),
+      recipients,
+    };
+
+    if (data.recipients && !data.recipients.length) {
+      delete data.recipients;
+    }
+
+    data.context_markdown = 'string';
+
+    if (isEditMode) {
+      // Edit
+      if (currentAlert && currentAlert.id) {
+        const update_id = currentAlert.id;
+
+        delete data.id;
+        delete data.created_by;
+        delete data.last_eval_dttm;
+        delete data.last_state;
+        delete data.last_value;
+        delete data.last_value_row_json;
+
+        updateResource(update_id, data).then(() => {
+          if (onAdd) {
+            onAdd();
+          }
+
+          hide();
+        });
+      }
+    } else if (currentAlert) {
+      // Create
+      createResource(data).then(response => {
+        if (onAdd) {
+          onAdd(response);
+        }
+
+        hide();
+      });
+    }
+  };
+
+  // Fetch data to populate form dropdowns
+  const loadOwnerOptions = (input = '') => {
+    const query = rison.encode({ filter: input });
+    return SupersetClient.get({
+      endpoint: `/api/v1/dashboard/related/owners?q=${query}`,
+    }).then(
+      response => {
+        return response.json.result.map((item: any) => ({
+          value: item.value,
+          label: item.text,
+        }));
+      },
+      badResponse => {
+        return [];
+      },
+    );
+  };
+
+  const loadSourceOptions = (input = '') => {
+    const query = rison.encode({ filter: input });
+    return SupersetClient.get({
+      endpoint: `/api/v1/dataset/related/database?q=${query}`,
+    }).then(
+      response => {
+        const list = response.json.result.map((item: any) => ({
+          value: item.value,
+          label: item.text,
+        }));
+
+        setSourceOptions(list);
+
+        // Find source if current alert has one set
+        if (
+          currentAlert &&
+          currentAlert.database &&
+          !currentAlert.database.label
+        ) {
+          updateAlertState('database', getSourceData());
+        }
+
+        return list;
+      },
+      badResponse => {
+        return [];
+      },
+    );
+  };
+
+  const getSourceData = (db?: MetaObject) => {
+    const database = db || currentAlert?.database;
+
+    if (!database || database.label) {
+      return null;
+    }
+
+    let result;
+
+    // Cycle through source options to find the selected option
+    sourceOptions.forEach(source => {
+      if (source.value === database.value || source.value === database.id) {
+        result = source;
+      }
+    });
+
+    return result;
+  };
+
+  const loadDashboardOptions = (input = '') => {
+    const query = rison.encode({ filter: input });
+    return SupersetClient.get({
+      endpoint: `/api/v1/dashboard?q=${query}`,
+    }).then(
+      response => {
+        const list = response.json.result.map((item: any) => ({
+          value: item.id,
+          label: item.dashboard_title,
+        }));
+
+        setDashboardOptions(list);
+
+        // Find source if current alert has one set
+        if (
+          currentAlert &&
+          currentAlert.dashboard &&
+          !currentAlert.dashboard.label
+        ) {
+          updateAlertState('dashboard', getDashboardData());
+        }
+
+        return list;
+      },
+      badResponse => {
+        return [];
+      },
+    );
+  };
+
+  const getDashboardData = (db?: MetaObject) => {
+    const dashboard = db || currentAlert?.dashboard;
+
+    if (!dashboard || dashboard.label) {
+      return null;
+    }
+
+    let result;
+
+    // Cycle through dashboard options to find the selected option
+    dashboardOptions.forEach(dash => {
+      if (dash.value === dashboard.value || dash.value === dashboard.id) {
+        result = dash;
+      }
+    });
+
+    return result;
+  };
+
+  const loadChartOptions = (input = '') => {
+    const query = rison.encode({ filter: input });
+    return SupersetClient.get({
+      endpoint: `/api/v1/chart?q=${query}`,
+    }).then(
+      response => {
+        const list = response.json.result.map((item: any) => ({
+          value: item.id,
+          label: item.slice_name,
+        }));
+
+        setChartOptions(list);
+
+        // Find source if current alert has one set
+        if (currentAlert && currentAlert.chart && !currentAlert.chart.label) {
+          updateAlertState('chart', getChartData());
+        }
+
+        return list;
+      },
+      badResponse => {
+        return [];
+      },
+    );
+  };
+
+  const getChartData = (chartData?: MetaObject) => {
+    const chart = chartData || currentAlert?.chart;
+
+    if (!chart || chart.label) {
+      return null;
+    }
+
+    let result;
+
+    // Cycle through chart options to find the selected option
+    chartOptions.forEach(slice => {
+      if (slice.value === chart.value || slice.value === chart.id) {
+        result = slice;
+      }
+    });
+
+    return result;
+  };
+
+  // Updating alert/report state
+  const updateAlertState = (name: string, value: any) => {
+    const data = {
+      ...currentAlert,
+    };
+
+    data[name] = value;
+    setCurrentAlert(data);
+  };
+
+  // Handle input/textarea updates
+  const onTextChange = (
+    event:
+      | React.ChangeEvent<HTMLTextAreaElement>
+      | React.ChangeEvent<HTMLInputElement>,
+  ) => {
+    const { target } = event;
+
+    updateAlertState(target.name, target.value);
+  };
+
+  const onOwnersChange = (value: Array<Owner>) => {
+    updateAlertState('owners', value || []);
+  };
+
+  const onSourceChange = (value: Array<Owner>) => {
+    updateAlertState('database', value || []);
+  };
+
+  const onDashboardChange = (dashboard: SelectValue) => {
+    updateAlertState('dashboard', dashboard || undefined);
+  };
+
+  const onChartChange = (chart: SelectValue) => {
+    updateAlertState('chart', chart || undefined);
+  };
+
+  const onActiveSwitch = (checked: boolean) => {
+    updateAlertState('active', checked);
+  };
+
+  const onConditionChange = (operation: Operator) => {
+    const config = {
+      operation,
+      threshold: currentAlert
+        ? currentAlert.validator_config_json?.threshold
+        : undefined,
+    };
+
+    updateAlertState('validator_config_json', config);
+  };
+
+  const onThresholdChange = (event: React.ChangeEvent<HTMLInputElement>) => {
+    const { target } = event;
+
+    const config = {
+      operation: currentAlert
+        ? currentAlert.validator_config_json?.operation
+        : undefined,
+      threshold: target.value,
+    };
+
+    updateAlertState('validator_config_json', config);
+  };
+
+  const onScheduleFormatChange = (event: any) => {
+    const { target } = event;
+
+    setScheduleFormat(target.value);
+  };
+
+  const onLogRetentionChange = (retention: number) => {
+    updateAlertState('log_retention', retention);
+  };
+
+  const onContentTypeChange = (event: any) => {
+    const { target } = event;
+
+    setContentType(target.value);
+  };
+
+  // Make sure notification settings has the required info
+  const checkNotificationSettings = () => {
+    if (!notificationSettings.length) {
+      return false;
+    }
+
+    let hasInfo = false;
+
+    notificationSettings.forEach(setting => {
+      if (!!setting.method && setting.recipients?.length) {
+        hasInfo = true;
+      }
+    });
+
+    return hasInfo;
+  };
+
+  const validate = () => {
+    if (
+      currentAlert &&
+      currentAlert.name?.length &&
+      currentAlert.owners?.length &&
+      currentAlert.crontab?.length &&
+      ((contentType === 'dashboard' && !!currentAlert.dashboard) ||
+        (contentType === 'chart' && !!currentAlert.chart)) &&
+      checkNotificationSettings()
+    ) {
+      if (isReport) {
+        setDisableSave(false);
+      } else if (
+        !!currentAlert.database &&
+        currentAlert.sql?.length &&
+        !!currentAlert.validator_config_json?.operation &&
+        currentAlert.validator_config_json?.threshold !== undefined
+      ) {
+        setDisableSave(false);
+      } else {
+        setDisableSave(true);
+      }
+    } else {
+      setDisableSave(true);
+    }
+  };
+
+  // Initialize
+  if (
+    isEditMode &&
+    (!currentAlert ||
+      !currentAlert.id ||
+      (alert && alert.id !== currentAlert.id) ||
+      (isHidden && show))
+  ) {
+    if (alert && alert.id !== null && !loading) {
+      const id = alert.id || 0;
+
+      fetchResource(id).then(() => {
+        if (resource) {
+          setContentType(resource.chart ? 'chart' : 'dashboard');
+
+          // Add notification settings
+          const settings = (resource.recipients || []).map(setting => ({
+            method: setting.type as NotificationMethod,
+            // @ts-ignore: Type not assignable
+            recipients: (JSON.parse(setting.recipient_config_json) || {})
+              .target,
+            options: NOTIFICATION_METHODS as NotificationMethod[], // Need better logic for this
+          }));
+
+          setNotificationSettings(settings);
+
+          setCurrentAlert({
+            ...resource,
+            chart: resource.chart
+              ? getChartData(resource.chart) || { value: resource.chart.id }
+              : undefined,
+            dashboard: resource.dashboard
+              ? getDashboardData(resource.dashboard) || {
+                  value: resource.dashboard.id,
+                }
+              : undefined,
+            database: resource.database
+              ? getSourceData(resource.database) || {
+                  value: resource.database.id,
+                }
+              : undefined,
+            // log_retention: { value: resource.log_retention },
+            owners: (resource.owners || []).map(owner => ({
+              value: owner.id,
+              label: `${(owner as Owner).first_name} ${
+                (owner as Owner).last_name
+              }`,
+            })),
+            // @ts-ignore: Type not assignable
+            validator_config_json: JSON.parse(resource.validator_config_json),

Review comment:
       I think the issue here if more that `resource` is expecting `validator_config_json` to be an object, not a string. I considered adding `string` to the type definition but it ended up creating more errors/checks I would need to handle, so ignoring this one case with the stringified response felt like less work in the long run.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org