config#UPLOAD_CONTACTS_SAMPLE TypeScript Examples

The following examples show how to use config#UPLOAD_CONTACTS_SAMPLE. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UploadContactsDialog.tsx    From glific-frontend with GNU Affero General Public License v3.0 4 votes vote down vote up
UploadContactsDialog: React.FC<UploadContactsDialogProps> = ({
  organizationDetails,
  setDialog,
}) => {
  const [error, setError] = useState<any>(false);
  const [csvContent, setCsvContent] = useState<String | null | ArrayBuffer>('');
  const [uploadingContacts, setUploadingContacts] = useState(false);
  const [fileName, setFileName] = useState<string>('');

  const { t } = useTranslation();
  const [collection] = useState();
  const [optedIn] = useState(false);

  const [getCollections, { data: collections, loading }] = useLazyQuery(
    GET_ORGANIZATION_COLLECTIONS
  );

  useEffect(() => {
    if (organizationDetails.id) {
      getCollections({
        variables: {
          organizationGroupsId: organizationDetails.id,
        },
      });
    }
  }, [organizationDetails]);

  const [importContacts] = useMutation(IMPORT_CONTACTS, {
    onCompleted: (data: any) => {
      if (data.errors) {
        setNotification(data.errors[0].message, 'warning');
      } else {
        setUploadingContacts(false);
        setNotification(t('Contacts have been uploaded'));
      }
      setDialog(false);
    },
    onError: (errors) => {
      setDialog(false);
      setNotification(errors.message, 'warning');
      setUploadingContacts(false);
    },
  });

  const addAttachment = (event: any) => {
    const media = event.target.files[0];
    const reader = new FileReader();
    reader.readAsText(media);

    reader.onload = () => {
      const mediaName = media.name;
      const extension = mediaName.slice((Math.max(0, mediaName.lastIndexOf('.')) || Infinity) + 1);
      if (extension !== 'csv') {
        setError(true);
      } else {
        const shortenedName = mediaName.length > 15 ? `${mediaName.slice(0, 15)}...` : mediaName;
        setFileName(shortenedName);
        setCsvContent(reader.result);
      }
    };
  };

  const uploadContacts = (details: any) => {
    importContacts({
      variables: {
        type: 'DATA',
        data: csvContent,
        groupLabel: details.collection.label,
        importContactsId: organizationDetails.id,
      },
    });
  };

  if (loading || !collections) {
    return <Loading />;
  }

  const validationSchema = Yup.object().shape({
    collection: Yup.object().nullable().required(t('Collection is required')),
  });

  const formFieldItems: any = [
    {
      component: AutoComplete,
      name: 'collection',
      placeholder: t('Select collection'),
      options: collections.organizationGroups,
      multiple: false,
      optionLabel: 'label',
      textFieldProps: {
        label: t('Collection'),
        variant: 'outlined',
      },
    },
    {
      component: Checkbox,
      name: 'optedIn',
      title: t('Are these contacts opted in?'),
      darkCheckbox: true,
    },
  ];

  const form = (
    <Formik
      enableReinitialize
      validationSchema={validationSchema}
      initialValues={{ collection, optedIn }}
      onSubmit={(itemData) => {
        uploadContacts(itemData);
        setUploadingContacts(true);
      }}
    >
      {({ submitForm }) => (
        <Form data-testid="formLayout">
          <DialogBox
            titleAlign="left"
            title={`${t('Upload contacts')}: ${organizationDetails.name}`}
            handleOk={() => {
              submitForm();
            }}
            handleCancel={() => {
              setDialog(false);
            }}
            skipCancel
            buttonOkLoading={uploadingContacts}
            buttonOk={t('Upload')}
            alignButtons="left"
          >
            <div className={styles.Fields}>
              {formFieldItems.map((field: any) => (
                <Field {...field} key={field.name} />
              ))}
            </div>

            <div className={styles.UploadContainer}>
              <label
                className={`${styles.UploadEnabled} ${fileName ? styles.Uploaded : ''}`}
                htmlFor="uploadFile"
              >
                <span>
                  {fileName !== '' ? (
                    <>
                      <span>{fileName}</span>
                      <CrossIcon
                        className={styles.CrossIcon}
                        onClick={(event) => {
                          event.preventDefault();
                          setFileName('');
                        }}
                      />
                    </>
                  ) : (
                    <>
                      <UploadIcon className={styles.UploadIcon} />
                      Select .csv
                    </>
                  )}

                  <input
                    type="file"
                    id="uploadFile"
                    disabled={fileName !== ''}
                    data-testid="uploadFile"
                    onChange={(event) => {
                      setError(false);
                      addAttachment(event);
                    }}
                  />
                </span>
              </label>
            </div>
            <div className={styles.Sample}>
              <a href={UPLOAD_CONTACTS_SAMPLE}>Download Sample</a>
            </div>

            {error && (
              <div className={styles.Error}>
                1. Please make sure the file format matches the sample
              </div>
            )}
          </DialogBox>
        </Form>
      )}
    </Formik>
  );

  return form;
}