import _ from "lodash" import React, { ReactElement, ReactNode, useEffect, useState } from "react" import * as formUtils from "./formUtils" import moment from "moment" import * as ui from "@mwater/react-library/lib/bootstrap" import VisibilityCalculator, { VisibilityStructure } from "./VisibilityCalculator" import { default as ResponseRow } from "./ResponseRow" import TextExprsComponent from "./TextExprsComponent" import ImageDisplayComponent from "./ImageDisplayComponent" import ImagePopupComponent from "./ImagePopupComponent" import RotationAwareImageComponent from "./RotationAwareImageComponent" import EntityDisplayComponent from "./EntityDisplayComponent" import AquagenxCBTDisplayComponent from "./answers/AquagenxCBTDisplayComponent" import { AdminRegionDisplayComponent } from "./answers/AdminRegionDisplayComponent" import { CascadingListDisplayComponent } from "./answers/CascadingListDisplayComponent" import { CascadingRefDisplayComponent } from "./answers/CascadingRefDisplayComponent" import { CalculationsDisplayComponent } from "./CalculationsDisplayComponent" import FileLinkComponent from "./FileLinkComponent" import { FileValue, Schema } from "@mwater/expressions" import { FormDesign, Choice, Question, DropdownQuestion, MulticheckQuestion, UnitsQuestion, SiteQuestion, EntityQuestion, LikertQuestion, RankedQuestion, Item, RosterMatrix, RosterGroup, BasicItem, MatrixColumn, MatrixColumnQuestion, AssetQuestion, LocationQuestion, MatrixColumnText, MatrixColumnCalculation, CascadingRefQuestion, CascadingListQuestion } from "./formDesign" import { Answer, AdminRegionAnswerValue, CascadingListAnswerValue, AssetAnswerValue, CascadingRefAnswerValue, CascadingRefsAnswerValue, LikertAnswerValue, MatrixAnswerValue, RankedAnswerValue, ResponseData, RosterData, RosterEntry, UnitsAnswerValue } from "./response" import { Image } from "./RotationAwareImageComponent" import { ImageManager, InnerFormContext } from "./formContext" import { LocalizeString } from "ez-localize" export interface ResponseAnswersComponentProps { formDesign: FormDesign data: ResponseData /** Schema of the */ schema: Schema /** Deployment id of the response */ deployment?: string /** True to hide empty answers */ hideEmptyAnswers?: boolean /** Defaults to english */ locale?: string /** Localizer to use */ T: LocalizeString /** Form context to use */ formCtx: InnerFormContext /** Optional factory for custom row contexts such as workflow events */ createResponseRow?: (data: ResponseData, rosterId?: string | null, rosterEntryIndex?: number) => ResponseRow /** Previous data */ prevData?: ResponseData showPrevAnswers?: boolean highlightChanges?: boolean hideUnchangedAnswers?: boolean showChangedLink?: boolean onChangedLinkClick?: any onCompleteHistoryLinkClick?: any hideCalculations?: boolean renderAdminRegionForLocation?: (location: any) => ReactElement | null | undefined } // Displays the answers of a response in a table export default function ResponseAnswersComponent(props: ResponseAnswersComponentProps) { const [error, setError] = useState(null) const [responseRow, setResponseRow] = useState(null) const [entityReloadKey, setEntityReloadKey] = useState(0) const [visibilityStructure, setVisibilityStructure] = useState(null) /** Open the standard entity view modal and refresh the summary if the entity was updated */ function handleViewEntity(entityType: string, entity: any) { props.formCtx.viewEntity?.(entityType, entity._id, () => { setEntityReloadKey((k) => k + 1) }) } function createResponseRow(data: ResponseData, rosterId?: string | null, rosterEntryIndex?: number) { if (props.createResponseRow) { return props.createResponseRow(data, rosterId, rosterEntryIndex) } return new ResponseRow({ responseData: data, formDesign: props.formDesign, getEntityById: props.formCtx.getEntityById, getEntityByCode: props.formCtx.getEntityByCode, getCustomTableRow: props.formCtx.getCustomTableRow, getAssetById: props.formCtx.getAssetById, getAdminRegion: props.formCtx.getAdminRegion, deployment: props.deployment, schema: props.schema, rosterId: rosterId || undefined, rosterEntryIndex }) } useEffect(() => { // Check if form design or data are different async function load() { setError(null) setResponseRow(null) setVisibilityStructure(null) const responseRow = createResponseRow(props.data) // Calculate visibility asynchronously const visibilityStructure = await new Promise((resolve, reject) => new VisibilityCalculator(props.formDesign, props.schema).createVisibilityStructure( props.data, responseRow, (error: any, visibilityStructure: any) => { if (error) { return reject(error) } else { return resolve(visibilityStructure) } } ) ) setResponseRow(responseRow) setVisibilityStructure(visibilityStructure) } load().catch(setError) }, [JSON.stringify(props.formDesign), JSON.stringify(props.data), props.deployment, props.schema, props.createResponseRow]) function handleLocationClick(location: any) { if (props.formCtx.displayMap) { props.formCtx.displayMap(location) } } function renderLocation(location: any, showAdminRegion = false) { if (location) { return
handleLocationClick(location)} style={{ cursor: "pointer" }}> {`${location.latitude}\u00B0 ${location.longitude}\u00B0`} {location.accuracy != null ? `(+/-) ${location.accuracy.toFixed(3)} m` : undefined} {location.method ? ` (${location.method})` : undefined} {showAdminRegion && props.renderAdminRegionForLocation ? props.renderAdminRegionForLocation(location) : undefined}
} return null } function renderAnswer(q: Question | MatrixColumnQuestion, answer: Answer | null): React.ReactNode { let label, specify if (!answer) { return null } // Handle alternates if (answer.alternate) { switch (answer.alternate) { case "na": return {props.T("Not Applicable")} case "dontknow": return {props.T("Don't Know")} } } if (answer.confidential != null) { return {props.T("Redacted")} } if (answer.value == null) { return null } switch (formUtils.getAnswerType(q)) { case "text": // Format as url if url if ( answer.value && typeof answer.value == "string" && answer.value.match( /^((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:,&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:,&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&,;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)$/ ) ) { // Open in system window if in cordova const target = (window as any).cordova != null ? "_system" : "_blank" return {answer.value} } return answer.value as string case "number": return "" + answer.value case "choice": var choice = _.findWhere((q as DropdownQuestion).choices, { id: answer.value }) if (choice) { label = formUtils.localizeString(choice.label, props.locale) if (answer.specify != null) { specify = answer.specify[answer.value as string] } else { specify = null } return
{label} {specify ? <>: {specify} : null}
} else { return {props.T("Invalid Choice")} } case "choices": return _.map(answer.value as string[], v => { choice = _.findWhere((q as MulticheckQuestion).choices, { id: v }) if (choice) { return
{formUtils.localizeString(choice.label, props.locale)} {answer.specify != null && answer.specify[v] ? <>: {answer.specify[v]} : null}
} else { return
{props.T("Invalid Choice")}
} }) case "date": // Depends on precision if ((answer.value as string).length <= 7) { // YYYY or YYYY-MM return
{answer.value as string}
} else if ((answer.value as string).length <= 10) { // Date return
{moment(answer.value as string).format("LL")}
} else { return
{moment(answer.value as string).format("LLL")}
} case "units": if ( answer.value && (answer.value as UnitsAnswerValue).quantity != null && (answer.value as UnitsAnswerValue).units != null ) { // Find units const units = _.findWhere((q as UnitsQuestion).units, { id: (answer.value as UnitsAnswerValue).units }) const valueStr = "" + (answer.value as UnitsAnswerValue).quantity const unitsStr = units ? formUtils.localizeString(units.label, props.locale) : props.T("(Invalid)") if ((q as UnitsQuestion).unitsPosition === "prefix") { return
{unitsStr} {valueStr}
} else { return
{valueStr} {unitsStr}
} } break case "boolean": if (answer.value) { return props.T("True") } else { return props.T("False") } case "location": return renderLocation(answer.value, (q as LocationQuestion).calculateAdminRegion) case "image": if (answer.value) { return } break case "images": return _.map(answer.value as Image[], img => { return }) case "file": if (answer.value) { const fileVal = answer.value as FileValue if (props.formCtx.fileManager) { return {fileVal.filename} } return {fileVal.filename} } break case "files": if (answer.value) { return (answer.value as FileValue[]).map((f) => (
{props.formCtx.fileManager ? {f.filename} : {f.filename}}
)) } break case "signature": if (answer.value) { return } break case "texts": return _.map(answer.value as string[], txt => { return
{txt}
}) case "site": var code: any = answer.value // TODO Eventually always go to code parameter. Legacy responses used code directly as value. if (_.isObject(code)) { ; ({ code } = code) } // Convert to new entity type var siteType = ((q as SiteQuestion).siteTypes ? (q as SiteQuestion).siteTypes![0] : undefined) || "water_point" // Site column question have siteType (TODO: remove this, as this does not get called for columns) if ((q as any)._type === "SiteColumnQuestion") { siteType = (q as any).siteType || "water_point" } var entityType = siteType.toLowerCase().replace(new RegExp(" ", "g"), "_") return handleViewEntity(entityType, entity) : undefined} T={props.T} /> case "entity": return handleViewEntity((q as EntityQuestion).entityType, entity) : undefined} T={props.T} /> case "admin_region": return case "items_choices": for (let item of (q as LikertQuestion).items) { const choiceId = (answer.value as LikertAnswerValue)[item.id] if (choiceId != null) { choice = _.findWhere((q as LikertQuestion).choices, { id: choiceId }) if (choice != null) { return
{formUtils.localizeString(choice.label, props.locale)}
} else { return {props.T("Invalid Choice")} } } } case "aquagenx_cbt": return case "cascading_list": return case "cascading_ref": case "cascading_refs": return case "ranked": const sortedChoices = _.sortBy( (q as RankedQuestion).choices, (item: Choice) => (answer.value as RankedAnswerValue)[item.id] ?? 0 ) const items = sortedChoices.map((choice: Choice, index: number) =>
  • {formUtils.localizeString(choice.label, props.locale)}
  • ) return
      {items}
    case "asset": return props.formCtx.renderAssetSummaryView ? props.formCtx.renderAssetSummaryView( (q as AssetQuestion).assetSystemId, answer.value as AssetAnswerValue ) : null } return null } // Special render on multiple rows function renderLikertAnswer(q: Question | MatrixColumnQuestion, answer: Answer | null, prevAnswer: Answer | null) { if (!answer) { return null } if (answer.alternate) { return null } if (answer.value == null) { return null } if (formUtils.getAnswerType(q) === "items_choices") { const likertQuestion = q as LikertQuestion const contents = [] for (let item of likertQuestion.items) { const itemTd = {formUtils.localizeString(item.label, props.locale)} let choiceId = (answer.value as LikertAnswerValue)[item.id] if (choiceId != null) { let choice = _.findWhere(likertQuestion.choices, { id: choiceId }) if (choice != null) { contents.push( {itemTd} {formUtils.localizeString(choice.label, props.locale)} ) } else { contents.push( {itemTd} {props.T("Invalid Choice")} ) } if (props.showPrevAnswers && prevAnswer) { choiceId = (prevAnswer.value as LikertAnswerValue)[item.id] if (choiceId != null) { choice = _.findWhere(likertQuestion.choices, { id: choiceId }) if (choice != null) { contents.push( {itemTd} {formUtils.localizeString(choice.label, props.locale)} ) } else { contents.push( {itemTd} {props.T("Invalid Choice")} ) } } } } } return contents } else { return null } } /** * Get the answer for a question using a dataId. * dataId is the path to the answer in the data object. It can be a simple id, or a path through a roster or matrix. */ function getAnswerUsingDataId(data: ResponseData, dataId: string): Answer | null { const dataIds = dataId.split(".") // Simple question if (dataIds.length === 1) { return data[dataId] as Answer | null } // Roster or matrix const answer = data[dataIds[0]] if (!answer) { return null } // Handle matrix (answer has a value property) if ((answer as Answer).value != null) { const value = (answer as Answer).value as MatrixAnswerValue return value?.[dataIds[1]]?.[dataIds[2]] } // Handle roster if (Array.isArray(answer)) { const rosterEntry = (answer as RosterData)[parseInt(dataIds[1])] // Matrix inside roster if (dataIds.length > 3) { return (rosterEntry?.data[dataIds[2]]?.value as MatrixAnswerValue)?.[dataIds[3]]?.[dataIds[4]] } return rosterEntry?.data[dataIds[2]] } return null } /** Render a question with its answer. * dataId is the path to the answer in the data object. It can be a simple id, or a path through a roster or matrix. */ function renderQuestion(q: Question | MatrixColumnQuestion, dataId: string) { // (Do not render disabled question) https://github.com/mWater/mwater-portal/issues/1578 if ((q as Question).disabled) return null // Get answer const answer = getAnswerUsingDataId(props.data, dataId) // Do not display if empty and hide empty true if (props.hideEmptyAnswers && answer?.value == null && !answer?.alternate) { return null } let prevAnswer: Answer | null = null const trProps: any = { key: dataId } if (props.prevData) { prevAnswer = getAnswerUsingDataId(props.prevData, dataId) } const likertAnswer = renderLikertAnswer(q, answer, prevAnswer) // If both answer and previous answer are falsy if (!prevAnswer && answer?.value == null && props.hideUnchangedAnswers) { return null } if (!_.isEqual(prevAnswer?.value, answer?.value) || !_.isEqual(prevAnswer?.specify, answer?.specify)) { if (props.highlightChanges) { trProps["style"] = { background: "#ffd" } } } else { if (props.hideUnchangedAnswers) { return null } } return [ {formUtils.localizeString(q.text, props.locale)}
    {likertAnswer == null ? renderAnswer(q, answer) : null} {answer && answer.timestamp ? props.T("Answered") + ": " + moment(answer.timestamp).format("llll") : null} {answer && answer.location ? renderLocation(answer.location) : null} {answer && answer.comments ?
    {answer.comments}
    : null} {prevAnswer != null && !_.isEqual(prevAnswer.value, answer?.value) && props.showChangedLink ? {props.T("Edited")} : null}
    {props.showPrevAnswers && props.prevData ? {prevAnswer != null && !_.isEqual(prevAnswer.value, answer?.value) && props.onCompleteHistoryLinkClick ? {props.T("Show Changes")} : null} {renderAnswer(q, prevAnswer)} {prevAnswer && prevAnswer.timestamp ?
    {props.T("Answered")}: {moment(prevAnswer.timestamp).format("llll")}
    : null} {prevAnswer && prevAnswer.location ? renderLocation(prevAnswer.location) : null} : null} , likertAnswer ] } // Add all the items with the proper rosterId to items array // Looks inside groups and sections function collectItemsReferencingRoster(items: any, contents: any, rosterId: string) { // Get the contents of all the other question that are referencing this roster for (let otherItem of contents) { if (otherItem._type === "Group" || otherItem._type === "Section") { collectItemsReferencingRoster(items, otherItem.contents, rosterId) } if (otherItem.rosterId === rosterId) { items.push.apply(items, otherItem.contents) } } } // dataId is the key used for looking up the data + testing visibility // dataId is simply item._id except for rosters children function renderItem(item: Item, visibilityStructure: VisibilityStructure, dataId: string): ReactNode { let items if (!visibilityStructure[dataId]) { return null } const colspan = props.showPrevAnswers && props.prevData ? 3 : 2 // Sections and Groups behave the same if (item._type === "Section" || item._type === "Group") { let contents = _.map(item.contents, item => { let id = item._id if (dataId) { // The group is inside a roster const parts = dataId.split(".") parts.pop() parts.push(item._id) id = parts.join(".") } return renderItem(item, visibilityStructure, id) }) // Remove nulls contents = _.compact(contents) // Do not display if empty if (contents.length === 0) { return null } return [ {formUtils.localizeString(item.name, props.locale)} , contents ] } // RosterMatrices and RosterGroups behave the same // Only the one storing the data will display it // The rosters referencing another one will display a simple text to say so if (item._type === "RosterMatrix" || item._type === "RosterGroup") { // Simply display a text referencing the other roster if a reference if (item.rosterId != null) { // Unless hiding empty, in which case blank if (props.hideEmptyAnswers) { return null } const referencedRoster = formUtils.findItem(props.formDesign, item.rosterId)! as RosterGroup | RosterMatrix return {formUtils.localizeString(item.name, props.locale)} {props.T("Data is stored in {0}", formUtils.localizeString(referencedRoster.name, props.locale))} } // Get the data for that roster const data = props.data[item._id] as RosterData | undefined if ((!data || data.length === 0) && props.hideEmptyAnswers) { return null } // Get the questions of the other rosters referencing this one items = _.clone(item.contents) collectItemsReferencingRoster(items, props.formDesign.contents, item._id) return [ {formUtils.localizeString(item.name, props.locale)} , data != null ? // For each entry in data (() => { const result = [] for (var index = 0; index < data.length; index++) { const entry = data[index] let contents = _.map(items as any[], (childItem: BasicItem | MatrixColumn) => { dataId = `${item._id}.${index}.${childItem._id}` return renderItem(childItem, visibilityStructure, dataId) }) // Remove nulls contents = _.compact(contents) // Do not display if empty if (contents.length === 0) { result.push(null) } else { result.push([ // Display the index of the answer {`${index + 1}.`} , // And the answer for each question contents ]) } } return result })() : undefined ] } if (item._type === "MatrixQuestion") { let answer = props.data[dataId] as Answer if (!answer && dataId.split(".").length === 3) { const dataIds = dataId.split(".") // handle matrix inside of roster where dataId is a path answer = (props.data[dataIds[0]] as RosterData)[parseInt(dataIds[1])].data[dataIds[2]] } if (answer?.value != null) { const rows = [] rows.push( {formUtils.localizeString(item.text, props.locale)} ) for (let rowItem of item.items) { const itemValue = (answer as MatrixAnswerValue).value[rowItem.id] if (itemValue) { rows.push( {formUtils.localizeString(rowItem.label, props.locale)} ) for (let column of item.columns) { if (itemValue[column._id]) { // dataId = `${item._id}.${rowItem.id}.data.${column._id}` rows.push(renderItem(column, visibilityStructure, `${dataId}.${rowItem.id}.${column._id}`)) } } } } return rows } else { return null } } if (formUtils.isQuestionOrMatrixColumnQuestion(item)) { return renderQuestion(item, dataId) } if (formUtils.isExpression(item)) { return renderExpression(item, dataId) } return null } function renderExpression(q: MatrixColumnCalculation | MatrixColumnText, dataId: any) { return [ {formUtils.localizeString(q.text, props.locale)}
    {renderExpressionAnswer(q, dataId, props.data)}
    {props.showPrevAnswers && props.prevData ? {renderExpressionAnswer(q, dataId, props.prevData)} : null} ] } function renderExpressionAnswer(q: MatrixColumnCalculation | MatrixColumnText, dataId: any, responseData: ResponseData) { let rosterId = null let rosterEntryIndex = undefined if (dataId != null) { const dataIds = dataId.split(".") rosterId = dataIds[0] rosterEntryIndex = Number(dataIds[1]) } return } if (error) { return
    {error.message}
    } if (!visibilityStructure) { return
    Loading...
    } return (
    {props.showPrevAnswers ? : undefined} {props.formDesign.contents.map(item => { return renderItem(item, visibilityStructure!, item._id) })}
    {props.T("Question")} {props.T("Answer")}{props.T("Original Answer")}
    {props.formDesign.calculations && props.formDesign.calculations.length > 0 && responseRow && !props.hideCalculations ? (

    {props.T("Calculations")}

    ) : undefined}
    ) } /** Component to display a signature with full-width and click-to-enlarge */ function SignatureDisplayComponent(props: { image: Image; imageManager: ImageManager; T: LocalizeString }) { const [popup, setPopup] = useState(false) return <>
    setPopup(true)}>
    {popup ? ( setPopup(false)} T={props.T} /> ) : null} }