// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Import React and Amplify packages import React from 'react'; import { API, graphqlOperation, I18n } from 'aws-amplify'; import { GraphQLResult } from '@aws-amplify/api-graphql'; import { Logger } from '@aws-amplify/core'; // Import React Bootstrap components import Container from 'react-bootstrap/Container'; import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import Breadcrumb from 'react-bootstrap/Breadcrumb'; import Button from 'react-bootstrap/Button'; import Form from 'react-bootstrap/Form'; import Card from 'react-bootstrap/Card'; import Jumbotron from 'react-bootstrap/Jumbotron'; import Table from 'react-bootstrap/Table'; import ProgressBar from 'react-bootstrap/ProgressBar'; import Alert from 'react-bootstrap/Alert'; import Modal from 'react-bootstrap/Modal'; // Import graphql import { createSite } from '../graphql/mutations'; // Import custom setting import { LOGGING_LEVEL, sendMetrics, validateGeneralInput, sortByName, getInputFormValidationClassName, makeAllVisible, makeVisibleBySearchKeyword } from '../util/CustomUtil'; import GraphQLCommon from '../util/GraphQLCommon'; import { IGeneralQueryData } from '../components/Interfaces'; import { ModalType, SortBy } from '../components/Enums'; import EmptyRow from '../components/EmptyRow'; /** * Properties Interface * @interface IProps */ interface IProps { history?: any; handleNotification: Function; } /** * State Interface * @interface IState */ interface IState { title: string; sites: IGeneralQueryData[]; isLoading: boolean; searchKeyword: string; sort: SortBy; error: string; siteId: string; siteName: string; siteDescription: string; modalType: ModalType; modalTitle: string; showModal: boolean; isModalProcessing: boolean; isSiteNameValid: boolean; isSiteDescriptionValid: boolean; } // Logging const LOGGER = new Logger('Site', LOGGING_LEVEL); /** * The site page * @class Site */ class Site extends React.Component { // GraphQL common class private graphQlCommon: GraphQLCommon; constructor(props: Readonly) { super(props); this.state = { title: I18n.get('text.sites'), sites: [], isLoading: false, searchKeyword: '', sort: SortBy.Asc, error: '', siteId: '', siteName: '', siteDescription: '', modalType: ModalType.None, modalTitle: '', showModal: false, isModalProcessing: false, isSiteNameValid: false, isSiteDescriptionValid: false }; this.graphQlCommon = new GraphQLCommon(); this.deleteSite = this.deleteSite.bind(this); this.addSite = this.addSite.bind(this); this.openModal = this.openModal.bind(this); this.handleSearchKeywordChange = this.handleSearchKeywordChange.bind(this); this.handleSort = this.handleSort.bind(this); this.handleSiteNameChange = this.handleSiteNameChange.bind(this); this.handleSiteDescriptionChange = this.handleSiteDescriptionChange.bind(this); this.handleModalClose = this.handleModalClose.bind(this); } /** * React componentDidMount function */ async componentDidMount() { await this.getSites(); } /** * Get sites. */ async getSites() { this.setState({ isLoading: true, error: '' }); try { const sites: IGeneralQueryData[] = await this.graphQlCommon.listSites(); // Make all sites visible. makeAllVisible(sites); // Sorts initially sites.sort((a, b) => a.name.localeCompare(b.name)); this.setState({ sites, title: `${I18n.get('text.sites')} (${sites.length})` }); } catch (error) { LOGGER.error('Error while getting sites', error); this.setState({ error: I18n.get('error.get.sites') }); } this.setState({ isLoading: false }); } /** * Delete a site. */ async deleteSite() { this.setState({ isModalProcessing: true }); try { // This will delete every area, process, station, event, and device belonged to the site as well. const { siteId } = this.state; await this.graphQlCommon.deleteSite(siteId); const updatedSites = this.state.sites.filter(site => site.id !== siteId); this.props.handleNotification(I18n.get('info.delete.site'), 'success', 5); this.setState({ sites: updatedSites, title: `${I18n.get('text.sites')} (${updatedSites.length})`, siteId: '', siteName: '', isModalProcessing: false, showModal: false, modalTitle: '', modalType: ModalType.None }); } catch (error) { let message = I18n.get('error.delete.site'); const castError = error as any; if (castError.errors) { const { errorType } = castError.errors[0]; if (errorType === 'Unauthorized') { message = I18n.get('error.not.authorized'); } } LOGGER.error('Error while deleting site', castError); this.props.handleNotification(message, 'error', 5); this.setState({ isModalProcessing: false }); } } /** * Register a site. */ async addSite() { this.setState({ isModalProcessing: true }); try { // Graphql operation to register site const { sites, siteName, siteDescription, searchKeyword, sort } = this.state; const input = { name: siteName, description: siteDescription }; const response = await API.graphql(graphqlOperation(createSite, input)) as GraphQLResult; const data: any = response.data; let newSite: IGeneralQueryData = data.createSite; newSite.visible = searchKeyword === '' || newSite.name.toLowerCase().includes(searchKeyword.toLowerCase()); const newSites = [...sites, newSite]; this.setState({ sites: sortByName(newSites, sort, 'name'), title: `${I18n.get('text.sites')} (${newSites.length})`, siteName: '', siteDescription: '', isModalProcessing: false, isSiteNameValid: false, isSiteDescriptionValid: false, showModal: false, modalTitle: '', modalType: ModalType.None }); this.props.handleNotification(I18n.get('info.add.site'), 'info', 5); await sendMetrics({ 'site': 1 }); } catch (error) { let message = I18n.get('error.create.site'); const castError = error as any; if (castError.errors) { const { errorType } = castError.errors[0]; if (errorType === 'Unauthorized') { message = I18n.get('error.not.authorized'); } else if (errorType === 'DataDuplicatedError') { message = I18n.get('error.duplicate.site.name'); } } LOGGER.error('Error while adding site', castError); this.props.handleNotification(message, 'error', 5); this.setState({ isModalProcessing: false }); } } /** * Open modal based on type input. * @param {ModalType} modalType - Modal type * @param {string | undefined} siteId - Site ID * @param {string | undefined} siteName - Site Name */ openModal(modalType: ModalType, siteId?: string, siteName?: string) { let modalTitle = ''; if (modalType === ModalType.Add) { modalTitle = I18n.get('text.site.registration'); } else if (modalType === ModalType.Delete) { modalTitle = I18n.get('text.delete.site'); } else { this.props.handleNotification(`${I18n.get('error.unsupported.modal.type')}: ${modalType}`, 'warning', 5); return; } this.setState({ modalType, modalTitle, siteId: siteId ? siteId : '', siteName: siteName ? siteName : '', showModal: true }); } /** * Handle the search keyword change to filter the site result. * @param {any} event - Event from the search keyword input */ handleSearchKeywordChange(event: any) { const searchKeyword = event.target.value; const { sites } = this.state; makeVisibleBySearchKeyword(sites, 'name', searchKeyword); this.setState({ sites, searchKeyword }); } /** * Handle sites sort by site name. * @param {any} event - Event from the sort by select */ handleSort(event: any) { const sort = event.target.value; const sites = sortByName(this.state.sites, sort, 'name'); this.setState({ sites, sort }); } /** * Handle modal close. */ handleModalClose() { this.setState({ siteId: '', siteName: '', siteDescription: '', isSiteNameValid: false, isSiteDescriptionValid: false, showModal: false }); } /** * Handle the site name change. * @param {any} event - Event from the site name input */ handleSiteNameChange(event: any) { const siteName = event.target.value; const isSiteNameValid = validateGeneralInput(siteName, 1, 40, '- _/#'); this.setState({ siteName, isSiteNameValid }); } /** * Handle the site description change. * @param {any} event - Event from the site description input */ handleSiteDescriptionChange(event: any) { const siteDescription = event.target.value; const isSiteDescriptionValid = validateGeneralInput(siteDescription, 1, 40, '- _/#'); this.setState({ siteDescription, isSiteDescriptionValid }); } /** * Render this page. */ render() { return (
{I18n.get('text.sites')}
{this.state.title}
{I18n.get('text.search.keyword')} {I18n.get('text.sort.by')}
{ this.state.sites.length === 0 && !this.state.isLoading &&

{I18n.get('text.no.site')}

} { this.state.sites.filter((site: IGeneralQueryData) => site.visible) .map((site: IGeneralQueryData) => { return ( {site.name}
{I18n.get('text.description')} {site.description}
); }) }
{ this.state.isLoading && } { this.state.error && {I18n.get('error')}:
{this.state.error}
}
{this.state.modalTitle} { this.state.modalType === ModalType.Add &&
{I18n.get('text.site.name')} * {`(${I18n.get('text.required')}) ${I18n.get('info.valid.general.input')}`} {I18n.get('text.site.description')} * {`(${I18n.get('text.required')}) ${I18n.get('info.valid.general.input')}`}
} { this.state.modalType === ModalType.Delete &&
{I18n.get('text.confirm.delete.site')}: {this.state.siteName}? {I18n.get('warning.delete.site')}
} { this.state.isModalProcessing && }
); } } export default Site;