import _ from "lodash" import React, { useState } from "react" import $ from "jquery" import moment from "moment" import ezlocalize, { LocalizeString } from "ez-localize" import ResponseAnswersComponent from "./ResponseAnswersComponent" import ResponseArchivesComponent from "./ResponseArchivesComponent" import ModalPopupComponent from "@mwater/react-library/lib/ModalPopupComponent" import { Form } from "./form" import { Response, ResponseEvent } from "./response" import { Schema } from "@mwater/expressions" import { FormContext, InnerFormContext } from "./formContext" import LocationQuestionAdminRegionComponent from "./LocationQuestionAdminRegionComponent" export interface ResponseDisplayComponentProps { form: Form response: Response /** Schema including the form */ schema: Schema formCtx: FormContext apiUrl?: string /** Defaults to english */ locale?: string /** Current login (contains user, username, groups) */ login?: { client: string, user: string, username: string, groups: string[] } /** True to display complete history always */ forceCompleteHistory?: boolean /** Controls whether complete history is shown. Uncontrolled if not present */ showCompleteHistory?: boolean /** Called when user shows or hides complete history */ onShowCompleteHistoryChange?: (show: boolean) => void /** True to hide the show/hide history links (e.g. when printing) */ hideHistoryControls?: boolean /** If present, allows editing of draft name */ onEditDraftName?: (draftName: string) => void } interface ResponseDisplayComponentState { innerFormCtx: InnerFormContext T: LocalizeString eventsUsernames: { [key: string]: { username: string } } | null loadingUsernames: boolean showCompleteHistory: any history?: Response[] showArchive: boolean showPrevAnswers: boolean loadingHistory: boolean } // Static view of a response export default class ResponseDisplayComponent extends React.Component< ResponseDisplayComponentProps, ResponseDisplayComponentState > { constructor(props: ResponseDisplayComponentProps) { super(props) this.state = { eventsUsernames: null, loadingUsernames: false, showCompleteHistory: this.props.forceCompleteHistory || false, T: this.createLocalizer(this.props.form.design, this.props.locale), loadingHistory: false, showArchive: false, showPrevAnswers: false, innerFormCtx: { ...this.props.formCtx, locale: this.props.locale, T: this.createLocalizer(this.props.form.design, this.props.locale) } } } componentDidMount() { this.loadEventUsernames(this.props.response.events || []) this.loadHistory(this.props) } componentDidUpdate(prevProps: ResponseDisplayComponentProps) { if (this.props.form.design !== prevProps.form.design || this.props.locale !== prevProps.locale) { this.setState({ T: this.createLocalizer(this.props.form.design, this.props.locale) }) } if (!_.isEqual(this.props.response._id, prevProps.response._id)) { // Reset comparison state immediately so stale history from the previous response is never shown. this.setState({ history: undefined, showPrevAnswers: false, showArchive: false }) this.loadHistory(this.props) } if (!_.isEqual(this.props.response.events, prevProps.response.events)) { this.loadEventUsernames(this.props.response.events || []) } } async loadHistory(props: ResponseDisplayComponentProps) { const requestedId = props.response._id const url = props.apiUrl + "archives/responses/" + requestedId + "?client=" + (props.login?.client || "") this.setState({ loadingHistory: true }) try { const response = await fetch(url) // History arrives in descending order of _rev const history: Response[] = await response.json() if (this.props.response._id !== requestedId) { return } // Get only ones since first submission const index = _.findLastIndex(history, rev => ["pending", "final"].includes(rev.status)) const slicedHistory = history.slice(0, index + 1) // Remove history where there was no change to data const compactHistory = [] for (let i = 0; i < slicedHistory.length; i++) { const entry = slicedHistory[i] const prevEntry = i === 0 ? this.props.response : slicedHistory[i - 1] if (!_.isEqual(entry.data, prevEntry.data)) { compactHistory.push(entry) } } this.setState({ loadingHistory: false, history: compactHistory }) } catch (error: any) { if (this.props.response._id !== requestedId) { return } this.setState({ loadingHistory: false, history: undefined }) } } // Load user names related to events async loadEventUsernames(events: ResponseEvent[]) { events = this.props.response.events || [] const byArray = _.compact(_.pluck(events, "by")) if (byArray.length > 0 && this.props.apiUrl != null) { const filter = { _id: { $in: byArray } } const url = this.props.apiUrl + "users_public_data?filter=" + JSON.stringify(filter) this.setState({ loadingUsernames: true }) try { const response = await fetch(url) const rows: any = await response.json() // eventsUsernames is an object with a key for each _id value this.setState({ loadingUsernames: false, eventsUsernames: _.indexBy(rows, "_id") }) } catch (error: any) { this.setState({ loadingUsernames: false, eventsUsernames: null }) } } } // Creates a localizer for the form design createLocalizer(design: any, locale: any) { // Create localizer const localizedStrings = design.localizedStrings || [] const localizerData = { locales: design.locales, strings: localizedStrings } const { T } = new ezlocalize.Localizer(localizerData, locale) return T } isShowingCompleteHistory() { return this.props.showCompleteHistory ?? this.state.showCompleteHistory } handleHideHistory = () => { this.setState({ showCompleteHistory: false }) this.props.onShowCompleteHistoryChange?.(false) } handleShowHistory = () => { this.setState({ showCompleteHistory: true }) this.props.onShowCompleteHistoryChange?.(true) } renderEvent(ev: any) { if (this.state.eventsUsernames == null) { return null } const eventType = (() => { switch (ev.type) { case "draft": return this.state.T("Drafted") case "submit": return this.state.T("Submitted") case "approve": return this.state.T("Approved") case "reject": return this.state.T("Rejected") case "edit": return this.state.T("Edited") } return "???" })() return (
{eventType} {this.state.T("by")} {ev.by ? this.state.eventsUsernames[ev.by]?.username : "Anonymous"} {this.state.T("on")}{" "} {moment(ev.on).format("lll")} {ev.message ? [": ", {ev.message}] : undefined} {ev.override ? {this.state.T("Admin Override")} : undefined}
) } // History of events renderHistory() { if (this.state.loadingUsernames) { return
} const contents = [] const events = this.props.response.events || [] const showCompleteHistory = this.isShowingCompleteHistory() if (showCompleteHistory) { for (let ev of _.initial(events)) { contents.push(this.renderEvent(ev)) } } const lastEvent = _.last(events) if (lastEvent) { contents.push(this.renderEvent(lastEvent)) } if (events.length > 1 && !this.props.forceCompleteHistory && !this.props.hideHistoryControls) { if (showCompleteHistory) { contents.push(
{this.state.T("Hide History")}
) contents.push(
this.setState({ showArchive: true })}> {this.state.T("Show Complete History of Changes")}
) } else { contents.push(
{this.state.T("Show History")}
) } } return
{contents}
} renderStatus() { const status = (() => { switch (this.props.response.status) { case "draft": return this.state.T("Draft") case "rejected": return this.state.T("Rejected") case "pending": return this.state.T("Pending") case "final": return this.state.T("Final") } })() return
{this.state.T("Status")}: {status}
} renderArchives() { if (!this.state.history || !this.state.showArchive) { return null } return ( this.setState({ showArchive: false })} > ) } // Header which includes basics renderHeader() { return (
{this.state.T("User")}: {this.props.response.username || "Anonymous"}
{this.state.T("Response Id")}: {this.props.response.code}
{this.props.response.deployment && this.props.form.deployments ? (
{this.state.T("Deployment")}: {this.props.form.deployments.find(d => d._id === this.props.response.deployment)?.name || this.state.T("Unknown")}
) : undefined} {this.props.response && this.props.response.submittedOn ? (
{this.state.T("Submitted")}: {moment(this.props.response.submittedOn).format("lll")}
) : undefined} {this.props.response.ipAddress ? (
{this.state.T("IP Address")}: {this.props.response.ipAddress}
) : undefined} {this.props.response.status == "draft" || this.props.response.draftName ? (
{this.state.T("Draft Name")}:
) : undefined} {this.renderStatus()} {this.renderHistory()} {this.renderArchives()}
) } renderAdminRegionForLocation = (location: any) => { if (location) return return null } render() { return (
{this.renderHeader()} 0 ? _.last(this.state.history).data : undefined} showPrevAnswers={this.state.history != null && this.state.showPrevAnswers} highlightChanges={this.state.showPrevAnswers} showChangedLink={this.state.history != null} renderAdminRegionForLocation={this.renderAdminRegionForLocation} onChangedLinkClick={() => { return this.setState({ showPrevAnswers: !this.state.showPrevAnswers }) }} onCompleteHistoryLinkClick={() => { return this.setState({ showArchive: true }) }} />
) } } function DraftNameComponent(props: { draftName: string | undefined, onEdit?: (newName: string) => void }) { const [isHovered, setIsHovered] = useState(false) const handleEdit = () => { const newName = window.prompt("Enter draft name:", props.draftName || "") if (newName !== null && props.onEdit) { props.onEdit(newName) setIsHovered(false) } } return ( setIsHovered(true)} onMouseLeave={() => setIsHovered(false)} onClick={(e) => { if (props.onEdit) { e.preventDefault() handleEdit() } }} style={{ cursor: props.onEdit ? "pointer" : "default" }} > {props.draftName ? props.draftName : —} {props.onEdit && isHovered && ( )} ) }