import _ from "lodash" import moment from "moment" import * as formUtils from "./formUtils" import { StickyStorage } from "./formContext" import { FormDesign, Item, MatrixColumn } from "./formDesign" import { Answer, MatrixAnswerValue, ResponseData, RosterData } from "./response" import { VisibilityStructure } from "./VisibilityCalculator" /** The DefaultValueApplier applies a value stored in the stickyStorage as a default answer to a question. * It uses the following logic: * - The question needs to be newly visible * - The question needs to have a default value * - The data for that question needs to be undefined or null, alternate needs to be null or undefined */ export default class DefaultValueApplier { formDesign: FormDesign stickyStorage: StickyStorage entity: any entityType: string | undefined assetSystemId: number | undefined assetType: string | undefined assetId: string | undefined /** entity is entity to use */ constructor(formDesign: FormDesign, stickyStorage: StickyStorage, options: { entity?: any entityType?: string assetSystemId?: number assetType?: string assetId?: string } = {}) { this.formDesign = formDesign this.stickyStorage = stickyStorage this.entity = options.entity this.entityType = options.entityType this.assetSystemId = options.assetSystemId this.assetType = options.assetType this.assetId = options.assetId } setStickyData( data: ResponseData, previousVisibilityStructure: VisibilityStructure, newVisibilityStructure: VisibilityStructure ): ResponseData { // NOTE: Always remember that data is immutable const newData = _.cloneDeep(data) for (let key in newVisibilityStructure) { // If it wasn't visible and it now is const nowVisible = newVisibilityStructure[key] if (nowVisible && !previousVisibilityStructure[key]) { var dataEntry, question, type const values = key.split(".") // Simple question if (values.length === 1) { type = "simple" question = formUtils.findItem(this.formDesign, values[0]) dataEntry = data[values[0]] } else if (values.length === 3 && values[1].match(/^\d+$/)) { // Roster type = "roster" question = formUtils.findItem(this.formDesign, values[2]) // Get roster data const rosterData = data[values[0]] as RosterData // Get roster entry const rosterEntry = rosterData[parseInt(values[1])] // Get data for roster entry if (!rosterEntry) { continue } // Get data for specific question dataEntry = rosterEntry.data[values[2]] } else if (values.length === 3) { // Matrix cell (questionid.itemid.columnid). Only column defaults apply (no sticky/entity) const matrix = formUtils.findItem(this.formDesign, values[0]) if (!matrix || matrix._type !== "MatrixQuestion") { continue } const column = matrix.columns.find((c) => c._id === values[2]) if (!column) { continue } const matrixAnswer = data[values[0]] as Answer | undefined if (matrixAnswer?.alternate != null) { continue } const matrixValue = matrixAnswer?.value as MatrixAnswerValue | undefined const cellAnswer = matrixValue?.[values[1]]?.[values[2]] if (cellAnswer != null && (cellAnswer.value != null || cellAnswer.alternate != null)) { continue } const defaultValue = this.getColumnDefaultValue(column) if (defaultValue == null) { continue } // Answers are immutable, so rebuild the path down to the cell const newMatrixAnswer = { ...(newData[values[0]] as Answer | undefined) } const newMatrixValue: MatrixAnswerValue = { ...(newMatrixAnswer.value as MatrixAnswerValue | undefined) } newMatrixValue[values[1]] = { ...newMatrixValue[values[1]], [values[2]]: { value: defaultValue } } newMatrixAnswer.value = newMatrixValue newData[values[0]] = newMatrixAnswer continue } else { continue } // If question not found if (question == null) { continue } // The data for that question needs to be undefined or null // Alternate for that question needs to be undefined or null if (dataEntry == null || ((dataEntry as Answer).value == null && (dataEntry as Answer).alternate == null)) { const defaultValue = this.getHighestPriorityDefaultValue(question) // Makes sure that a defaultValue has been found if (defaultValue != null && defaultValue !== "") { // Create the dataEntry if not present if (dataEntry == null) { if (type === "simple") { newData[values[0]] = dataEntry = {} } else if (type === "roster") { (newData[values[0]] as RosterData)[parseInt(values[1])].data[values[2]] = dataEntry = {} } } (dataEntry as Answer).value = defaultValue } } } } return newData } /** 2 different sources exist for default values. * This function returns the one with highest priority: * - entityType/entity * - sticky with a stored sticky value */ getHighestPriorityDefaultValue(question: Item) { if ( this.entityType != null && this.entity != null && (question._type === "SiteQuestion" || question._type === "EntityQuestion") ) { let entityType if (question._type === "SiteQuestion") { const siteType = (question.siteTypes ? question.siteTypes[0] : undefined) || "water_point" entityType = siteType.toLowerCase().replace(new RegExp(" ", "g"), "_") } else { ;({ entityType } = question) } if (entityType === this.entityType) { if (question.entityFilter && !matchesEntityFilter(this.entity, question.entityFilter)) { return undefined } if (question._type === "SiteQuestion") { return { code: this.entity.code } } else { return this.entity._id } } } // Fill in asset question if (question._type === "AssetQuestion" && this.assetSystemId != null && this.assetId != null && this.assetType != null) { if (question.assetSystemId === this.assetSystemId) { if (question.assetTypes == null || question.assetTypes.includes(this.assetType)) { return this.assetId } } } // If it's a sticky question or if it has a defaultValue // Tries to use a sticky value if possible, if not it tries to use the defaultValue field if (formUtils.isQuestion(question)) { if (question.sticky) { // Uses stickyStorage.get(questionId) to find any sticky value return this.stickyStorage.get(question._id) } } // Handle defaultNow if (question._type === "DateQuestion" && question.defaultNow) { return getNow(question.format!) } if (formUtils.isMatrixColumnQuestion(question)) { return this.getColumnDefaultValue(question) } return undefined } /** Default value of a matrix or roster matrix column: current date/time or a fixed number */ getColumnDefaultValue(column: MatrixColumn) { if (column._type === "DateColumnQuestion" && column.defaultNow) { return getNow(column.format!) } if (column._type === "NumberColumnQuestion" && column.defaultValue != null) { return column.defaultValue } if (column._type === "UnitsColumnQuestion" && column.defaultValue != null) { return { quantity: column.defaultValue, units: column.defaultUnits ?? undefined } } return undefined } } /** Current date (or date/time if format includes time) as stored in answers */ function getNow(format: string) { if (format.match(/ss|LLL|lll|m|h|H/)) { return new Date().toISOString() } else { return moment().format("YYYY-MM-DD") } } /** Checks if an entity matches a simple MongoDB-style filter. * Supports direct equality (`{ field: value }`) and `$in` (`{ field: { $in: [values] } }`). */ function matchesEntityFilter(entity: any, filter: any): boolean { for (const key of Object.keys(filter)) { const condition = filter[key] const value = entity[key] if (condition != null && typeof condition === "object" && !Array.isArray(condition)) { if ("$in" in condition) { if (!Array.isArray(condition.$in) || !condition.$in.includes(value)) { return false } } } else { if (value !== condition) { return false } } } return true }