diff --git a/Sources/GroveQuestionnaire/DSL/Questions.swift b/Sources/GroveQuestionnaire/DSL/Questions.swift index dd2e43eac..479fe9da2 100644 --- a/Sources/GroveQuestionnaire/DSL/Questions.swift +++ b/Sources/GroveQuestionnaire/DSL/Questions.swift @@ -247,23 +247,31 @@ public struct NumberQuestion: TypedQuestion { } public static func == (question: Self, value: Double) -> Questionnaire.Condition { - .responseValueComparison(taskId: question.id, operator: .equal, value: .decimal(value)) + .responseValueComparison(taskId: question.id, operator: .equal, value: question.conditionValue(value)) } public static func > (question: Self, value: Double) -> Questionnaire.Condition { - .responseValueComparison(taskId: question.id, operator: .greaterThan, value: .decimal(value)) + .responseValueComparison(taskId: question.id, operator: .greaterThan, value: question.conditionValue(value)) } public static func >= (question: Self, value: Double) -> Questionnaire.Condition { - .responseValueComparison(taskId: question.id, operator: .greaterThanOrEqual, value: .decimal(value)) + .responseValueComparison(taskId: question.id, operator: .greaterThanOrEqual, value: question.conditionValue(value)) } public static func < (question: Self, value: Double) -> Questionnaire.Condition { - .responseValueComparison(taskId: question.id, operator: .lessThan, value: .decimal(value)) + .responseValueComparison(taskId: question.id, operator: .lessThan, value: question.conditionValue(value)) } public static func <= (question: Self, value: Double) -> Questionnaire.Condition { - .responseValueComparison(taskId: question.id, operator: .lessThanOrEqual, value: .decimal(value)) + .responseValueComparison(taskId: question.id, operator: .lessThanOrEqual, value: question.conditionValue(value)) + } + + /// The condition value for `value`, with the digits it was written with; in the question's unit for a quantity question. + private func conditionValue(_ value: Double) -> Questionnaire.Condition.Value { + guard let decimal = Decimal(shortestDigitsOf: value) else { + preconditionFailure("A number question is compared with a finite value within the range of Decimal, not \(value).") + } + return valueKind == .quantity ? .quantity(value: decimal, unitCode: unit?.code) : .decimal(decimal) } /// Bounds the accepted values (FHIR `minValue`/`maxValue`). diff --git a/Sources/GroveQuestionnaire/Model/Condition.swift b/Sources/GroveQuestionnaire/Model/Condition.swift index fd591a563..f396dc799 100644 --- a/Sources/GroveQuestionnaire/Model/Condition.swift +++ b/Sources/GroveQuestionnaire/Model/Condition.swift @@ -19,8 +19,15 @@ extension Questionnaire { /// /// A condition may reference any other task in the questionnaire, including tasks that appear /// after the one it belongs to (matching FHIR's `enableWhen`, which places no ordering - /// restriction on references). A condition that references its own task, an unknown task, or a - /// task that is itself currently disabled evaluates as if the referenced response were absent. + /// restriction on references). A condition that references a task that is itself currently + /// disabled evaluates as if the referenced response were absent; one that references its own task or an + /// unknown task cannot be evaluated and leaves the task disabled. + /// + /// A follow-up task occurs once for every selected option of its choice task, and once without answers while + /// the choice task has no selection or is disabled. A condition reads the + /// occurrence FHIR R4 names for `enableWhen.question`: the nearest occurrence on the ancestor axis, + /// then on the preceding axis, then on the following axis, in document order, where the follow-up + /// tasks of the selected options follow their choice task in the order of the options. /// /// ## Topics /// @@ -70,8 +77,18 @@ extension Questionnaire { /// A condition that compares a task's response to some value. /// - /// - Note: Not all comparisons make sense for all question types. - /// If a response is compared against a value of a different type, or if the operator isn't applicable for the type, the condition evaluates to `false`. + /// Integer and decimal values compare numerically with integer and decimal responses, without + /// binary floating-point rounding, so a response of `80.5` satisfies `>= .integer(80)`. + /// A ``Value/SCMCOption(id:)`` matches only the option with exactly that id. + /// + /// - Note: Not all comparisons make sense for all question types. A value of a type the question's answers + /// cannot be compared with, such as a string for a boolean question or a decimal for integer options, + /// makes the condition one that cannot be evaluated, and so does a reference to the task itself, to a + /// task it encloses, or to a task whose enablement depends on it. Such a condition satisfies no operator, + /// ``ComparisonOperator/notEqual`` included, and leaves the task disabled; within ``all(_:)`` and + /// ``any(_:)`` the other conditions still decide where they suffice. A comparison whose outcome the + /// values leave open, such as a full date against `2024` or a quantity in another unit, also satisfies + /// no operator. /// /// - parameter taskId: The id of the task whose response should be inspected. /// - parameter operator: The comparison operation @@ -91,10 +108,11 @@ extension Questionnaire { public enum ComparisonOperator: Hashable, Sendable { /// True if at least one answer has a value that is equal to the enableWhen answer case equal - /// True if at least one answer has a value that is not equal to the enableWhen answer. + /// True if no answer has a value that is equal to the enableWhen answer. /// - /// Unlike `.not(.responseValueComparison(…, .equal, …))`, this evaluates to `false` - /// when the referenced question has no answer, matching FHIR's enableWhen semantics. + /// This also holds when the referenced question has no answer, matching FHIR's enableWhen semantics. + /// It differs from `.not(.responseValueComparison(…, .equal, …))` where equality is open, such as for + /// a full date against `2024`: there neither holds. case notEqual /// True if at least one answer has a value that is less than the enableWhen answer case lessThan @@ -109,13 +127,20 @@ extension Questionnaire { /// Value used in comparison conditions. public enum Value: Hashable, Sendable { case bool(Bool) + /// An integer, compared numerically with integer and decimal responses. case integer(Int) - case decimal(Double) + /// A decimal, compared numerically with integer and decimal responses. + /// + /// It keeps the digits it was given, such as a FHIR `answerDecimal`, so that a + /// comparison never depends on binary floating-point rounding. A float literal such as + /// `.decimal(36.52)` passes through `Double` and carries its binary expansion + /// (`36.52000000000000512`); write `Decimal(string: "36.52")`, or use the `NumberQuestion` operators. + case decimal(Decimal) case string(String) case date(DateComponents) - /// A quantity, compared against numeric responses whose unit matches `unitCode` - /// (a `nil` `unitCode` matches any unit). - case quantity(value: Double, unitCode: String?) + /// A quantity, compared against quantity responses in the unit `unitCode`; units are not converted, + /// and a `nil` `unitCode` compares only with responses without a unit. + case quantity(value: Decimal, unitCode: String?) /// A choice option, identified by its ``Questionnaire/Task/Kind-swift.struct/ChoiceConfig/Option/id``. /// /// For options created from FHIR codings, the id is the `system|code` token diff --git a/Sources/GroveQuestionnaire/Model/Decimal+Double.swift b/Sources/GroveQuestionnaire/Model/Decimal+Double.swift new file mode 100644 index 000000000..b56b9d178 --- /dev/null +++ b/Sources/GroveQuestionnaire/Model/Decimal+Double.swift @@ -0,0 +1,27 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +package import Foundation + + +extension Decimal { + /// The decimal with the shortest digits that convert back to `value`. + /// + /// A number typed into a form or read from JSON becomes the nearest `Double`, and its shortest + /// round-trip digits are the digits that were given, up to 15 significant digits. + /// `Decimal(value)` instead expands the binary value, so `36.52` becomes `36.52000000000000512`. + /// + /// `nil` for a value that is not finite or lies outside the range of `Decimal`. + package init?(shortestDigitsOf value: Double) { + guard value.isFinite, + let decimal = Decimal(string: String(value), locale: Locale(identifier: "en_US_POSIX")) else { + return nil + } + self = decimal + } +} diff --git a/Sources/GroveQuestionnaire/Model/QuestionKindDefinition.swift b/Sources/GroveQuestionnaire/Model/QuestionKindDefinition.swift index 78fc9bdb5..7c0cc9f62 100644 --- a/Sources/GroveQuestionnaire/Model/QuestionKindDefinition.swift +++ b/Sources/GroveQuestionnaire/Model/QuestionKindDefinition.swift @@ -39,7 +39,8 @@ public protocol QuestionKindDefinition: Sendable, SendableMetatype { /// Evaluates a ``Questionnaire/Condition/responseValueComparison(taskId:operator:value:)`` condition against a response collected to a question of this kind. /// - /// - Note: By default, this function always returns `false`. + /// - Note: By default, the response is equal to no value and has no order, so this function returns `true` + /// for ``Questionnaire/Condition/ComparisonOperator/notEqual`` and `false` for every other operator. static func evaluateResponseValueComparison( for config: Config, response: QuestionnaireResponses.Response.Value, @@ -58,9 +59,8 @@ extension QuestionKindDefinition { operator: Questionnaire.Condition.ComparisonOperator, value: Questionnaire.Condition.Value ) -> Bool { - // Idea: instead of always returning false, we could try to default-match the response value against the condition value. - // But: might not be what we want here; the current behaviour is more explicit in forcing the question kind to customize this! - false + // A question kind customizes this to compare its responses; without that, no response equals the value. + `operator` == .notEqual } } diff --git a/Sources/GroveQuestionnaire/Model/QuestionnaireResponses+ConditionAnswer.swift b/Sources/GroveQuestionnaire/Model/QuestionnaireResponses+ConditionAnswer.swift new file mode 100644 index 000000000..55e96a632 --- /dev/null +++ b/Sources/GroveQuestionnaire/Model/QuestionnaireResponses+ConditionAnswer.swift @@ -0,0 +1,247 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +import Foundation + + +/// One answer of a question, in the form a ``Questionnaire/Condition/responseValueComparison(taskId:operator:value:)`` compares it. +@available(iOS 18, macOS 15, watchOS 11, *) +enum ConditionAnswer { + case bool(Bool) + case string(String) + /// An integer or decimal answer, compared exactly. + case number(Decimal) + /// A quantity answer, compared exactly in `unitCode`, the unit the answer is given in. + case quantity(Decimal, unitCode: String?) + /// The integer value of a choice option, which compares only with an integer. + case integerOption(Int) + case date(DateComponents, style: Questionnaire.Task.Kind.DateTimeConfig.Style) + /// A selected choice option, together with the value it stands for. + indirect case option(id: String, value: ConditionAnswer?) + + /// How the answer compares with an enableWhen value. + enum Comparison { + /// The values are ordered. + case ordered(ComparisonResult) + /// The values have no order, and are equal or not. + case equal(Bool) + /// The values could be ordered, but their precision or unit leaves the order open. + case unknown + /// The values are of different kinds: not equal, and without an order. + case incomparable + + /// Whether the values are equal; `nil` if that is unknown. + var isEqual: Bool? { // swiftlint:disable:this discouraged_optional_boolean + switch self { + case .ordered(let order): order == .orderedSame + case .equal(let equal): equal + case .unknown: nil + case .incomparable: false + } + } + } + + /// Whether `operator` can compare with `value`: the ordered operators need a value with an order. + static func compares(_ operator: Questionnaire.Condition.ComparisonOperator, with value: Questionnaire.Condition.Value) -> Bool { + switch (`operator`, value) { + case (.equal, _), (.notEqual, _), (_, .integer), (_, .decimal), (_, .date), (_, .quantity): + true + default: + false + } + } + + /// Whether a condition with `value` can be evaluated on the answers of `task`. + /// + /// These are the `answer[x]` types the pair rules compare with each item type; a custom kind compares its own. + static func compares( // swiftlint:disable:this cyclomatic_complexity + _ value: Questionnaire.Condition.Value, + withAnswersOf task: Questionnaire.Task + ) -> Bool { + func isDate(_ components: DateComponents) -> Bool { + components.year != nil && components.hour == nil + } + func isTime(_ components: DateComponents) -> Bool { + components.year == nil && components.hour != nil + } + switch (task.kind.variant, value) { + case (.boolean, .bool), (.freeText, .string), (.custom, _): + return true + case let (.numeric(config), value): + switch value { + case .integer, .decimal: return config.valueKind != .quantity + case .quantity: return config.valueKind == .quantity + default: return false + } + case let (.dateTime(config), .date(components)): + switch config.style { + case .dateOnly: return isDate(components) + case .timeOnly: return isTime(components) + case .dateAndTime: return components.year != nil + } + case (.choice, .SCMCOption), (.choice, .string), (.choice, .integer): + return true + case let (.choice, .date(components)): + return isDate(components) || isTime(components) + default: + return false + } + } + + /// The answers a response holds for the task. + static func answers( // swiftlint:disable:this cyclomatic_complexity + of response: QuestionnaireResponses.Response.Value, + for task: Questionnaire.Task + ) -> [Self] { + switch task.kind.variant { + case .boolean: + return response.boolValue.map { [.bool($0)] } ?? [] + case .freeText: + return response.stringValue.map { [.string($0)] } ?? [] + case .dateTime(let config): + return response.dateValue.map { [.date($0, style: config.style)] } ?? [] + case .numeric(let config): + // A unit the participant chose (unitOption) takes precedence over the fixed unit. + let unitCode = response.quantityValue?.unitCode ?? config.unitCode ?? (config.unit.base.isEmpty ? nil : config.unit.base) + guard let number = response.numberValue.flatMap({ Decimal(shortestDigitsOf: $0) }) else { + return [] + } + return [config.valueKind == .quantity ? .quantity(number, unitCode: unitCode) : .number(number)] + case .choice(let config): + let choice = response.choiceValue + let selected: [Self] = config.options.filter { choice.selectedOptions.contains($0.id) }.map { option in + let value: Self? = switch option.answerValue { + case .string(let string): .string(string) + case .integer(let integer): .integerOption(integer) + case .date(let date): .date(date, style: .dateOnly) + case .time(let time): .date(time, style: .timeOnly) + case nil: nil + } + return .option(id: option.id, value: value) + } + // The open-choice free-text answer. + return selected + (choice.freeTextOtherResponse.map { [.string($0)] } ?? []) + case .instructional, .fileAttachment, .custom: + return [] + } + } + + private static func compare(_ lhs: T, _ rhs: T) -> ComparisonResult { + lhs < rhs ? .orderedAscending : lhs > rhs ? .orderedDescending : .orderedSame + } + + private static func compare( + _ answer: DateComponents, + _ value: DateComponents, + style: Questionnaire.Task.Kind.DateTimeConfig.Style + ) -> ComparisonResult? { + switch style { + case .timeOnly: + let answer = [answer.hour ?? 0, answer.minute ?? 0, answer.second ?? 0] + let value = [value.hour ?? 0, value.minute ?? 0, value.second ?? 0] + return answer == value ? .orderedSame : answer.lexicographicallyPrecedes(value) ? .orderedAscending : .orderedDescending + case .dateOnly: + // Dates compare as far as both state them; when they agree that far and one is more precise, + // the order is unknown, as in FHIR (`2024-03-05` neither equals nor follows `2024`). + let answer = [answer.year, answer.month, answer.day].prefix { $0 != nil }.compactMap(\.self) + let value = [value.year, value.month, value.day].prefix { $0 != nil }.compactMap(\.self) + let common = min(answer.count, value.count) + guard common > 0 else { + return nil + } + if answer.prefix(common) == value.prefix(common) { + return answer.count == value.count ? .orderedSame : nil + } + return answer.prefix(common).lexicographicallyPrecedes(value.prefix(common)) ? .orderedAscending : .orderedDescending + case .dateAndTime where value.hour == nil: + // A condition without a time compares with the answer's date; on the same day, the answer's time + // leaves the order open. + let order = compare(answer, value, style: .dateOnly) + return order == .orderedSame && answer.hour != nil ? nil : order + case .dateAndTime: + let calendar = Calendar.current + guard let answer = calendar.date(from: answer), let value = calendar.date(from: value) else { + return nil + } + return compare(answer, value) + } + } + + /// How the answer compares with `expected`, by the rules of the pair validation. + func comparison(with expected: Questionnaire.Condition.Value) -> Comparison { + switch (self, expected) { + case let (.bool(answer), .bool(value)): + return .equal(answer == value) + case let (.string(answer), .string(value)): + // FHIR strings compare by their characters as written, without Unicode normalization. + return .equal(answer.utf8.elementsEqual(value.utf8)) + case let (.option(id, _), .SCMCOption(conditionId)): + // Option ids created from FHIR codings are `system|code` tokens, or the bare code for a + // coding without a system, so a coding matches only when system and code are both equal. + return .equal(id == conditionId) + case let (.option(_, value?), _): + return value.comparison(with: expected) + case let (.number(answer), .integer(value)): + return .ordered(Self.compare(answer, Decimal(value))) + case let (.number(answer), .decimal(value)): + return .ordered(Self.compare(answer, value)) + case let (.integerOption(answer), .integer(value)): + return .ordered(Self.compare(answer, value)) + case let (.quantity(answer, unitCode), .quantity(value, conditionUnit)): + // Units are not converted; a condition without a unit orders only answers without a unit. + return conditionUnit == unitCode ? .ordered(Self.compare(answer, value)) : .unknown + case let (.date(answer, style), .date(value)): + return Self.compare(answer, value, style: style).map { .ordered($0) } ?? .unknown + default: + return .incomparable + } + } +} + + +@available(iOS 18, macOS 15, watchOS 11, *) +extension [ConditionAnswer] { + /// FHIR enableWhen: `!=` holds when no answer equals the value, so also without an answer; + /// every other operator holds when at least one answer satisfies it. `nil` if the outcome is open. + func satisfy( + _ operator: Questionnaire.Condition.ComparisonOperator, + _ value: Questionnaire.Condition.Value + ) -> Bool? { // swiftlint:disable:this discouraged_optional_boolean + let comparisons = map { $0.comparison(with: value) } + // An answer whose comparison is open decides nothing, so the outcome is open unless another answer decides it. + let isOpen = comparisons.contains { + guard case .unknown = $0 else { + return false + } + return true + } + func ordered(_ accepted: Set) -> Bool? { // swiftlint:disable:this discouraged_optional_boolean + let holds = comparisons.contains { + guard case .ordered(let order) = $0 else { + return false + } + return accepted.contains(order) + } + return holds ? true : isOpen ? nil : false + } + switch `operator` { + case .equal: + return comparisons.contains { $0.isEqual == true } ? true : isOpen ? nil : false + case .notEqual: + return comparisons.contains { $0.isEqual == true } ? false : isOpen ? nil : true + case .lessThan: + return ordered([.orderedAscending]) + case .greaterThan: + return ordered([.orderedDescending]) + case .lessThanOrEqual: + return ordered([.orderedAscending, .orderedSame]) + case .greaterThanOrEqual: + return ordered([.orderedDescending, .orderedSame]) + } + } +} diff --git a/Sources/GroveQuestionnaire/Model/QuestionnaireResponses+Conditions.swift b/Sources/GroveQuestionnaire/Model/QuestionnaireResponses+Conditions.swift index f90b4ed7b..6d93a0a6b 100644 --- a/Sources/GroveQuestionnaire/Model/QuestionnaireResponses+Conditions.swift +++ b/Sources/GroveQuestionnaire/Model/QuestionnaireResponses+Conditions.swift @@ -12,19 +12,47 @@ private import GroveFoundation @available(iOS 18, macOS 15, watchOS 11, *) extension QuestionnaireResponses { - /// Controls task id lookup behaviour when evaluating a condition. - private struct TaskLookupConfig { - /// Whether the condition should be limited to only see responses for tasks that precede the one to which the condition belongs. - let limitToPreviousTasks: Bool - /// Whether, if the condition references a task that cannot be found in the current scope, the lookup for this task should continue in the parent scope. - let exposeParentScope: Bool - } - - private struct ResolvedTask { + /// A class, so that the evaluation, which recurses once for every task a condition depends on, keeps small + /// stack frames. + private final class ResolvedTask { /// The task with the resolved id. let task: Questionnaire.Task /// The ``QuestionnaireResponses`` instance whose ``QuestionnaireResponses/responses`` property contains this task's + /// response; for an answerless occurrence, the container of the task it stands beneath. let responses: QuestionnaireResponses + /// The occurrence's place in document order: the index of each enclosing task in its container, + /// each followed by the index of the choice option whose follow-up container holds the next level. + let position: [Int] + /// Whether the occurrence has no answers by construction: it stands for the follow-up tasks of a task that + /// is disabled or has no follow-up container, as the pair rules place items beneath a question without answers. + let isAnswerless: Bool + + init(task: Questionnaire.Task, responses: QuestionnaireResponses, position: [Int], isAnswerless: Bool = false) { + self.task = task + self.responses = responses + self.position = position + self.isAnswerless = isAnswerless + } + } + + /// A task definition, held by reference for the same reason as ``ResolvedTask``. + private final class TaskDefinition { + let task: Questionnaire.Task + + init(_ task: Questionnaire.Task) { + self.task = task + } + } + + /// What a condition reads for a referenced task. + private enum Source { + /// The occurrence the condition reads; it is enabled. + case occurrence(ResolvedTask) + /// The task has no enabled occurrence the condition can read, so it has no answers. + case absent(TaskDefinition) + /// The condition cannot be evaluated: it reads its own task, a task the questionnaire does not have, + /// a task it encloses, or a task whose enablement depends on it. + case unknown } @@ -37,35 +65,46 @@ extension QuestionnaireResponses { /// - parameter visited: The task ids already on the evaluation stack; a task encountered /// twice forms a reference cycle and evaluates as disabled, terminating the recursion. private func shouldEnable(task: Questionnaire.Task, visited: Set) -> Bool { + // A condition that cannot be evaluated leaves the task disabled. + enablement(of: task, visited: visited) == true + } + + /// Whether the task is enabled; `nil` if its conditions cannot be evaluated, as on a reference cycle. + private func enablement( + of task: Questionnaire.Task, + visited: Set + ) -> Bool? { // swiftlint:disable:this discouraged_optional_boolean guard !visited.contains(task.id) else { - return false + return nil } let visited = visited.union([task.id]) - // FHIR's enableWhen places no ordering restriction on references, so lookups - // consider the whole questionnaire, not only preceding tasks. - let config = TaskLookupConfig(limitToPreviousTasks: false, exposeParentScope: true) // A grouped task is asked only while every group it sits in is enabled. - return task.groupPath.allSatisfy { evaluate($0.condition, for: task, visited: visited, config: config) } - && evaluate(task.enabledCondition, for: task, visited: visited, config: config) + let outcomes = task.groupPath.map { evaluate($0.condition, for: task, visited: visited) } + + [evaluate(task.enabledCondition, for: task, visited: visited)] + return outcomes.contains(false) ? false : outcomes.contains(nil) ? nil : true } private func evaluate( _ condition: Questionnaire.Condition, for task: Questionnaire.Task, - visited: Set, - config: TaskLookupConfig - ) -> Bool { + visited: Set + ) -> Bool? { // swiftlint:disable:this discouraged_optional_boolean Self._evaluate(condition) { - guard let resolved = resolveTaskId(targetTaskId: $0, currentTaskId: task.id, using: config) else { - return nil + let source = resolve(targetTaskId: $0, from: task.id, visited: visited) + guard case .occurrence(let resolved) = source else { + return source } - // FHIR: when evaluating enableWhen, the answers of an item that is itself - // currently disabled are treated as absent. - guard resolved.responses.shouldEnable(task: resolved.task, visited: visited) else { - return nil + guard !resolved.isAnswerless else { + return .absent(TaskDefinition(resolved.task)) + } + // FHIR: when evaluating enableWhen, the answers of an item that is itself currently disabled are + // treated as absent. A task whose enablement is evaluated further up forms a cycle and is unknown. + switch resolved.responses.enablement(of: resolved.task, visited: visited) { + case true?: return source + case false?: return .absent(TaskDefinition(resolved.task)) + case nil: return .unknown } - return resolved } evaluateExpression: { expression in // SDC enableWhenExpression: an empty result disables the item. A failing one is // an authoring defect, so it is recorded before the item disappears. @@ -95,38 +134,45 @@ extension QuestionnaireResponses { return true } let visited = visited.union([task.id]) - let config = TaskLookupConfig(limitToPreviousTasks: false, exposeParentScope: true) - return task.groupPath.allSatisfy { isSettled($0.condition, for: task, visited: visited, config: config) } - && isSettled(task.enabledCondition, for: task, visited: visited, config: config) + return task.groupPath.allSatisfy { isSettled($0.condition, for: task, visited: visited) } + && isSettled(task.enabledCondition, for: task, visited: visited) } private func isSettled( _ condition: Questionnaire.Condition, for task: Questionnaire.Task, - visited: Set, - config: TaskLookupConfig + visited: Set ) -> Bool { func settled(_ inner: Questionnaire.Condition) -> Bool { - isSettled(inner, for: task, visited: visited, config: config) + isSettled(inner, for: task, visited: visited) } - func holds(_ inner: Questionnaire.Condition) -> Bool { - evaluate(inner, for: task, visited: visited, config: config) + func outcome(_ inner: Questionnaire.Condition) -> Bool? { // swiftlint:disable:this discouraged_optional_boolean + evaluate(inner, for: task, visited: visited) } switch condition { case .not(let inner): return settled(inner) case .all(let inner): // One settled miss decides it; otherwise every part has to be settled. - return inner.contains { settled($0) && !holds($0) } || inner.allSatisfy { settled($0) } + return inner.contains { settled($0) && outcome($0) == false } || inner.allSatisfy { settled($0) } case .any(let inner): - return inner.contains { settled($0) && holds($0) } || inner.allSatisfy { settled($0) } + return inner.contains { settled($0) && outcome($0) == true } || inner.allSatisfy { settled($0) } case .expression(let expression): guard let engine = questionnaire.expressionEngine else { return true } return (try? engine.evaluateBoolean(expression, scope: .item(task.id), in: self)) != .empty case .hasResponse(let taskId), .isMissingResponse(let taskId), .responseValueComparison(let taskId, _, _): - guard let resolved = resolveTaskId(targetTaskId: taskId, currentTaskId: task.id, using: config) else { + let resolved: ResolvedTask + switch resolve(targetTaskId: taskId, from: task.id, visited: visited) { + case .occurrence(let occurrence) where occurrence.isAnswerless: + // A follow-up task whose option is not selected yet, or whose choice task is disabled, can still occur. + return false + case .occurrence(let occurrence): + resolved = occurrence + case .absent: + return false + case .unknown: return true } // An answer settles it, and so does the referenced question being ruled out for good. @@ -136,330 +182,155 @@ extension QuestionnaireResponses { } } - /// Looks up a ``Questionnaire/Task``, based on its id, in compliance with a ``TaskLookupConfig``. - private func resolveTaskId( // swiftlint:disable:this cyclomatic_complexity + /// The occurrence of `targetTaskId` that a condition of the task `currentTaskId` in this container reads. + /// + /// Follows FHIR R4 `Questionnaire.item.enableWhen.question`: the nearest occurrence on the ancestor axis, + /// then on the preceding axis, then on the following axis, in document order. A follow-up task occurs once + /// in the container of every selected option of its choice task, in the order of the options, while that + /// choice task is enabled, and otherwise once without answers. A condition never reads its own task. + private func resolve( targetTaskId: Questionnaire.Task.ID, - currentTaskId: Questionnaire.Task.ID, - using config: TaskLookupConfig - ) -> ResolvedTask? { - guard targetTaskId != currentTaskId else { - // A condition is never allowed to reference its own task - return nil + from currentTaskId: Questionnaire.Task.ID, + visited: Set + ) -> Source { + let tasks = questionnaire.sections.flatMap(\.tasks) + guard targetTaskId != currentTaskId, let definition = Self.task(targetTaskId, in: tasks), + let current = position(of: currentTaskId) else { + return .unknown } - switch _variant { - case .root: - // if we're at the root level, we only can look up top-level (i.e., non-nested) tasks. - let allTopLevelTasks = questionnaire.sections.flatMap(\.tasks) - guard let curIdx = allTopLevelTasks.firstIndex(where: { $0.id == currentTaskId }) else { - // we were unable to find the current task. this should never happen - assertionFailure("Failed to resolve current task (\(currentTaskId)) in scope consisting of \(allTopLevelTasks.map(\.id))") - return nil - } - guard let targetIdx = allTopLevelTasks.firstIndex(where: { $0.id == targetTaskId }) else { - // we were not able to find the referenced task. - // since we're not at the root level, we simply return nil. - return nil - } - if targetIdx < curIdx || !config.limitToPreviousTasks { - // the referenced task is ordered before the current task, or we're not limited to earlier tasks. all is well. - return .init(task: allTopLevelTasks[targetIdx], responses: self) - } else { - return nil - } - case let .view(parent, pathFromParent: _): - // we're nested somwehere within the questionnaire. - // this is a little more tricky now. - let parentTaskPath = self.pathFromRoot.compactMap { component in - switch component { - case .task(let taskId): - taskId - case .choiceOption: - nil + guard let candidates = Self.occurrences( + of: targetTaskId, + in: tasks, + container: root, + position: [], + currentPath: Array(pathFromRoot), + visited: visited + ) else { + return .unknown + } + if let ancestor = candidates.last(where: { current.starts(with: $0.position) }) { + return .occurrence(ancestor) + } + if let nearest = candidates.last(where: { $0.position.lexicographicallyPrecedes(current) }) + ?? candidates.first(where: { current.lexicographicallyPrecedes($0.position) && !$0.position.starts(with: current) }) { + return .occurrence(nearest) + } + return .absent(TaskDefinition(definition)) + } + + /// The document position of the task with `taskId` in this container; see ``ResolvedTask/position``. + private func position(of taskId: Questionnaire.Task.ID) -> [Int]? { // swiftlint:disable:this discouraged_optional_collection + var tasks = questionnaire.sections.flatMap(\.tasks) + var current: Questionnaire.Task? + var container = root + var position: [Int] = [] + for component in pathFromRoot { + switch component { + case .task(let id): + guard let index = tasks.firstIndex(where: { $0.id == id }) else { + return nil } - } - guard let parentTask = questionnaire.task(at: parentTaskPath) else { - assertionFailure("unable to find parent task") - return nil - } - let allTasks = parentTask.kind.followUpTasks - guard let curIdx = allTasks.firstIndex(where: { $0.id == currentTaskId }) else { - // we were unable to find the current task. this should never happen - assertionFailure() - return nil - } - guard let targetIdx = allTasks.firstIndex(where: { $0.id == targetTaskId }) else { - // we were unable to find the referenced task at the current level. - return if config.exposeParentScope { - parent.resolveTaskId(targetTaskId: targetTaskId, currentTaskId: parentTask.id, using: config) - } else { - nil + position.append(index) + current = tasks[index] + case .choiceOption(let optionId): + guard let task = current, + let index = Self.followUpContainerIndex(of: optionId, of: task, in: container) else { + return nil } + position.append(index) + tasks = task.kind.followUpTasks + container = container.view(appending: ResponsesPath().appending(taskId: task.id).appending(choiceOption: optionId)) } - // we found both the current and the target task, at the current level - if targetIdx < curIdx || !config.limitToPreviousTasks { - return .init(task: allTasks[targetIdx], responses: self) - } else { - return nil - } } + guard let index = tasks.firstIndex(where: { $0.id == taskId }) else { + return nil + } + return position + [index] } } @available(iOS 18, macOS 15, watchOS 11, *) extension QuestionnaireResponses { + /// The outcome of `condition`: `nil` if it cannot be evaluated, as in the pair rules. + /// + /// `not`, `all` and `any` follow three-valued logic, so a condition that cannot be evaluated decides only + /// where the known conditions do not. /// - parameter condition: The ``Questionnaire/Condition`` that should be evaluated - /// - parameter resolveTaskId: A closure that maps a task is to its task. The function uses this to resolve tasks that are referenced by the condition. - private static func _evaluate( // swiftlint:disable:this cyclomatic_complexity function_body_length + /// - parameter resolveTaskId: Maps a referenced task id to what the condition reads for it. + private static func _evaluate( // swiftlint:disable:this cyclomatic_complexity _ condition: Questionnaire.Condition, - _ resolveTaskId: (Questionnaire.Task.ID) -> ResolvedTask?, + _ resolveTaskId: (Questionnaire.Task.ID) -> Source, evaluateExpression: (String) -> Bool - ) -> Bool { + ) -> Bool? { // swiftlint:disable:this discouraged_optional_boolean + func inner(_ condition: Questionnaire.Condition) -> Bool? { // swiftlint:disable:this discouraged_optional_boolean + _evaluate(condition, resolveTaskId, evaluateExpression: evaluateExpression) + } switch condition { - case .not(let inner): - return !_evaluate(inner, resolveTaskId, evaluateExpression: evaluateExpression) - case .any(let inner): - return inner.contains { _evaluate($0, resolveTaskId, evaluateExpression: evaluateExpression) } - case .all(let inner): - return inner.allSatisfy { _evaluate($0, resolveTaskId, evaluateExpression: evaluateExpression) } + case .not(let condition): + return inner(condition).map(!) + case .any(let conditions): + let outcomes = conditions.map(inner) + return outcomes.contains(true) ? true : outcomes.contains(nil) ? nil : false + case .all(let conditions): + let outcomes = conditions.map(inner) + return outcomes.contains(false) ? false : outcomes.contains(nil) ? nil : true case .expression(let expression): return evaluateExpression(expression) case .hasResponse(let taskId): - guard let resolved = resolveTaskId(taskId) else { - return false + switch resolveTaskId(taskId) { + case .occurrence(let resolved): return resolved.responses.hasResponse(for: resolved.task) + case .absent: return false + case .unknown: return nil } - return resolved.responses.hasResponse(for: resolved.task) case .isMissingResponse(let taskId): - guard let resolved = resolveTaskId(taskId) else { - return false + switch resolveTaskId(taskId) { + case .occurrence(let resolved): return resolved.responses.isMissingResponse(for: resolved.task) + case .absent: return false + case .unknown: return nil } - return resolved.responses.isMissingResponse(for: resolved.task) case let .responseValueComparison(taskId, `operator`, value): - guard let resolved = resolveTaskId(taskId) else { - return false + return compare(resolveTaskId(taskId), `operator`, value) + } + } + + /// The outcome of a ``Questionnaire/Condition/responseValueComparison(taskId:operator:value:)`` on `source`. + @inline(never) + private static func compare( + _ source: Source, + _ operator: Questionnaire.Condition.ComparisonOperator, + _ value: Questionnaire.Condition.Value + ) -> Bool? { // swiftlint:disable:this discouraged_optional_boolean + let resolved: ResolvedTask + switch source { + case .occurrence(let occurrence): + resolved = occurrence + case .absent(let definition): + if case .custom = definition.task.kind.variant { + return `operator` == .notEqual } - let task = resolved.task - let responses = resolved.responses.responses - switch task.kind.variant { - case .instructional: - return false - case .boolean: - guard let response = responses[task.id].value.boolValue, - case let .bool(value) = value else { - return false - } - switch `operator` { - case .equal: - return response == value - case .notEqual: - return response != value - case .lessThan, .greaterThan, .lessThanOrEqual, .greaterThanOrEqual: - // not supported - return false - } - case .choice(let config): - let response = responses[task.id].value.choiceValue - // Option ids created from FHIR codings are `system|code` tokens; a condition - // coding without a system matches on the bare code. - func matches(optionId: String, conditionId: String) -> Bool { - optionId == conditionId || (!conditionId.contains("|") && optionId.hasSuffix("|\(conditionId)")) - } - switch value { - case let .SCMCOption(conditionId): - switch `operator` { - case .equal: - return response.selectedOptions.contains { matches(optionId: $0, conditionId: conditionId) } - case .notEqual: - // FHIR: true if at least one answer differs; an unanswered question stays false. - return response.selectedOptions.contains { !matches(optionId: $0, conditionId: conditionId) } - case .lessThan, .greaterThan, .lessThanOrEqual, .greaterThanOrEqual: - return false - } - case .string(let expected): - // String-valued answerOptions, plus the open-choice free-text answer. - let selected: [String] = response.selectedOptions.compactMap { id in - config.options.first { $0.id == id }.flatMap { - if case .string(let string) = $0.answerValue { string } else { nil } - } - } + (response.freeTextOtherResponse.map { [$0] } ?? []) - switch `operator` { - case .equal: - return selected.contains(expected) - case .notEqual: - return selected.contains { $0 != expected } - case .lessThan, .greaterThan, .lessThanOrEqual, .greaterThanOrEqual: - return false - } - case .integer(let expected): - let selected: [Int] = response.selectedOptions.compactMap { id in - config.options.first { $0.id == id }.flatMap { - if case .integer(let int) = $0.answerValue { int } else { nil } - } - } - switch `operator` { - case .equal: - return selected.contains(expected) - case .notEqual: - return selected.contains { $0 != expected } - case .lessThan, .greaterThan, .lessThanOrEqual, .greaterThanOrEqual: - return false - } - case .bool, .decimal, .date, .quantity: - return false - } - case .freeText: - guard case let .string(value) = value, - let response = responses[task.id].value.stringValue else { - return false - } - switch `operator` { - case .equal: - return response == value - case .notEqual: - return response != value - case .lessThan, .greaterThan, .lessThanOrEqual, .greaterThanOrEqual: - // not supported - return false - } - case .dateTime(let config): - guard let response = responses[task.id].value.dateValue else { - return false - } - guard case .date(let expected) = value else { - return false - } - switch config.style { - case .timeOnly: - let response = (response.hour ?? 0, response.minute ?? 0, response.second ?? 0) - let expected = (expected.hour ?? 0, expected.minute ?? 0, expected.second ?? 0) - return switch `operator` { - case .equal: - response == expected - case .notEqual: - response != expected - case .greaterThan: - response > expected - case .greaterThanOrEqual: - response >= expected - case .lessThan: - response < expected - case .lessThanOrEqual: - response <= expected - } - case .dateOnly: - let response = (response.year ?? 0, response.month ?? 1, response.day ?? 1) - let expected = (expected.year ?? 0, expected.month ?? 1, expected.day ?? 1) - return switch `operator` { - case .equal: - response == expected - case .notEqual: - response != expected - case .greaterThan: - response > expected - case .greaterThanOrEqual: - response >= expected - case .lessThan: - response < expected - case .lessThanOrEqual: - response <= expected - } - case .dateAndTime: - let cal = Calendar.current - guard let response = cal.date(from: response), let expected = cal.date(from: expected) else { - return false - } - return switch `operator` { - case .equal: - response == expected - case .notEqual: - response != expected - case .greaterThan: - response > expected - case .greaterThanOrEqual: - response >= expected - case .lessThan: - response < expected - case .lessThanOrEqual: - response <= expected - } - } - case .numeric(let config): - switch value { - case let .quantity(value, unitCode): - // Same-unit magnitude comparison; a condition without a unit matches any. - // A unit the participant chose (unitOption) takes precedence over the fixed unit. - let taskUnit = responses[task.id].value.quantityValue?.unitCode - ?? config.unitCode ?? (config.unit.base.isEmpty ? nil : config.unit.base) - guard unitCode == nil || unitCode == taskUnit, - let response = responses[task.id].value.numberValue else { - return false - } - return switch `operator` { - case .equal: - response == value - case .notEqual: - response != value - case .lessThan: - response < value - case .greaterThan: - response > value - case .lessThanOrEqual: - response <= value - case .greaterThanOrEqual: - response >= value - } - case .integer(let value): - guard let response = responses[task.id].value.numberValue.flatMap(Int.init(exactly:)) else { - return false - } - return switch `operator` { - case .equal: - response == value - case .notEqual: - response != value - case .lessThan: - response < value - case .greaterThan: - response > value - case .lessThanOrEqual: - response <= value - case .greaterThanOrEqual: - response >= value - } - case .decimal(let value): - guard let response = responses[task.id].value.numberValue else { - return false - } - return switch `operator` { - case .equal: - response == value - case .notEqual: - response != value - case .lessThan: - response < value - case .greaterThan: - response > value - case .lessThanOrEqual: - response <= value - case .greaterThanOrEqual: - response >= value - } - case .bool, .date, .string, .SCMCOption: - // invalid match - return false - } - case .fileAttachment: - return false - case let .custom(questionKind, config): - let response = responses[taskId].value - return questionKind.evaluateResponseValueComparison( - for: config, - response: response, - operator: `operator`, - value: value - ) + guard ConditionAnswer.compares(value, withAnswersOf: definition.task), ConditionAnswer.compares(`operator`, with: value) else { + return nil } + // An absent or disabled question has no answers. + return `operator` == .notEqual + case .unknown: + return nil + } + let task = resolved.task + let response = resolved.responses.responses[task.id].value + if case let .custom(questionKind, config) = task.kind.variant { + return questionKind.evaluateResponseValueComparison( + for: config, + response: response, + operator: `operator`, + value: value + ) } + guard ConditionAnswer.compares(value, withAnswersOf: task), ConditionAnswer.compares(`operator`, with: value) else { + return nil + } + return ConditionAnswer.answers(of: response, for: task).satisfy(`operator`, value) } } @@ -483,3 +354,79 @@ extension QuestionKindDefinition { ) } } + + +@available(iOS 18, macOS 15, watchOS 11, *) +extension QuestionnaireResponses { + /// Every occurrence of `taskId` among `tasks` and their follow-up containers, in document order; `nil` if whether + /// a follow-up container occurs is open. + /// + /// - parameter visited: The task ids on the evaluation stack, for deciding whether a choice task is enabled. + /// - parameter currentPath: The rest of the path of the container a condition is evaluated in. A custom kind's + /// container on it occurs also while it holds no responses. + private static func occurrences( // swiftlint:disable:this function_parameter_count cyclomatic_complexity function_body_length + of taskId: Questionnaire.Task.ID, + in tasks: [Questionnaire.Task], + container: QuestionnaireResponses, + position: [Int], + currentPath: [ResponsePathComponent], + visited: Set + ) -> [ResolvedTask]? { // swiftlint:disable:this discouraged_optional_collection + var occurrences: [ResolvedTask] = [] + for (index, task) in tasks.enumerated() { + let taskPosition = position + [index] + if task.id == taskId { + occurrences.append(.init(task: task, responses: container, position: taskPosition)) + } + // Only follow-up containers that can hold the task are searched. + guard Self.contains(taskId, in: task.kind.followUpTasks) else { + continue + } + // The follow-up tasks of a disabled task, or of one without a follow-up container, occur once beneath it + // without answers. That occurrence sorts before every follow-up container of the task. + let answerless = ResolvedTask( + task: Self.task(taskId, in: task.kind.followUpTasks) ?? task, + responses: container, + position: taskPosition + [-1], + isAnswerless: true + ) + switch container.enablement(of: task, visited: visited) { + case true?: break + case false?: + occurrences.append(answerless) + continue + // Whether the follow-up tasks occur is open, as on a cycle through the task's own condition. + case nil: return nil + } + var currentOptionId: Questionnaire.Task.Kind.ChoiceConfig.Option.ID? + if currentPath.count >= 2, case .task(task.id) = currentPath[0], case .choiceOption(let optionId) = currentPath[1] { + currentOptionId = optionId + } + var optionIds = Self.followUpContainers(of: task, in: container) + if case .custom = task.kind.variant, let currentOptionId, !optionIds.contains(currentOptionId) { + optionIds.append(currentOptionId) + } + guard !optionIds.isEmpty else { + occurrences.append(answerless) + continue + } + for optionId in optionIds { + guard let containerIndex = Self.followUpContainerIndex(of: optionId, of: task, in: container) else { + continue + } + guard let nested = Self.occurrences( + of: taskId, + in: task.kind.followUpTasks, + container: container.view(appending: ResponsesPath().appending(taskId: task.id).appending(choiceOption: optionId)), + position: taskPosition + [containerIndex], + currentPath: optionId == currentOptionId ? Array(currentPath.dropFirst(2)) : [], + visited: visited + ) else { + return nil + } + occurrences += nested + } + } + return occurrences + } +} diff --git a/Sources/GroveQuestionnaire/Model/QuestionnaireResponses+FollowUpContainers.swift b/Sources/GroveQuestionnaire/Model/QuestionnaireResponses+FollowUpContainers.swift new file mode 100644 index 000000000..fcd2d12e9 --- /dev/null +++ b/Sources/GroveQuestionnaire/Model/QuestionnaireResponses+FollowUpContainers.swift @@ -0,0 +1,86 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +/// The follow-up containers of tasks, in the order the enablement conditions read them. +@available(iOS 18, macOS 15, watchOS 11, *) +extension QuestionnaireResponses { + /// The follow-up container that stands for the free-text answer of an open choice. + /// + /// No option has this id, so the container holds no responses. An exported response carries the free-text + /// answer after the selected options, and its follow-up items occur beneath it without answers. + static let freeTextContainerId = "\u{1F}free-text" + + /// The follow-up containers of `task` in `container`, in document order. + /// + /// A choice task has one for every selected option, in the order of the options, and a last one for a + /// free-text answer. A custom kind keeps its follow-up responses under option ids of its own; they are + /// taken in the order of their ids. + static func followUpContainers( + of task: Questionnaire.Task, + in container: QuestionnaireResponses + ) -> [Questionnaire.Task.Kind.ChoiceConfig.Option.ID] { + switch task.kind.variant { + case .choice(let config): + let choice = container.responses[task.id].value.choiceValue + return config.options.map(\.id).filter { choice.selectedOptions.contains($0) } + + (choice.freeTextOtherResponse == nil ? [] : [freeTextContainerId]) + case .custom: + let optionIds = container.responses[task.id].nestedResponses.keys.map { identifier in + switch identifier { + case .choiceOption(let optionId): + optionId + } + } + return optionIds.sorted() + case .instructional, .boolean, .freeText, .dateTime, .numeric, .fileAttachment: + return [] + } + } + + /// The document position of the follow-up container `optionId` of `task` among all its containers. + /// + /// A choice task orders its containers by its options, also those not selected, followed by the free-text + /// container. A custom kind orders them by option id: a stored container `i` is at `2 * i`, and a container + /// without stored responses, such as the one a condition is evaluated in, falls between them. + static func followUpContainerIndex( + of optionId: Questionnaire.Task.Kind.ChoiceConfig.Option.ID, + of task: Questionnaire.Task, + in container: QuestionnaireResponses + ) -> Int? { + switch task.kind.variant { + case .choice(let config): + return optionId == freeTextContainerId ? config.options.count : config.options.firstIndex { $0.id == optionId } + case .custom: + let stored = followUpContainers(of: task, in: container) + if let index = stored.firstIndex(of: optionId) { + return 2 * index + } + return 2 * stored.count { $0 < optionId } - 1 + case .instructional, .boolean, .freeText, .dateTime, .numeric, .fileAttachment: + return nil + } + } + + /// The task with `taskId` among `tasks` or their follow-up tasks, at any depth. + static func task(_ taskId: Questionnaire.Task.ID, in tasks: [Questionnaire.Task]) -> Questionnaire.Task? { + for task in tasks { + if task.id == taskId { + return task + } + if let found = Self.task(taskId, in: task.kind.followUpTasks) { + return found + } + } + return nil + } + + /// Whether `taskId` is one of `tasks` or of their follow-up tasks, at any depth. + static func contains(_ taskId: Questionnaire.Task.ID, in tasks: [Questionnaire.Task]) -> Bool { + tasks.contains { $0.id == taskId || contains(taskId, in: $0.kind.followUpTasks) } + } +} diff --git a/Sources/GroveQuestionnaireFHIR/ChoiceOptionResolver.swift b/Sources/GroveQuestionnaireFHIR/ChoiceOptionResolver.swift index f7922edf0..f975074c9 100644 --- a/Sources/GroveQuestionnaireFHIR/ChoiceOptionResolver.swift +++ b/Sources/GroveQuestionnaireFHIR/ChoiceOptionResolver.swift @@ -13,8 +13,8 @@ import GroveQuestionnaire /// Resolves a FHIR Coding against the closed options on one questionnaire item. /// /// A system-qualified Coding is always an exact `(system, code)` match. A Coding that -/// genuinely omits `system` may use code-only matching, but only when that code identifies -/// exactly one option. Picking the first suffix match would make option order change clinical +/// genuinely omits `system` is the option without a system and that code, and otherwise may use +/// code-only matching, but only when that code identifies exactly one option. Picking the first suffix match would make option order change clinical /// meaning when two code systems reuse the same code. @available(iOS 18, macOS 15, watchOS 11, *) enum ChoiceOptionResolver { @@ -37,14 +37,19 @@ enum ChoiceOptionResolver { $0.fhirCoding?.system == system && $0.fhirCoding?.code == code } } - return try codeOnly(code, in: options) + // A coding without a system is the option without a system, or otherwise a code-only input. + return try options.first { $0.id == code } ?? codeOnly(code, in: options) } /// Resolves a native option token. A token containing `|` is already qualified and - /// therefore only matches an exact option id. A bare token is a code-only input. + /// therefore only matches an exact option id. A bare token is the id of an option without + /// a system, or otherwise a code-only input. static func token(_ token: String, in options: [Option]) throws -> Option? { + if let option = options.first(where: { $0.id == token }) { + return option + } guard !token.contains("|") else { - return options.first { $0.id == token } + return nil } return try codeOnly(token, in: options) } diff --git a/Sources/GroveQuestionnaireFHIR/PairRules+AnswerValues.swift b/Sources/GroveQuestionnaireFHIR/PairRules+AnswerValues.swift index b60b1d8c5..7c6a74f58 100644 --- a/Sources/GroveQuestionnaireFHIR/PairRules+AnswerValues.swift +++ b/Sources/GroveQuestionnaireFHIR/PairRules+AnswerValues.swift @@ -8,6 +8,7 @@ import CoreFoundation import Foundation +import GroveQuestionnaire @available(iOS 18, macOS 15, watchOS 11, *) @@ -29,6 +30,37 @@ extension PairRules { return value } + /// Warns about every enableWhen `answerCoding` and every `answerOption` coding without a system. + /// + /// A coding without a system matches only an answer coding without a system, so such a condition + /// or option rarely means what its author intended. + static func validateCodingSystems(_ items: [FHIRJSONObject], path: String, issues: inout [ValidationIssue]) { + for (index, item) in items.enumerated() { + let itemPath = "\(path)[\(index)]" + for (conditionIndex, condition) in (item["enableWhen"] as? [FHIRJSONObject] ?? []).enumerated() { + if let coding = condition["answerCoding"] as? FHIRJSONObject, coding["system"] == nil { + issues.append(.init( + severity: .warning, + code: .codingSystem, + path: "\(itemPath).enableWhen[\(conditionIndex)].answerCoding", + message: "The enableWhen coding has no system, so it matches only answers without a system." + )) + } + } + for (optionIndex, option) in (item["answerOption"] as? [FHIRJSONObject] ?? []).enumerated() { + if let coding = option["valueCoding"] as? FHIRJSONObject, coding["system"] == nil { + issues.append(.init( + severity: .warning, + code: .codingSystem, + path: "\(itemPath).answerOption[\(optionIndex)].valueCoding", + message: "The answer option coding has no system, so only enableWhen codings without a system match it." + )) + } + } + validateCodingSystems(item["item"] as? [FHIRJSONObject] ?? [], path: "\(itemPath).item", issues: &issues) + } + } + static func questionnaireAnswerValues(_ response: FHIRJSONObject) -> [String: [Any]] { var values: [String: [Any]] = [:] collectResponseValues( @@ -103,15 +135,6 @@ extension PairRules { } } - /// A systemless enableWhen coding names a code in any system, as it does in the form's condition engine. - /// Answer-option membership still uses exact coding identity through `valuesEqual`. - static func enableWhenMatches(_ value: Any, expected: Any) -> Bool { - if let expectedCoding = codingKey(expected), expectedCoding.system == nil { - return codingKey(value)?.code == expectedCoding.code - } - return valuesEqual(value, expected) - } - // Tri-state: nil means the answer families or quantity units are incomparable. // swiftlint:disable:next discouraged_optional_boolean static func lessThanOrEqual(_ left: Any, _ right: Any) -> Bool? { @@ -130,22 +153,6 @@ extension PairRules { return nil } - static func compare(_ left: Any, _ right: Any) -> ComparisonResult? { - if let left = decimal(left), let right = decimal(right) { - if left < right { - return .orderedAscending - } - if left > right { - return .orderedDescending - } - return .orderedSame - } - if let left = left as? String, let right = right as? String { - return left.compare(right) - } - return nil - } - // Tri-state: nil means the JSON value is not a FHIR boolean. // swiftlint:disable:next discouraged_optional_boolean static func boolean(_ value: Any?) -> Bool? { @@ -169,15 +176,25 @@ extension PairRules { return integer } + /// The value of a JSON number; `nil` for any other JSON value, a numeric string included. + /// + /// JSON parsing reads a number with up to 17 significant digits into the nearest `Double`, whose + /// `stringValue` can carry rounding digits (`79.9` reads as `79.90000000000001`), so such a number is + /// read back through its shortest digits. These are the written digits for up to 15 significant digits, + /// and can differ from them for 16 or 17. A number with more digits parses into an exact `NSDecimalNumber`. static func decimal(_ value: Any?) -> Decimal? { + if let number = value as? NSDecimalNumber { + return number.decimalValue + } if let number = value as? NSNumber { guard CFGetTypeID(number) != CFBooleanGetTypeID() else { return nil } - return Decimal(string: number.stringValue, locale: Locale(identifier: "en_US_POSIX")) - } - if let string = value as? String { - return Decimal(string: string, locale: Locale(identifier: "en_US_POSIX")) + let digits = number.stringValue + if digits.contains(where: { $0 == "." || $0 == "e" || $0 == "E" }) { + return Decimal(shortestDigitsOf: number.doubleValue) + } + return Decimal(string: digits, locale: Locale(identifier: "en_US_POSIX")) } return nil } diff --git a/Sources/GroveQuestionnaireFHIR/PairRules+Conditions.swift b/Sources/GroveQuestionnaireFHIR/PairRules+Conditions.swift new file mode 100644 index 000000000..723386683 --- /dev/null +++ b/Sources/GroveQuestionnaireFHIR/PairRules+Conditions.swift @@ -0,0 +1,327 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +import Foundation + + +/// A FHIR `date`, `dateTime` or `time` value with the precision its text states. +@available(iOS 18, macOS 15, watchOS 11, *) +struct PairTemporal: Equatable { + /// Year, month and day, as far as the value states them. Empty for a time. + let date: [Int] + /// Seconds since 1970-01-01T00:00:00Z for a date-time with a time, or seconds since midnight for a time. + let seconds: Int? + /// Digits after the decimal point, without trailing zeros. + let fraction: String + + /// `YYYY`, `YYYY-MM` or `YYYY-MM-DD`. + static func date(_ text: String) -> Self? { + let parts = text.split(separator: "-", omittingEmptySubsequences: false).map(String.init) + guard (1...3).contains(parts.count), + parts[0].count == 4, + parts.dropFirst().allSatisfy({ $0.count == 2 }), + let values = digits(parts), + isValidDate(values) else { + return nil + } + return Self(date: values, seconds: nil, fraction: "") + } + + /// A partial date, or a full date with a time of day and a time zone. + static func dateTime(_ text: String) -> Self? { + guard let separator = text.firstIndex(of: "T") else { + return date(text) + } + guard let day = date(String(text[.. Self? { + let parts = text.split(separator: ":", omittingEmptySubsequences: false).map(String.init) + guard parts.count == 3, parts[0].count == 2, parts[1].count == 2, + let clock = digits([parts[0], parts[1]]), clock[0] < 24, clock[1] < 60, + let seconds = fractionalSeconds(parts[2]) else { + return nil + } + return Self(date: [], seconds: clock[0] * 3_600 + clock[1] * 60 + seconds.whole, fraction: seconds.fraction) + } + + private static func digits(_ parts: [String]) -> [Int]? { // swiftlint:disable:this discouraged_optional_collection + let values = parts.compactMap { part in part.allSatisfy { $0.isASCII && $0.isNumber } ? Int(part) : nil } + return values.count == parts.count ? values : nil + } + + private static func fractionalSeconds(_ text: String) -> (whole: Int, fraction: String)? { + let parts = text.split(separator: ".", omittingEmptySubsequences: false).map(String.init) + guard (1...2).contains(parts.count), parts[0].count == 2, + parts.allSatisfy({ !$0.isEmpty && $0.allSatisfy { $0.isASCII && $0.isNumber } }), + let whole = Int(parts[0]), whole <= 60 else { + return nil + } + let fraction = parts.dropFirst().first ?? "" + let end = fraction.lastIndex { $0 != "0" }.map { fraction.index(after: $0) } ?? fraction.startIndex + return (whole, String(fraction[.. Int? { + if text == "Z" { + return 0 + } + let sign = text.first == "-" ? -1 : 1 + let parts = text.dropFirst().split(separator: ":", omittingEmptySubsequences: false).map(String.init) + guard text.first == "+" || text.first == "-", parts.count == 2, parts.allSatisfy({ $0.count == 2 }), + let values = digits(parts), values[1] < 60, values[0] * 60 + values[1] <= 14 * 60 else { + return nil + } + return sign * (values[0] * 3_600 + values[1] * 60) + } + + private static func isValidDate(_ values: [Int]) -> Bool { + guard values[0] >= 1 else { + return false + } + guard values.count > 1 else { + return true + } + guard (1...12).contains(values[1]) else { + return false + } + guard values.count > 2 else { + return true + } + let leap = values[0].isMultiple(of: 4) && (!values[0].isMultiple(of: 100) || values[0].isMultiple(of: 400)) + let lengths = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + return (1...lengths[values[1] - 1]).contains(values[2]) + } + + /// Days from 1970-01-01 in the proleptic Gregorian calendar. + private static func daysSinceEpoch(year: Int, month: Int, day: Int) -> Int { + let shiftedYear = month <= 2 ? year - 1 : year + let era = (shiftedYear >= 0 ? shiftedYear : shiftedYear - 399) / 400 + let yearOfEra = shiftedYear - era * 400 + let dayOfYear = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + day - 1 + let dayOfEra = yearOfEra * 365 + yearOfEra / 4 - yearOfEra / 100 + dayOfYear + return era * 146_097 + dayOfEra - 719_468 + } + + /// The order of two values; values that agree down to the coarser precision of the two have no order. + func compare(to other: Self) -> ComparisonResult? { + if let seconds, let otherSeconds = other.seconds { + return seconds == otherSeconds ? PairCondition.order(fraction, other.fraction) : PairCondition.order(seconds, otherSeconds) + } + for (left, right) in zip(date, other.date) where left != right { + return PairCondition.order(left, right) + } + return date.count == other.date.count && seconds == nil && other.seconds == nil ? .orderedSame : nil + } +} + + +/// An answer or enableWhen value, read by its FHIR type, as enableWhen compares it. +@available(iOS 18, macOS 15, watchOS 11, *) +enum PairCondition { + case boolean(Bool) + case number(Decimal) + case string(String) + case uri(String) + case coding(system: String?, code: String?) + case quantity(Quantity) + case temporal(PairTemporal, isTime: Bool) + case reference(String?) + /// A value enableWhen does not compare, such as an attachment. + case other + + /// The order of an answer relative to an enableWhen value. + enum Ordering { + case ordered(ComparisonResult) + /// The values could have an order, but their precision, unit or comparator leaves it open. + case unknown + /// The values are of different kinds and have no order. + case incomparable + } + + struct Quantity { + let value: Decimal? + let comparator: String? + let system: String? + let code: String? + let unit: String? + + /// The order of the quantity relative to a threshold. Units are not converted: a quantity in another + /// unit, or a bounded quantity, has no known order. + func order(comparedTo threshold: Self) -> Ordering { + let sameUnit: Bool + if let thresholdCode = threshold.code { + sameUnit = code == thresholdCode && (threshold.system == nil || system == threshold.system) + } else if let thresholdUnit = threshold.unit { + sameUnit = unit == thresholdUnit + } else { + // A threshold without a unit orders only quantities without a unit. + sameUnit = code == nil && unit == nil + } + guard sameUnit, comparator == nil, let value, let thresholdValue = threshold.value else { + return .unknown + } + return .ordered(PairCondition.order(value, thresholdValue)) + } + } + + /// Reads a `value[x]` or `answer[x]` element by the type its key names. + init?(key: String, value: Any) { // swiftlint:disable:this cyclomatic_complexity + let type = key.hasPrefix("value") ? key.dropFirst("value".count) : key.dropFirst("answer".count) + switch type { + case "Boolean": + guard let value = PairRules.boolean(value) else { + return nil + } + self = .boolean(value) + case "Decimal", "Integer": + guard let value = PairRules.decimal(value) else { + return nil + } + self = .number(value) + case "String", "Uri": + guard let value = value as? String else { + return nil + } + self = type == "Uri" ? .uri(value) : .string(value) + case "Date", "DateTime", "Time": + guard let text = value as? String, + let temporal = type == "Time" ? PairTemporal.time(text) : PairTemporal.dateTime(text) else { + return nil + } + self = .temporal(temporal, isTime: type == "Time") + case "Coding": + guard let coding = value as? FHIRJSONObject else { + return nil + } + self = .coding(system: coding["system"] as? String, code: coding["code"] as? String) + case "Quantity": + guard let quantity = value as? FHIRJSONObject else { + return nil + } + self = .quantity(Quantity( + value: PairRules.decimal(quantity["value"]), + comparator: quantity["comparator"] as? String, + system: quantity["system"] as? String, + code: quantity["code"] as? String, + unit: quantity["unit"] as? String + )) + case "Reference": + self = .reference((value as? FHIRJSONObject)?["reference"] as? String) + default: + self = .other + } + } + + static func order(_ left: Value, _ right: Value) -> ComparisonResult { + left < right ? .orderedAscending : left > right ? .orderedDescending : .orderedSame + } + + /// The outcome of one enableWhen operator over the answers; `nil` when it is unknown. + /// + /// `!=` holds when no answer equals the value, so also without an answer; every other operator holds when + /// at least one answer satisfies it. + static func test(_ operation: String, expected: Self, answers: [Self]) -> Bool? { // swiftlint:disable:this discouraged_optional_boolean + switch operation { + case "exists": + guard case .boolean(let value) = expected else { + return nil + } + return answers.isEmpty != value + case "=": + return any(answers.map { $0.equals(expected) }) + case "!=": + return any(answers.map { $0.equals(expected) }).map { !$0 } + case ">", "<", ">=", "<=": + // Only numbers, dates and times, and quantities have an order. + switch expected { + case .number, .temporal, .quantity: + return any(answers.map { $0.satisfies(operation, expected) }) + default: + return nil + } + default: + return nil + } + } + + /// True if any outcome is true, unknown if none is true and any is unknown, and false otherwise. + static func any(_ outcomes: [Bool?]) -> Bool? { // swiftlint:disable:this discouraged_optional_boolean + outcomes.contains(true) ? true : outcomes.contains(nil) ? nil : false + } + + /// False if any outcome is false, unknown if none is false and any is unknown, and true otherwise. + static func all(_ outcomes: [Bool?]) -> Bool? { // swiftlint:disable:this discouraged_optional_boolean + outcomes.contains(false) ? false : outcomes.contains(nil) ? nil : true + } + + /// Whether the answer equals the enableWhen value; `nil` when equality is unknown. Values of different kinds + /// are not equal, and a coding equals another only when system and code are both equal. + func equals(_ expected: Self) -> Bool? { // swiftlint:disable:this discouraged_optional_boolean + switch (self, expected) { + case let (.boolean(answer), .boolean(value)): + return answer == value + case let (.string(answer), .string(value)), let (.uri(answer), .uri(value)): + // Strings are equal when their characters are, without Unicode normalization. + return answer.utf8.elementsEqual(value.utf8) + case let (.coding(system, code), .coding(expectedSystem, expectedCode)): + guard let code, let expectedCode else { + return false + } + return code == expectedCode && system == expectedSystem + case let (.reference(answer), .reference(value)): + return answer != nil && answer == value + default: + switch order(comparedTo: expected) { + case .ordered(let result): return result == .orderedSame + case .unknown: return nil + case .incomparable: return false + } + } + } + + func order(comparedTo expected: Self) -> Ordering { + switch (self, expected) { + case let (.number(answer), .number(value)): + .ordered(Self.order(answer, value)) + case let (.temporal(answer, answerIsTime), .temporal(value, valueIsTime)) where answerIsTime == valueIsTime: + answer.compare(to: value).map(Ordering.ordered) ?? .unknown + case let (.quantity(answer), .quantity(threshold)): + answer.order(comparedTo: threshold) + default: + .incomparable + } + } + + /// Whether the answer satisfies an ordered operator; `nil` when its order is unknown. + private func satisfies(_ operation: String, _ expected: Self) -> Bool? { // swiftlint:disable:this discouraged_optional_boolean + switch order(comparedTo: expected) { + case .ordered(let result): + switch operation { + case ">": result == .orderedDescending + case "<": result == .orderedAscending + case ">=": result != .orderedAscending + default: result != .orderedDescending + } + case .unknown: nil + case .incomparable: false + } + } +} diff --git a/Sources/GroveQuestionnaireFHIR/PairRules+EnableWhenRules.swift b/Sources/GroveQuestionnaireFHIR/PairRules+EnableWhenRules.swift new file mode 100644 index 000000000..22ad85a04 --- /dev/null +++ b/Sources/GroveQuestionnaireFHIR/PairRules+EnableWhenRules.swift @@ -0,0 +1,131 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +import Foundation + + +/// The `enableWhen` conditions of a Questionnaire that can be evaluated, and the items that depend on themselves. +@available(iOS 18, macOS 15, watchOS 11, *) +struct PairEnableWhenRules { + /// One condition that can be evaluated. + struct Rule { + let question: String + let operation: String + let expected: PairCondition + } + + private static let operators: Set = ["exists", "=", "!=", ">", "<", ">=", "<="] + private static let orderedKinds: Set = ["Decimal", "Integer", "Date", "DateTime", "Time", "Quantity"] + /// The option kinds a condition on a choice compares. Reference answers are outside the exchange contract, + /// so a condition with an `answerReference` cannot be evaluated. + private static let optionKinds: Set = ["Coding", "String", "Integer", "Date", "Time"] + /// The `answer[x]` types a condition other than `exists` compares with the answers of each answerable item type. + private static let conditionKinds: [String: Set] = [ + "boolean": ["Boolean"], "decimal": ["Decimal", "Integer"], "integer": ["Decimal", "Integer"], "date": ["Date"], + "dateTime": ["DateTime"], "time": ["Time"], "string": ["String"], "text": ["String"], "url": [], "choice": optionKinds, + "open-choice": optionKinds, "attachment": [], "quantity": ["Quantity"] + ] + + /// The type of each item, by its linkId, for linkIds that only one item uses. + private let types: [String: String] + /// The linkIds of the items whose enablement depends on itself, through conditions or enclosing items. + private(set) var cyclic: Set = [] + + init(definitions: [FHIRJSONObject]) { + var seen: Set = [] + var duplicates: Set = [] + var types: [String: String] = [:] + var parents: [String: String] = [:] + var all: [FHIRJSONObject] = [] + var pending = definitions.map { (item: $0, parent: String?.none) } + while !pending.isEmpty { + let (item, parent) = pending.removeFirst() + all.append(item) + let linkID = item["linkId"] as? String + if let linkID { + if !seen.insert(linkID).inserted { + duplicates.insert(linkID) + } + types[linkID] = item["type"] as? String ?? "" + parents[linkID] = parent + } + pending += (item["item"] as? [FHIRJSONObject] ?? []).map { ($0, linkID) } + } + for duplicate in duplicates { + types.removeValue(forKey: duplicate) + } + self.types = types + var dependencies: [String: Set] = [:] + for item in all { + guard let linkID = item["linkId"] as? String else { + continue + } + // Conditions that cannot be evaluated never close a cycle. + let questions = (item["enableWhen"] as? [FHIRJSONObject] ?? []).compactMap { rule($0)?.question } + dependencies[linkID, default: []].formUnion(questions + (parents[linkID].map { [$0] } ?? [])) + } + cyclic = Set(dependencies.keys.filter { start in + var visited: Set = [] + var pending = Array(dependencies[start] ?? []) + while let next = pending.popLast() { + if next == start { + return true + } + if visited.insert(next).inserted { + pending += dependencies[next] ?? [] + } + } + return false + }) + } + + /// The item's conditions, each `nil` when it cannot be evaluated; `nil` when the item's enablement is invalid. + /// + /// A condition cannot be evaluated when it names no item, an item that several items share the linkId of, + /// or an item without answers; when its operator is not an R4 operator; or when its answer is missing, + /// incomplete, of a type the question's answers do not have, or without an order for an ordered operator. + /// An item with several conditions must state `enableBehavior` as `all` or `any`. + func rules(of definition: FHIRJSONObject) -> [Rule?]? { // swiftlint:disable:this discouraged_optional_collection + let conditions = definition["enableWhen"] as? [FHIRJSONObject] ?? [] + let behavior = definition["enableBehavior"] as? String + guard behavior == nil ? conditions.count <= 1 : ["all", "any"].contains(behavior) else { + return nil + } + return conditions.map(rule) + } + + private func rule(_ condition: FHIRJSONObject) -> Rule? { + let answers = condition.filter { $0.key.hasPrefix("answer") } + guard let question = condition["question"] as? String, + let type = types[question], Self.conditionKinds[type] != nil, + let operation = condition["operator"] as? String, Self.operators.contains(operation), + answers.count == 1, let answer = answers.first, + let expected = PairCondition(key: answer.key, value: answer.value) else { + return nil + } + let kind = String(answer.key.dropFirst("answer".count)) + if operation == "exists" { + guard kind == "Boolean" else { + return nil + } + return Rule(question: question, operation: operation, expected: expected) + } + guard Self.conditionKinds[type]?.contains(kind) == true, + ["=", "!="].contains(operation) || Self.orderedKinds.contains(kind) else { + return nil + } + switch expected { + case .coding(_, nil), .reference(nil): + return nil + case .quantity(let quantity) where quantity.value == nil || quantity.comparator != nil: + return nil + default: + return Rule(question: question, operation: operation, expected: expected) + } + } +} diff --git a/Sources/GroveQuestionnaireFHIR/PairRules+Expressions.swift b/Sources/GroveQuestionnaireFHIR/PairRules+Expressions.swift index 7f0b0125d..aa2ea65aa 100644 --- a/Sources/GroveQuestionnaireFHIR/PairRules+Expressions.swift +++ b/Sources/GroveQuestionnaireFHIR/PairRules+Expressions.swift @@ -8,9 +8,6 @@ import Foundation -// Expression shape and execution paths deliberately preserve tri-state evaluation. -// swiftlint:disable cyclomatic_complexity discouraged_optional_boolean - @available(iOS 18, macOS 15, watchOS 11, *) extension PairRules { static func validateItemExpressionShapes( @@ -187,57 +184,6 @@ extension PairRules { @available(iOS 18, macOS 15, watchOS 11, *) extension PairContext { - // Core enableWhen has one explicit branch for every R4 operator. - // swiftlint:disable:next cyclomatic_complexity - func evaluateEnableWhen(_ definition: FHIRJSONObject) -> Bool? { - let conditions = definition["enableWhen"] as? [FHIRJSONObject] ?? [] - guard !conditions.isEmpty else { - return true - } - var outcomes: [Bool] = [] - for condition in conditions { - let values = allAnswers[condition["question"] as? String ?? ""] ?? [] - let expected = condition.filter { $0.key.hasPrefix("answer") } - guard expected.count == 1, let expectedValue = expected.first?.value else { - return nil - } - switch condition["operator"] as? String { - case "exists": - guard let expected = PairRules.boolean(expectedValue) else { - return nil - } - outcomes.append((!values.isEmpty) == expected) - case "=": - outcomes.append(values.contains { PairRules.enableWhenMatches($0, expected: expectedValue) }) - case "!=": - outcomes.append(values.contains { !PairRules.enableWhenMatches($0, expected: expectedValue) }) - case ">", "<", ">=", "<=": - guard let operation = condition["operator"] as? String else { - return nil - } - var comparisons: [Bool] = [] - for value in values { - guard let comparison = PairRules.compare(value, expectedValue) else { - return nil - } - let outcome = switch operation { - case ">": comparison == .orderedDescending - case "<": comparison == .orderedAscending - case ">=": comparison != .orderedAscending - default: comparison != .orderedDescending - } - comparisons.append(outcome) - } - outcomes.append(comparisons.contains(true)) - default: - return nil - } - } - return definition["enableBehavior"] as? String == "any" - ? outcomes.contains(true) - : outcomes.allSatisfy { $0 } - } - mutating func requireTargetConstraintEvaluation( in element: FHIRJSONObject, path: String diff --git a/Sources/GroveQuestionnaireFHIR/PairRules+Occurrences.swift b/Sources/GroveQuestionnaireFHIR/PairRules+Occurrences.swift new file mode 100644 index 000000000..164873b31 --- /dev/null +++ b/Sources/GroveQuestionnaireFHIR/PairRules+Occurrences.swift @@ -0,0 +1,243 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +import Foundation + + +/// Every item instance of a response, in document order, with the enablement `enableWhen` gives it. +/// +/// The response holds an instance of each Questionnaire item wherever the item can appear, also where the +/// response omits it: once in every instance of an enclosing group, and once beneath every answer of an +/// enclosing question, or once if that question has no answer. A condition thereby reads the instance +/// a participant sees. +@available(iOS 18, macOS 15, watchOS 11, *) +struct PairOccurrences { + struct Occurrence { + let definition: FHIRJSONObject + let linkID: String + let parent: Int? + let answers: [PairCondition] + /// `.`, the path an item's expressions are evaluated at. + let expressionPath: String + } + + /// The answer values a condition compares with an answer of a choice item, beyond `answerTypes`. + /// + /// They are the `answerOption.value[x]` types. An answer of such a type is reported as an `answerType` + /// issue, and still counts for enablement, so that a condition with one of these types can be met. + private static let conditionAnswerTypes: [String: Set] = [ + "choice": ["valueString", "valueInteger", "valueDate", "valueTime"], + "open-choice": ["valueInteger", "valueDate", "valueTime"] + ] + + private(set) var occurrences: [Occurrence] = [] + private var byLinkID: [String: [Int]] = [:] + /// The occurrence at each response item path, and at `.` for an item the response omits. + private(set) var byPath: [String: Int] = [:] + /// The outcome of each occurrence's own core `enableWhen`; `nil` when it cannot be evaluated. + private(set) var conditionStates: [Bool?] = [] // swiftlint:disable:this discouraged_optional_boolean + /// Whether each occurrence is enabled, by its enclosing items and its own enablement; `nil` when unknown. + private var states: [Bool?] = [] // swiftlint:disable:this discouraged_optional_boolean + private var evaluated: [Bool] = [] + private var evaluating: Set = [] + private let rules: PairEnableWhenRules + private let expressionEnablement: (FHIRJSONObject, String) -> Bool? // swiftlint:disable:this discouraged_optional_boolean + + /// - parameter expressionEnablement: The outcome of an item definition's `enableWhenExpression` at a path, + /// `nil` when it cannot be evaluated. + init( + definitions: [FHIRJSONObject], + response: FHIRJSONObject, + expressionEnablement: @escaping (FHIRJSONObject, String) -> Bool? // swiftlint:disable:this discouraged_optional_boolean + ) { + self.expressionEnablement = expressionEnablement + rules = PairEnableWhenRules(definitions: definitions) + place( + definitions, + responses: response["item"] as? [FHIRJSONObject] ?? [], + parent: nil, + path: "QuestionnaireResponse.item" + ) + conditionStates = Array(repeating: nil, count: occurrences.count) + states = Array(repeating: nil, count: occurrences.count) + evaluated = Array(repeating: false, count: occurrences.count) + for index in occurrences.indices { + _ = state(of: index) + } + } + + /// The answer values that count: those of a type the item's answers have, and only the first unless the item repeats. + private static func values(of answers: [FHIRJSONObject], for definition: FHIRJSONObject, repeats: Bool) -> [PairCondition] { + let type = definition["type"] as? String ?? "" + let keys = (PairRules.answerTypes[type] ?? []).union(conditionAnswerTypes[type] ?? []) + let values = answers.compactMap { answer in + PairRules.answerValue(answer).flatMap { keys.contains($0.key) ? PairCondition(key: $0.key, value: $0.value) : nil } + } + return repeats ? values : Array(values.prefix(1)) + } + + /// The instance of `linkID` that a condition of the occurrence reads. + /// + /// Follows FHIR R4 `Questionnaire.item.enableWhen.question`: the nearest occurrence on the ancestor axis, + /// then on the preceding axis, then on the following axis. A condition never reads its own item. + private func source(of linkID: String, from occurrence: Int) -> Int? { + guard occurrences[occurrence].linkID != linkID else { + return nil + } + var ancestor = occurrences[occurrence].parent + while let index = ancestor { + if occurrences[index].linkID == linkID { + return index + } + ancestor = occurrences[index].parent + } + let candidates = byLinkID[linkID] ?? [] + return candidates.last { $0 < occurrence } + ?? candidates.first { $0 > occurrence && !isDescendant($0, of: occurrence) } + } + + private func isDescendant(_ candidate: Int, of occurrence: Int) -> Bool { + var parent = occurrences[candidate].parent + while let index = parent { + if index == occurrence { + return true + } + parent = occurrences[index].parent + } + return false + } + + /// Whether the occurrence is enabled. An occurrence on the evaluation stack forms a reference cycle and is unknown. + private mutating func state(of index: Int) -> Bool? { // swiftlint:disable:this discouraged_optional_boolean + if evaluated[index] { + return states[index] + } + guard evaluating.insert(index).inserted else { + return nil + } + defer { + evaluating.remove(index) + } + let enclosing = occurrences[index].parent.map { state(of: $0) } ?? true + guard !rules.cyclic.contains(occurrences[index].linkID) else { + // An item that depends on itself has no enablement of its own; a disabled enclosing item still disables it. + let enablement = PairCondition.all([enclosing, nil]) + states[index] = enablement + evaluated[index] = true + return enablement + } + let condition = conditionState(of: index) + conditionStates[index] = condition + let definition = occurrences[index].definition + let hasExpression = !PairRules.extensions(definition, url: PairRules.URL.enableWhenExpression).isEmpty + let own = hasExpression ? expressionEnablement(definition, occurrences[index].expressionPath) : condition + let enablement = PairCondition.all([enclosing, own]) + states[index] = enablement + evaluated[index] = true + return enablement + } + + /// The outcome of the occurrence's core `enableWhen`. The answers of a disabled question count as absent. + private mutating func conditionState(of index: Int) -> Bool? { // swiftlint:disable:this discouraged_optional_boolean + let definition = occurrences[index].definition + guard let conditions = rules.rules(of: definition) else { + return nil + } + guard !conditions.isEmpty else { + return true + } + let outcomes = conditions.map { rule -> Bool? in // swiftlint:disable:this discouraged_optional_boolean + // A condition on the item itself has no other instance to read. + guard let rule, let source = source(of: rule.question, from: index) else { + return nil + } + let answers = occurrences[source].answers + switch state(of: source) { + case .some(true): + return PairCondition.test(rule.operation, expected: rule.expected, answers: answers) + case .some(false): + return PairCondition.test(rule.operation, expected: rule.expected, answers: []) + case .none: + // The outcome is known when it does not depend on whether the question is enabled. + let withAnswers = PairCondition.test(rule.operation, expected: rule.expected, answers: answers) + let withoutAnswers = PairCondition.test(rule.operation, expected: rule.expected, answers: []) + return withAnswers == withoutAnswers ? withAnswers : nil + } + } + return definition["enableBehavior"] as? String == "any" ? PairCondition.any(outcomes) : PairCondition.all(outcomes) + } + + private mutating func place( + _ definitions: [FHIRJSONObject], + responses: [FHIRJSONObject], + parent: Int?, + path: String + ) { + var found: [String: [(response: FHIRJSONObject, path: String)]] = [:] + for (index, response) in responses.enumerated() { + if let linkID = response["linkId"] as? String { + found[linkID, default: []].append((response, "\(path)[\(index)]")) + } + } + for definition in definitions { + guard let linkID = definition["linkId"] as? String else { + continue + } + let entries = found[linkID] ?? [] + // Only a repeating group has several instances in one container; of a duplicated item, the first counts. + let repeats = definition["repeats"] as? Bool == true + let counted = definition["type"] as? String == "group" && repeats ? entries : Array(entries.prefix(1)) + let instances: [(response: FHIRJSONObject?, path: String)] = counted.isEmpty + ? [(nil, "\(path).\(linkID)")] + : counted.map { ($0.response, $0.path) } + for instance in instances { + let answers = instance.response?["answer"] as? [FHIRJSONObject] ?? [] + let index = occurrences.count + occurrences.append(Occurrence( + definition: definition, + linkID: linkID, + parent: parent, + answers: Self.values(of: answers, for: definition, repeats: repeats), + expressionPath: "\(path).\(linkID)" + )) + byLinkID[linkID, default: []].append(index) + byPath[instance.path] = index + placeChildren(of: definition, instance: instance, answers: answers, parent: index) + } + for duplicate in entries.dropFirst(counted.count) { + byPath[duplicate.path] = byPath[counted[0].path] + } + } + } + + private mutating func placeChildren( + of definition: FHIRJSONObject, + instance: (response: FHIRJSONObject?, path: String), + answers: [FHIRJSONObject], + parent: Int + ) { + let children = definition["item"] as? [FHIRJSONObject] ?? [] + guard !children.isEmpty else { + return + } + if definition["type"] as? String == "group" { + place(children, responses: instance.response?["item"] as? [FHIRJSONObject] ?? [], parent: parent, path: "\(instance.path).item") + } else if answers.isEmpty { + place(children, responses: [], parent: parent, path: "\(instance.path).answer.item") + } else { + for (answerIndex, answer) in answers.enumerated() { + place( + children, + responses: answer["item"] as? [FHIRJSONObject] ?? [], + parent: parent, + path: "\(instance.path).answer[\(answerIndex)].item" + ) + } + } + } +} diff --git a/Sources/GroveQuestionnaireFHIR/PairRules.swift b/Sources/GroveQuestionnaireFHIR/PairRules.swift index bf63e8e95..6b39b6dfa 100644 --- a/Sources/GroveQuestionnaireFHIR/PairRules.swift +++ b/Sources/GroveQuestionnaireFHIR/PairRules.swift @@ -193,11 +193,21 @@ enum PairRules { ) let definitions = questionnaire["item"] as? [FHIRJSONObject] ?? [] + validateCodingSystems(definitions, path: "Questionnaire.item", issues: &issues) var allDefinitionIDs: Set = [] collectDefinitionIDs(definitions, into: &allDefinitionIDs) var context = PairContext( allDefinitionIDs: allDefinitionIDs, allAnswers: questionnaireAnswerValues(response), + occurrences: PairOccurrences(definitions: definitions, response: response) { definition, path in + // An item enabled by an expression is a known source only when the expression evaluates. + guard let expressionEvaluator, + let linkID = definition["linkId"] as? String, + let expression = extensions(definition, url: URL.enableWhenExpression).first.flatMap(expressionString) else { + return nil + } + return try? expressionEvaluator.evaluate(expression, path: path, scope: .item(linkID)) + }, resolver: .init(valueSets: valueSets), completed: completedStatuses.contains(response["status"] as? String ?? ""), expressionEvaluator: expressionEvaluator, @@ -223,6 +233,7 @@ enum PairRules { struct PairContext { let allDefinitionIDs: Set let allAnswers: [String: [Any]] + let occurrences: PairOccurrences let resolver: ValueSetResolver let completed: Bool let expressionEvaluator: PairExpressionEvaluator? @@ -257,7 +268,9 @@ struct PairContext { actual[linkID, default: []].append((response, itemPath)) } - for (linkID, occurrences) in actual where occurrences.count > 1 { + // A repeating group is represented by one response item for each of its instances. + for (linkID, occurrences) in actual where occurrences.count > 1 + && !(expected[linkID]?["type"] as? String == "group" && expected[linkID]?["repeats"] as? Bool == true) { issues.append(.init( code: .itemDuplicate, path: path, @@ -269,7 +282,17 @@ struct PairContext { guard let linkID = definition["linkId"] as? String else { continue } - var enabled = evaluateEnableWhen(definition) + let occurrences = actual[linkID] ?? [] + // Each instance reads the question instances nearest to it, so enablement is evaluated per instance; + // an item the response omits is evaluated where it would appear. + let instancePaths = occurrences.isEmpty ? ["\(path).\(linkID)"] : occurrences.map(\.path) + // A further instance of a non-repeating item is reported as a duplicate and shares the first instance's state. + // The items inside a duplicate instance have no occurrence of their own and are not evaluated. + let instances = instancePaths.map { self.occurrences.byPath[$0] } + let firstIndex = instances.compactMap(\.self).first + var states = instances.map { index in + (index ?? firstIndex).flatMap { self.occurrences.conditionStates[$0] } + } let expressionEnablement = PairRules.extensions( definition, url: PairRules.URL.enableWhenExpression @@ -277,6 +300,7 @@ struct PairContext { if let expressionEnablement, let expression = PairRules.expressionString(from: expressionEnablement) { if let expressionEvaluator { + var enabled: Bool? do { enabled = try expressionEvaluator.evaluate( expression, @@ -284,15 +308,15 @@ struct PairContext { scope: .item(linkID) ) } catch { - enabled = nil issues.append(.init( code: .expressionEvaluation, path: path, message: "enableWhenExpression for '\(linkID)' failed: \(error)" )) } + states = states.map { _ in enabled } } else if completed { - enabled = nil + states = states.map { _ in nil } issues.append(.init( code: .expressionEngineRequired, path: path, @@ -300,21 +324,21 @@ struct PairContext { )) } } - if enabled == nil, completed { + if states.contains(nil), completed, firstIndex != nil { issues.append(.init( code: .enableWhenEvaluation, path: path, message: "Cannot evaluate enableWhen for '\(linkID)'." )) } - let occurrences = actual[linkID] ?? [] - if enabled == false, let first = occurrences.first { + for (occurrence, enabled) in zip(occurrences, states) where enabled == false { issues.append(.init( code: .itemDisabled, - path: first.path, + path: occurrence.path, message: "Disabled item '\(linkID)' must not be present." )) } + let enabled = states[0] if completed, definition["required"] as? Bool == true, enabled == true, @@ -326,7 +350,7 @@ struct PairContext { )) } - for occurrence in occurrences { + for (occurrence, enabled) in zip(occurrences, states) { validateItem( definition: definition, response: occurrence.value, diff --git a/Sources/GroveQuestionnaireFHIR/Questionnaire+FromFHIR.swift b/Sources/GroveQuestionnaireFHIR/Questionnaire+FromFHIR.swift index fd33cdb8c..66f496436 100644 --- a/Sources/GroveQuestionnaireFHIR/Questionnaire+FromFHIR.swift +++ b/Sources/GroveQuestionnaireFHIR/Questionnaire+FromFHIR.swift @@ -193,9 +193,32 @@ extension GroveQuestionnaire.Questionnaire { ).first?.value, styleSensitive.value?.bool == true { warnings.append("The questionnaire declares itself style-sensitive; this renderer does not apply rendering-style/xhtml.") } + warnings += systemlessCodingWarnings(in: other.item ?? []) return warnings } + /// A coding without a system matches only an answer coding without a system, so every enableWhen + /// `answerCoding` and every `answerOption` coding without one is reported. + private static func systemlessCodingWarnings(in items: [ModelsR4.QuestionnaireItem]) -> [String] { + items.flatMap { item in + let linkId = item.linkId.value?.string ?? "?" + var warnings: [String] = [] + for condition in item.enableWhen ?? [] { + if case .coding(let coding) = condition.answer, coding.system?.value == nil { + let code = coding.code?.value?.string ?? "?" + warnings.append("The enableWhen coding '\(code)' on item '\(linkId)' has no system, so it matches only answers without a system.") + } + } + for option in item.answerOption ?? [] { + if case .coding(let coding) = option.value, coding.system?.value == nil { + let code = coding.code?.value?.string ?? "?" + warnings.append("The answer option '\(code)' on item '\(linkId)' has no system, so only enableWhen codings without a system match it.") + } + } + return warnings + systemlessCodingWarnings(in: item.item ?? []) + } + } + private static func entryMode(of other: ModelsR4.Questionnaire) -> EntryMode { guard case .code(let code)? = other.extensions( for: "http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-entryMode" @@ -1316,9 +1339,6 @@ extension GroveQuestionnaire.Questionnaire.Condition { value: try enableWhen.answer.toConditionValue() ) case .notEqual: - // Deliberately NOT compiled as not(equal): FHIR's != evaluates to false when - // the referenced question has no answer, whereas a negated equality would - // evaluate to true there. self = .responseValueComparison( taskId: questionLinkId, operator: .notEqual, @@ -1370,19 +1390,19 @@ extension ModelsR4.QuestionnaireItemEnableWhen.AnswerX { case .coding(let value): let code = try Self.unwrap(value.code?.value?.string) // Match the option-id token form: system|code when the coding carries a - // system, bare code otherwise (which then matches any system). + // system, bare code otherwise (which then matches only an option without a system). let token = (value.system?.value?.url).map { "\($0.absoluteString)|\(code)" } ?? code return .SCMCOption(id: token) case .date, .time, .dateTime: return .date(try Self.unwrap(dateComponents())) case .decimal(let value): - return .decimal(try Self.unwrap(value.value?.decimal.doubleValue)) + return .decimal(try Self.unwrap(value.value?.decimal)) case .integer(let value): return .integer(Int(try Self.unwrap(value.value?.integer))) case .quantity(let quantity): // Same-unit magnitude comparison; unit conversion is out of scope, so a // condition whose unit differs from the question's simply never matches. - let value = try Self.unwrap(quantity.value?.value?.decimal.doubleValue) + let value = try Self.unwrap(quantity.value?.value?.decimal) return .quantity(value: value, unitCode: quantity.code?.value?.string ?? quantity.unit?.value?.string) case .reference(let value): throw .other("Unsupported comparison value '\(value)'") diff --git a/Sources/GroveQuestionnaireFHIR/Questionnaire+ToFHIR.swift b/Sources/GroveQuestionnaireFHIR/Questionnaire+ToFHIR.swift index 74d4a894e..f385cf48d 100644 --- a/Sources/GroveQuestionnaireFHIR/Questionnaire+ToFHIR.swift +++ b/Sources/GroveQuestionnaireFHIR/Questionnaire+ToFHIR.swift @@ -45,12 +45,25 @@ struct FHIRExportContext { /// qty-3 makes a coded `Quantity` without a system an error, so a unit whose system the /// question does not declare is carried as display text rather than as a code. func quantity(_ value: Double, unitCode: String?, forTaskWithId taskId: GroveQuestionnaire.Questionnaire.Task.ID) -> Quantity { + quantity(value.shortestFHIRDecimal, unitCode: unitCode, forTaskWithId: taskId) + } + + /// A `Quantity` expressed in the unit the given question is answered in, with the digits of `value`. + func quantity(_ value: Decimal, unitCode: String?, forTaskWithId taskId: GroveQuestionnaire.Questionnaire.Task.ID) -> Quantity { + quantity(FHIRPrimitive(FHIRDecimal(value)), unitCode: unitCode, forTaskWithId: taskId) + } + + private func quantity( + _ value: FHIRPrimitive, + unitCode: String?, + forTaskWithId taskId: GroveQuestionnaire.Questionnaire.Task.ID + ) -> Quantity { let system = unitCode.flatMap { unitSystem(ofUnit: $0, forTaskWithId: taskId) } return Quantity( code: system == nil ? nil : unitCode?.asFHIRStringPrimitive(), system: system?.asFHIRURIPrimitive(), unit: unitCode?.asFHIRStringPrimitive(), - value: value.asFHIRDecimalPrimitive() + value: value ) } diff --git a/Sources/GroveQuestionnaireFHIR/QuestionnaireItem+Conditions.swift b/Sources/GroveQuestionnaireFHIR/QuestionnaireItem+Conditions.swift index 4e3b49c56..6dfa3b4fa 100644 --- a/Sources/GroveQuestionnaireFHIR/QuestionnaireItem+Conditions.swift +++ b/Sources/GroveQuestionnaireFHIR/QuestionnaireItem+Conditions.swift @@ -65,7 +65,7 @@ extension ModelsR4.QuestionnaireItem { case .integer(let integer): return .integer(FHIRPrimitive(FHIRInteger(Int32(clamping: integer)))) case .decimal(let decimal): - return .decimal(decimal.asFHIRDecimalPrimitive()) + return .decimal(FHIRPrimitive(FHIRDecimal(decimal))) case .string(let string): return .string(string.asFHIRStringPrimitive()) case let .quantity(quantity, unitCode): diff --git a/Sources/GroveQuestionnaireFHIR/QuestionnaireItem+KindDetails.swift b/Sources/GroveQuestionnaireFHIR/QuestionnaireItem+KindDetails.swift index 45a22f68e..6c467b0ba 100644 --- a/Sources/GroveQuestionnaireFHIR/QuestionnaireItem+KindDetails.swift +++ b/Sources/GroveQuestionnaireFHIR/QuestionnaireItem+KindDetails.swift @@ -141,7 +141,7 @@ extension GroveQuestionnaire.Questionnaire.Task.Kind.NumericTaskConfig { case .decimal: Extension( url: FHIRPrimitive(FHIRURI(stringLiteral: core)), - value: .decimal(value.asFHIRDecimalPrimitive()) + value: .decimal(value.shortestFHIRDecimal) ) case .quantity: Extension(url: FHIRPrimitive(FHIRURI(stringLiteral: quantity)), value: .quantity(boundQuantity(value))) diff --git a/Sources/GroveQuestionnaireFHIR/QuestionnaireItem+ToFHIR.swift b/Sources/GroveQuestionnaireFHIR/QuestionnaireItem+ToFHIR.swift index 0eb827864..27e4793e4 100644 --- a/Sources/GroveQuestionnaireFHIR/QuestionnaireItem+ToFHIR.swift +++ b/Sources/GroveQuestionnaireFHIR/QuestionnaireItem+ToFHIR.swift @@ -334,7 +334,7 @@ extension ModelsR4.QuestionnaireItem { if case .numeric(let config) = task.kind.variant, config.valueKind == .integer { return QuestionnaireItemInitial(value: .integer(FHIRPrimitive(FHIRInteger(Int32(clamping: Int(number)))))) } - return QuestionnaireItemInitial(value: .decimal(number.asFHIRDecimalPrimitive())) + return QuestionnaireItemInitial(value: .decimal(number.shortestFHIRDecimal)) } private static func initialDate( diff --git a/Sources/GroveQuestionnaireFHIR/ResourcePair.swift b/Sources/GroveQuestionnaireFHIR/ResourcePair.swift index 94eaef793..7943ad859 100644 --- a/Sources/GroveQuestionnaireFHIR/ResourcePair.swift +++ b/Sources/GroveQuestionnaireFHIR/ResourcePair.swift @@ -56,6 +56,8 @@ public struct ValidationIssue: Equatable, Hashable, Sendable { case requiredItem case itemNesting case enableWhenEvaluation + /// An enableWhen `answerCoding` or an `answerOption` coding has no system. + case codingSystem case expressionShape case expressionEngineRequired case expressionEvaluation diff --git a/Sources/GroveQuestionnaireFHIR/Response+ToFHIR.swift b/Sources/GroveQuestionnaireFHIR/Response+ToFHIR.swift index 7d809d47a..2df7abce0 100644 --- a/Sources/GroveQuestionnaireFHIR/Response+ToFHIR.swift +++ b/Sources/GroveQuestionnaireFHIR/Response+ToFHIR.swift @@ -90,10 +90,10 @@ extension QuestionnaireResponses.Response { code: config.unitCode?.asFHIRStringPrimitive(), system: config.unitSystem?.asFHIRURIPrimitive(), unit: (config.unit.base.isEmpty ? config.unitCode : config.unit.base)?.asFHIRStringPrimitive(), - value: response.asFHIRDecimalPrimitive() + value: response.shortestFHIRDecimal )) case .decimal: - value = .decimal(response.asFHIRDecimalPrimitive()) + value = .decimal(response.shortestFHIRDecimal) } responseItem.answer = [.init(value: value)] case let .quantity(response, unitCode): @@ -107,18 +107,22 @@ extension QuestionnaireResponses.Response { code: unitCode.asFHIRStringPrimitive(), system: (unitOption?.system ?? config.unitSystem)?.asFHIRURIPrimitive(), unit: (unitOption?.display.base ?? (config.unit.base.isEmpty ? unitCode : config.unit.base)).asFHIRStringPrimitive(), - value: response.asFHIRDecimalPrimitive() + value: response.shortestFHIRDecimal ))) ] case .choice(let response): guard case .choice(let config) = task.kind.variant else { throw FHIRResponseConversionError("Invalid Input") } - var answers = try response.selectedOptions.map { optionId in + let selected = try response.selectedOptions.map { optionId in guard let option = try ChoiceOptionResolver.token(optionId, in: config.options) else { throw FHIRResponseConversionError("Unable to find option for '\(optionId)'") } - return QuestionnaireResponseItemAnswer(value: try option.toFHIRAnswerValue(displayed: context.inBaseLanguage)) + return option + } + // Answers follow the order of the options, which is the document order enableWhen reads them in. + var answers = try config.options.filter { option in selected.contains { $0.id == option.id } }.map { option in + QuestionnaireResponseItemAnswer(value: try option.toFHIRAnswerValue(displayed: context.inBaseLanguage)) } if let otherText = response.freeTextOtherResponse { answers.append(.init(value: .string(otherText.asFHIRStringPrimitive()))) diff --git a/Sources/GroveQuestionnaireFHIR/Utils.swift b/Sources/GroveQuestionnaireFHIR/Utils.swift index 90bd64b3e..86d73c414 100644 --- a/Sources/GroveQuestionnaireFHIR/Utils.swift +++ b/Sources/GroveQuestionnaireFHIR/Utils.swift @@ -7,10 +7,27 @@ // import Foundation +import GroveQuestionnaire +import ModelsR4 extension Decimal { + /// The `Double` nearest to the decimal. + /// + /// `NSDecimalNumber.doubleValue` is not correctly rounded: it turns `36.52` into + /// `36.519999999999996`, which then differs from the `36.52` a participant types. var doubleValue: Double { - NSDecimalNumber(decimal: self).doubleValue + Double(description) ?? NSDecimalNumber(decimal: self).doubleValue + } +} + + +extension Double { + /// The FHIR decimal with the shortest digits that convert back to the value. + /// + /// `asFHIRDecimalPrimitive()` expands the binary value, so a typed `36.52` would be exported as + /// `36.52000000000000512` and no longer equal an `answerDecimal` of `36.52`. + var shortestFHIRDecimal: FHIRPrimitive { + FHIRPrimitive(FHIRDecimal(Decimal(shortestDigitsOf: self) ?? Decimal(self))) } } diff --git a/Sources/GroveQuestionnaireUI/Tasks/AnnotateImage/AnnotationHistoryController.swift b/Sources/GroveQuestionnaireUI/Tasks/AnnotateImage/AnnotationHistoryController.swift index 815e6344d..b0b2431e8 100644 --- a/Sources/GroveQuestionnaireUI/Tasks/AnnotateImage/AnnotationHistoryController.swift +++ b/Sources/GroveQuestionnaireUI/Tasks/AnnotateImage/AnnotationHistoryController.swift @@ -40,6 +40,7 @@ final class AnnotationHistoryController { } func undo() { + finishPendingChangeNow() guard undoManager.canUndo else { return } @@ -49,6 +50,7 @@ final class AnnotationHistoryController { } func redo() { + finishPendingChangeNow() guard undoManager.canRedo else { return } @@ -72,6 +74,16 @@ final class AnnotationHistoryController { } } + /// Files a change that is still waiting for the pen to settle, so Undo and Redo act on the drawing the canvas shows. + private func finishPendingChangeNow() { + guard let pendingChangeTask else { + return + } + pendingChangeTask.cancel() + self.pendingChangeTask = nil + finishPendingChange() + } + private func finishHistoryAction() { isPerformingHistoryAction = false refreshAvailability() diff --git a/Tests/GroveQuestionnaireTests/AnnotationHistoryControllerTests.swift b/Tests/GroveQuestionnaireTests/AnnotationHistoryControllerTests.swift new file mode 100644 index 000000000..f5349cc36 --- /dev/null +++ b/Tests/GroveQuestionnaireTests/AnnotationHistoryControllerTests.swift @@ -0,0 +1,81 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +#if canImport(UIKit) +@testable import GroveQuestionnaireUI +import PencilKit +import Testing +import UIKit + + +/// Covers Undo and Redo while a drawing change still waits for the pen to settle. +/// +/// The history files a change 150 ms after the pen lifts. These tests act before that, so they do not +/// depend on how long the pause actually takes. +@Suite +@MainActor +struct AnnotationHistoryControllerTests { + private final class Restorations: AnnotationHistoryControllerDelegate { + func annotationHistoryDidRestore(_ drawing: PKDrawing) {} + } + + private static func drawing(strokes count: Int) -> PKDrawing { + PKDrawing(strokes: (0.. QuestionnaireItemEnableWhen.AnswerX { + .quantity(Quantity( + code: code.asFHIRStringPrimitive(), + system: "http://unitsofmeasure.org", + value: FHIRPrimitive(FHIRDecimal(try #require(Decimal(string: value, locale: Locale(identifier: "en_US_POSIX"))))) + )) + } + var weight = item("weight", .quantity) + weight.extension = [Extension( + url: "http://hl7.org/fhir/StructureDefinition/questionnaire-unit", + value: .coding(Coding(code: "kg", system: "http://unitsofmeasure.org")) + )] + let questionnaire = try questionnaire([ + weight, + item("at-least", .display, when: [condition("weight", .greaterThanOrEqual, try quantity("80", "kg"))]), + item("other-unit", .display, when: [condition("weight", .greaterThanOrEqual, try quantity("80", "[lb_av]"))]), + item("without-unit", .display, when: [ + condition("weight", .greaterThanOrEqual, .quantity(Quantity(value: FHIRPrimitive(FHIRDecimal(Decimal(80)))))) + ]) + ]) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + responses.responses["weight"] = .init(value: .number(80.5)) + #expect(try enabled("at-least", in: responses)) + #expect(try !enabled("other-unit", in: responses)) + // A quantity without a unit orders only answers without a unit. + #expect(try !enabled("without-unit", in: responses)) + } + + /// Dates compare as far as both state them; a partial date that agrees with a full one has no order, + /// so neither `=` nor `!=` is met. + @Test + func partialDatesCompareAtTheirPrecision() throws { + func date(_ text: String) throws -> QuestionnaireItemEnableWhen.AnswerX { + .date(FHIRPrimitive(try FHIRDate(text))) + } + let questionnaire = try questionnaire([ + item("visit", .date), + item("in-2024", .display, when: [condition("visit", .equal, try date("2024"))]), + item("after-2023", .display, when: [condition("visit", .greaterThan, try date("2023"))]), + item("before-2024-04", .display, when: [condition("visit", .lessThan, try date("2024-04"))]), + item("not-2024", .display, when: [condition("visit", .notEqual, try date("2024"))]), + item("seen", .dateTime), + item("seen-after-2024", .display, when: [condition("seen", .greaterThan, .dateTime(FHIRPrimitive(DateTime("2024"))))]), + item("seen-after-2023", .display, when: [condition("seen", .greaterThan, .dateTime(FHIRPrimitive(DateTime("2023"))))]), + // A date-time answer on the day of a date without a time has no order relative to it. + item("seen-on-the-day", .display, when: [condition("seen", .greaterThanOrEqual, .dateTime(FHIRPrimitive(DateTime("2024-03-05"))))]), + item("seen-not-on-the-day", .display, when: [condition("seen", .notEqual, .dateTime(FHIRPrimitive(DateTime("2024-03-05"))))]), + item("seen-after-the-day-before", .display, when: [ + condition("seen", .greaterThan, .dateTime(FHIRPrimitive(DateTime("2024-03-04")))) + ]) + ]) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + responses.responses["visit"] = .init(value: .date(DateComponents(year: 2024, month: 3, day: 5))) + #expect(try !enabled("in-2024", in: responses)) + #expect(try enabled("after-2023", in: responses)) + #expect(try enabled("before-2024-04", in: responses)) + #expect(try !enabled("not-2024", in: responses)) + responses.responses["seen"] = .init(value: .date(DateComponents(year: 2024, month: 3, day: 5, hour: 10, minute: 0))) + #expect(try !enabled("seen-after-2024", in: responses)) + #expect(try enabled("seen-after-2023", in: responses)) + #expect(try !enabled("seen-on-the-day", in: responses)) + #expect(try !enabled("seen-not-on-the-day", in: responses)) + #expect(try enabled("seen-after-the-day-before", in: responses)) + } + + /// Integer answer options compare numerically, with every operator. + @Test + func integerOptionsCompareNumerically() throws { + var score = item("score", .choice) + score.repeats = true + score.answerOption = [1, 3, 5].map { QuestionnaireItemAnswerOption(value: .integer(FHIRPrimitive(FHIRInteger($0)))) } + let questionnaire = try questionnaire([ + score, + item("above-four", .display, when: [condition("score", .greaterThan, .integer(4))]), + item("three", .display, when: [condition("score", .equal, .integer(3))]), + // An integer option has integer values; a decimal condition on it is not met, as the pair rules cannot evaluate it. + item("three-as-decimal", .display, when: [condition("score", .equal, .decimal(FHIRPrimitive(FHIRDecimal(3))))]), + item("below-one", .display, when: [condition("score", .lessThan, .integer(1))]) + ]) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + responses.responses["score"] = .init(value: .choice(.init(selectedOptions: ["integer|3", "integer|5"]))) + #expect(try enabled("above-four", in: responses)) + #expect(try enabled("three", in: responses)) + #expect(try !enabled("three-as-decimal", in: responses)) + #expect(try !enabled("below-one", in: responses)) + } + + /// A decimal initial value keeps its digits, so it equals the same decimal in a condition. + @Test + func decimalInitialValueEqualsTheSameDecimal() throws { + let value = FHIRPrimitive(FHIRDecimal(try #require(Decimal(string: "36.52", locale: Locale(identifier: "en_US_POSIX"))))) + var temperature = item("temperature", .decimal) + temperature.initial = [QuestionnaireItemInitial(value: .decimal(value))] + let questionnaire = try questionnaire([ + temperature, + item("gated", .display, when: [condition("temperature", .equal, .decimal(value))]) + ]) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + #expect(responses.responses["temperature"].value.numberValue == 36.52) + #expect(try enabled("gated", in: responses)) + } + + // MARK: Inequality and codings + + /// `!=` holds when no answer equals the value, so also without an answer; with several answers, one equal + /// answer is enough to make it fail. + @Test + func notEqualHoldsWhenNoAnswerIsEqual() throws { + let questionnaire = try codingQuestionnaire() + let responses = QuestionnaireResponses(questionnaire: questionnaire) + #expect(try enabled("not-blue", in: responses)) + responses.responses["color"] = .init(value: .choice(.init(selectedOptions: ["\(Self.colors)|red"]))) + #expect(try enabled("not-blue", in: responses)) + responses.responses["color"] = .init(value: .choice(.init(selectedOptions: ["\(Self.colors)|red", "\(Self.colors)|blue"]))) + #expect(try !enabled("not-blue", in: responses)) + } + + struct CodingCase: Sendable, CustomTestStringConvertible { + let name: String + let selected: Set + let enabled: Set + + var testDescription: String { name } + } + + static let codingCases: [CodingCase] = [ + CodingCase(name: "system red", selected: ["\(colors)|red"], enabled: ["with-system", "not-blue", "not-red-without-system"]), + CodingCase(name: "red without a system", selected: ["red"], enabled: ["without-system", "not-blue"]), + CodingCase(name: "several, none blue", selected: ["\(colors)|red", "red"], enabled: ["with-system", "without-system", "not-blue"]), + CodingCase( + name: "several, one blue", + selected: ["\(colors)|red", "\(colors)|blue"], + enabled: ["with-system", "not-red-without-system"] + ), + CodingCase(name: "unanswered", selected: [], enabled: ["not-blue", "not-red-without-system"]) + ] + + /// A coding matches only when system and code are both equal; a coding without a system matches only an + /// answer without a system. + @Test(arguments: codingCases) + func codingsMatchOnSystemAndCode(testCase: CodingCase) throws { + let questionnaire = try codingQuestionnaire() + let responses = QuestionnaireResponses(questionnaire: questionnaire) + responses.responses["color"] = .init(value: .choice(.init(selectedOptions: testCase.selected))) + for gate in ["with-system", "without-system", "other-system", "not-blue", "not-red-without-system"] { + #expect(try enabled(gate, in: responses) == testCase.enabled.contains(gate), "\(gate)") + } + } + + /// Every enableWhen coding and answer option without a system is reported. + @Test + func codingsWithoutSystemAreReported() throws { + let warnings = try codingQuestionnaire().metadata.administrationWarnings + #expect(warnings.filter { $0.contains("has no system") }.count == 3) + #expect(warnings.contains { $0.contains("answer option 'red' on item 'color'") }) + #expect(warnings.contains { $0.contains("enableWhen coding 'red' on item 'without-system'") }) + #expect(warnings.contains { $0.contains("enableWhen coding 'red' on item 'not-red-without-system'") }) + } + + // MARK: Follow-up occurrences + + /// A follow-up task occurs once for every selected option. A question before the gated follow-up is read in + /// the same occurrence, a question after it in the previous one (in the first, the following one), and a + /// task outside reads the nearest occurrence before it, or else the first after it. + @Test + func followUpOccurrencesFollowTheR4Axes() throws { // swiftlint:disable:this function_body_length + let questionnaire = Questionnaire( + metadata: .init(id: "", url: nil, title: "", explainer: ""), + sections: [ + .init(id: "section", tasks: [ + .init(id: "preview", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "played", operator: .equal, value: .bool(true) + )), + .init(id: "rounds", title: "", kind: .choice(.init( + options: [.init(id: "first", title: "First"), .init(id: "second", title: "Second"), .init(id: "third", title: "Third")], + allowsMultipleSelection: true, + followUpTasks: [ + .init(id: "played", title: "", kind: .boolean), + .init(id: "bonus", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "next", operator: .equal, value: .bool(true) + )), + .init(id: "next", title: "", kind: .boolean), + .init(id: "score", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "played", operator: .equal, value: .bool(true) + )), + .init(id: "picked", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "rounds", operator: .equal, value: .SCMCOption(id: "third") + )) + ] + ))), + .init(id: "summary", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "played", operator: .equal, value: .bool(true) + )) + ]) + ] + ) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + // The options are selected out of order; occurrences follow the order of the options. + responses.responses["rounds"] = .init(value: .choice(.init(selectedOptions: ["third", "first", "second"]))) + let answers: [(String, played: Bool, next: Bool)] = [("first", true, false), ("second", true, true), ("third", false, true)] + func round(_ option: String) -> QuestionnaireResponses { + responses.view(appending: .init().appending(taskId: "rounds").appending(choiceOption: option)) + } + for (option, played, next) in answers { + round(option).responses["played"] = .init(value: .bool(played)) + round(option).responses["next"] = .init(value: .bool(next)) + } + let rounds = try #require(questionnaire.task(withId: "rounds")) + let followUp = { (id: String) in try #require(rounds.kind.followUpTasks.first { $0.id == id }) } + // `bonus` reads `next` of the first occurrence in the first two rounds, and of the second in the third. + #expect(try !round("first").shouldEnable(task: followUp("bonus"))) + #expect(try !round("second").shouldEnable(task: followUp("bonus"))) + #expect(try round("third").shouldEnable(task: followUp("bonus"))) + // `score` reads `played` of its own round. + #expect(try round("first").shouldEnable(task: followUp("score"))) + #expect(try !round("third").shouldEnable(task: followUp("score"))) + // `picked` reads its enclosing choice task, with every selected option. + #expect(try round("first").shouldEnable(task: followUp("picked"))) + // `preview` reads the first round; `summary` reads the last. + #expect(try enabled("preview", in: responses)) + #expect(try !enabled("summary", in: responses)) + // Without the third round, the second round is the last. + responses.responses["rounds"].value = .choice(.init(selectedOptions: ["first", "second"])) + #expect(try enabled("summary", in: responses)) + } + + /// A follow-up nested two levels deep reads the nearest preceding occurrence, which is in its own visit. + @Test + func nestedFollowUpsReadTheNearestPrecedingOccurrence() throws { + let questionnaire = Questionnaire( + metadata: .init(id: "", url: nil, title: "", explainer: ""), + sections: [ + .init(id: "section", tasks: [ + .init(id: "visits", title: "", kind: .choice(.init( + options: [.init(id: "a", title: "A"), .init(id: "b", title: "B")], + allowsMultipleSelection: true, + followUpTasks: [ + .init(id: "attended", title: "", kind: .boolean), + .init(id: "topics", title: "", kind: .choice(.init( + options: [.init(id: "x", title: "X")], + allowsMultipleSelection: false, + followUpTasks: [ + .init(id: "note", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "attended", operator: .equal, value: .bool(true) + )) + ] + ))) + ] + ))) + ]) + ] + ) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + responses.responses["visits"] = .init(value: .choice(.init(selectedOptions: ["a", "b"]))) + func visit(_ option: String) -> QuestionnaireResponses { + responses.view(appending: .init().appending(taskId: "visits").appending(choiceOption: option)) + } + visit("a").responses["attended"] = .init(value: .bool(true)) + visit("b").responses["attended"] = .init(value: .bool(false)) + for option in ["a", "b"] { + visit(option).responses["topics"] = .init(value: .choice(.init(selectedOptions: ["x"]))) + } + let note = try #require(questionnaire.task(at: ["visits", "topics", "note"])) + func topic(_ option: String) -> QuestionnaireResponses { + visit(option).view(appending: .init().appending(taskId: "topics").appending(choiceOption: "x")) + } + #expect(topic("a").shouldEnable(task: note)) + #expect(!topic("b").shouldEnable(task: note)) + } + + /// The follow-up tasks of a disabled choice task occur without answers, so a task outside cannot read their answers. + @Test + func followUpsOfADisabledChoiceTaskHaveNoAnswers() throws { + let questionnaire = Questionnaire( + metadata: .init(id: "", url: nil, title: "", explainer: ""), + sections: [ + .init(id: "section", tasks: [ + .init(id: "asked", title: "", kind: .boolean), + .init( + id: "rounds", + title: "", + kind: .choice(.init( + options: [.init(id: "first", title: "First")], + allowsMultipleSelection: true, + followUpTasks: [.init(id: "played", title: "", kind: .boolean)] + )), + enabledCondition: .responseValueComparison(taskId: "asked", operator: .equal, value: .bool(true)) + ), + .init(id: "summary", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "played", operator: .equal, value: .bool(true) + )) + ]) + ] + ) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + responses.responses["asked"] = .init(value: .bool(true)) + responses.responses["rounds"] = .init(value: .choice(.init(selectedOptions: ["first"]))) + responses.view(appending: .init().appending(taskId: "rounds").appending(choiceOption: "first")) + .responses["played"] = .init(value: .bool(true)) + #expect(try enabled("summary", in: responses)) + responses.responses["asked"].value = .bool(false) + #expect(try !enabled("summary", in: responses)) + } + + /// The follow-up tasks of a custom question kind occur in the containers the kind stores responses in. + @Test + func customKindFollowUpsResolve() throws { + struct Config: QuestionKindConfig { + let followUpTasks: [GroveQuestionnaire.Questionnaire.Task] + } + struct FollowUpKind: QuestionKindDefinition { + static func validate( + response: QuestionnaireResponses.Response, + for config: Config + ) -> QuestionnaireResponses.ResponseValidationResult { + .ok + } + } + let questionnaire = Questionnaire( + metadata: .init(id: "", url: nil, title: "", explainer: ""), + sections: [ + .init(id: "section", tasks: [ + .init(id: "custom", title: "", kind: .custom(FollowUpKind.self, config: Config(followUpTasks: [ + .init(id: "played", title: "", kind: .boolean), + .init(id: "bonus", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "played", operator: .equal, value: .bool(true) + )) + ]))), + .init(id: "summary", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "played", operator: .equal, value: .bool(true) + )) + ]) + ] + ) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + // Follow-up responses are kept only under a task that has a response. + responses.responses["custom"] = .init(value: .string("entry")) + let nested = responses.view(appending: .init().appending(taskId: "custom").appending(choiceOption: "entry")) + nested.responses["played"] = .init(value: .bool(true)) + let bonus = try #require(questionnaire.task(at: ["custom", "bonus"])) + #expect(nested.shouldEnable(task: bonus)) + #expect(try enabled("summary", in: responses)) + nested.responses["played"].value = .bool(false) + #expect(!nested.shouldEnable(task: bonus)) + #expect(try !enabled("summary", in: responses)) + } + + /// A free-text answer of an open choice is the last answer, and the follow-up tasks occur beneath it without + /// answers, as in the exported response; a task after the choice reads that occurrence. + @Test + func freeTextAnswerHasEmptyFollowUps() throws { + let questionnaire = Questionnaire( + metadata: .init(id: "", url: nil, title: "", explainer: ""), + sections: [ + .init(id: "section", tasks: [ + .init(id: "rounds", title: "", kind: .choice(.init( + options: [.init(id: "first", title: "First")], + hasFreeTextOtherOption: true, + allowsMultipleSelection: true, + followUpTasks: [.init(id: "played", title: "", kind: .boolean)] + ))), + .init(id: "summary", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "played", operator: .equal, value: .bool(true) + )) + ]) + ] + ) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + responses.responses["rounds"] = .init(value: .choice(.init(selectedOptions: ["first"]))) + responses.view(appending: .init().appending(taskId: "rounds").appending(choiceOption: "first")) + .responses["played"] = .init(value: .bool(true)) + #expect(try enabled("summary", in: responses)) + responses.responses["rounds"].value = .choice(.init(selectedOptions: ["first"], freeTextOtherResponse: "Other")) + #expect(try !enabled("summary", in: responses)) + } + + /// A follow-up task of a custom kind reads its conditions also in a container that holds no responses yet. + @Test + func customKindFollowUpsResolveInAnEmptyContainer() throws { + struct Config: QuestionKindConfig { + let followUpTasks: [GroveQuestionnaire.Questionnaire.Task] + } + struct FollowUpKind: QuestionKindDefinition { + static func validate( + response: QuestionnaireResponses.Response, + for config: Config + ) -> QuestionnaireResponses.ResponseValidationResult { + .ok + } + } + let questionnaire = Questionnaire( + metadata: .init(id: "", url: nil, title: "", explainer: ""), + sections: [ + .init(id: "section", tasks: [ + .init(id: "consent", title: "", kind: .boolean), + .init(id: "custom", title: "", kind: .custom(FollowUpKind.self, config: Config(followUpTasks: [ + .init(id: "bonus", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "consent", operator: .equal, value: .bool(true) + )) + ]))) + ]) + ] + ) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + responses.responses["consent"] = .init(value: .bool(true)) + responses.responses["custom"] = .init(value: .string("entry")) + let nested = responses.view(appending: .init().appending(taskId: "custom").appending(choiceOption: "entry")) + let bonus = try #require(questionnaire.task(at: ["custom", "bonus"])) + #expect(nested.shouldEnable(task: bonus)) + } + + /// A custom kind's container without stored responses is an occurrence of its own, so a follow-up there reads + /// its own unanswered sibling and not the answer in another container. + @Test + func customKindEmptyContainerReadsItsOwnFollowUps() throws { + struct Config: QuestionKindConfig { + let followUpTasks: [GroveQuestionnaire.Questionnaire.Task] + } + struct FollowUpKind: QuestionKindDefinition { + static func validate( + response: QuestionnaireResponses.Response, + for config: Config + ) -> QuestionnaireResponses.ResponseValidationResult { + .ok + } + } + let questionnaire = Questionnaire( + metadata: .init(id: "", url: nil, title: "", explainer: ""), + sections: [ + .init(id: "section", tasks: [ + .init(id: "custom", title: "", kind: .custom(FollowUpKind.self, config: Config(followUpTasks: [ + .init(id: "played", title: "", kind: .boolean), + .init(id: "bonus", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "played", operator: .equal, value: .bool(true) + )) + ]))) + ]) + ] + ) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + responses.responses["custom"] = .init(value: .string("entries")) + responses.view(appending: .init().appending(taskId: "custom").appending(choiceOption: "a")) + .responses["played"] = .init(value: .bool(true)) + let empty = responses.view(appending: .init().appending(taskId: "custom").appending(choiceOption: "b")) + let bonus = try #require(questionnaire.task(at: ["custom", "bonus"])) + #expect(!empty.shouldEnable(task: bonus)) + } + + /// A condition that cannot be evaluated satisfies no operator, `!=` included, as the pair rules report it; + /// `any` and `all` still decide where the other conditions suffice. + @Test + func conditionsThatCannotBeEvaluatedSatisfyNoOperator() throws { + func task(_ id: String, _ condition: GroveQuestionnaire.Questionnaire.Condition) -> GroveQuestionnaire.Questionnaire.Task { + .init(id: id, title: "", kind: .boolean, enabledCondition: condition) + } + let flagIsTrue = GroveQuestionnaire.Questionnaire.Condition.responseValueComparison(taskId: "flag", operator: .equal, value: .bool(true)) + let questionnaire = Questionnaire( + metadata: .init(id: "", url: nil, title: "", explainer: ""), + sections: [ + .init(id: "section", tasks: [ + .init(id: "flag", title: "", kind: .boolean), + task("other-type", .responseValueComparison(taskId: "flag", operator: .notEqual, value: .string("x"))), + task("itself", .responseValueComparison(taskId: "itself", operator: .notEqual, value: .bool(true))), + task("unknown", .responseValueComparison(taskId: "missing", operator: .notEqual, value: .bool(true))), + task("not-unknown", .not(.hasResponse(taskId: "missing"))), + task("any-decides", .any([.hasResponse(taskId: "missing"), flagIsTrue])), + task("all-decides", .all([.hasResponse(taskId: "missing"), .not(flagIsTrue)])), + task("cycle-a", .responseValueComparison(taskId: "cycle-b", operator: .notEqual, value: .bool(true))), + task("cycle-b", .responseValueComparison(taskId: "cycle-a", operator: .notEqual, value: .bool(true))), + // An ordered operator on a value without an order, and an open comparison, stay open under `not`. + task("not-ordered-boolean", .not(.responseValueComparison(taskId: "flag", operator: .greaterThan, value: .bool(true)))), + .init(id: "visit", title: "", kind: .dateTime(.init(style: .dateOnly))), + task("not-in-2024", .not(.responseValueComparison(taskId: "visit", operator: .equal, value: .date(DateComponents(year: 2024))))), + // A cycle through the condition of a choice task whose follow-up task is referenced. + task("outer", .responseValueComparison(taskId: "inner", operator: .notEqual, value: .bool(true))), + .init( + id: "rounds", + title: "", + kind: .choice(.init( + options: [.init(id: "first", title: "First")], + allowsMultipleSelection: false, + followUpTasks: [.init(id: "inner", title: "", kind: .boolean)] + )), + enabledCondition: .responseValueComparison(taskId: "outer", operator: .equal, value: .bool(true)) + ) + ]) + ] + ) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + responses.responses["flag"] = .init(value: .bool(true)) + responses.responses["visit"] = .init(value: .date(DateComponents(year: 2024, month: 3, day: 5))) + responses.responses["outer"] = .init(value: .bool(true)) + responses.responses["rounds"] = .init(value: .choice(.init(selectedOptions: ["first"]))) + responses.view(appending: .init().appending(taskId: "rounds").appending(choiceOption: "first")) + .responses["inner"] = .init(value: .bool(true)) + let ids = ["other-type", "itself", "unknown", "not-unknown", "all-decides", "cycle-a", "cycle-b", "not-ordered-boolean", "not-in-2024", "outer"] + for id in ids { + #expect(try !enabled(id, in: responses), "\(id)") + } + #expect(try enabled("any-decides", in: responses)) + } + + /// The comparison operators of a quantity question compare in the question's unit. + @Test + func quantityQuestionOperatorsCompareInTheirUnit() throws { + let weight = NumberQuestion.quantity("weight", "Weight", unit: "kg") + let condition = weight >= 80 + #expect(condition == .responseValueComparison(taskId: "weight", operator: .greaterThanOrEqual, value: .quantity(value: 80, unitCode: "kg"))) + let questionnaire = Questionnaire( + metadata: .init(id: "", url: nil, title: "", explainer: ""), + sections: [ + .init(id: "section", tasks: weight._makeTasks() + [ + .init(id: "heavy", title: "", kind: .boolean, enabledCondition: weight >= 80), + .init(id: "not-light", title: "", kind: .boolean, enabledCondition: !(weight < 80)) + ]) + ] + ) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + responses.responses["weight"] = .init(value: .number(85)) + #expect(try enabled("heavy", in: responses)) + #expect(try enabled("not-light", in: responses)) + } + + /// A choice task without a selection, or a disabled one, holds its follow-up tasks once without answers, so a + /// condition reads that occurrence instead of reaching an answer in another container, as the pair rules do. + @Test + func nestedFollowUpsOfAnUnansweredChoiceHaveNoAnswers() throws { + let inner = GroveQuestionnaire.Questionnaire.Task( + id: "inner", + title: "", + kind: .choice(.init( + options: [.init(id: "o", title: "O")], + allowsMultipleSelection: false, + followUpTasks: [.init(id: "detail", title: "", kind: .boolean)] + )), + enabledCondition: .responseValueComparison(taskId: "asked", operator: .equal, value: .bool(true)) + ) + let questionnaire = Questionnaire( + metadata: .init(id: "", url: nil, title: "", explainer: ""), + sections: [ + .init(id: "section", tasks: [ + .init(id: "visits", title: "", kind: .choice(.init( + options: [.init(id: "a", title: "A"), .init(id: "b", title: "B")], + allowsMultipleSelection: true, + followUpTasks: [ + .init(id: "asked", title: "", kind: .boolean), + inner, + .init(id: "noted", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "detail", operator: .equal, value: .bool(true) + )) + ] + ))), + .init(id: "summary", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "detail", operator: .equal, value: .bool(true) + )), + .init(id: "no-summary", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "detail", operator: .notEqual, value: .bool(true) + )) + ]) + ] + ) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + func visit(_ option: String) -> QuestionnaireResponses { + responses.view(appending: .init().appending(taskId: "visits").appending(choiceOption: option)) + } + responses.responses["visits"] = .init(value: .choice(.init(selectedOptions: ["a", "b"]))) + visit("a").responses["asked"] = .init(value: .bool(true)) + visit("a").responses["inner"] = .init(value: .choice(.init(selectedOptions: ["o"]))) + visit("a").view(appending: .init().appending(taskId: "inner").appending(choiceOption: "o")) + .responses["detail"] = .init(value: .bool(true)) + let noted = try #require(questionnaire.task(at: ["visits", "noted"])) + // Visit b asks the inner question but has no answer to it yet. + visit("b").responses["asked"] = .init(value: .bool(true)) + #expect(visit("a").shouldEnable(task: noted)) + #expect(!visit("b").shouldEnable(task: noted)) + #expect(try !enabled("summary", in: responses)) + #expect(try enabled("no-summary", in: responses)) + // In visit b the inner question is disabled. + visit("b").responses["asked"] = .init(value: .bool(false)) + #expect(!visit("b").shouldEnable(task: noted)) + #expect(try !enabled("summary", in: responses)) + #expect(try enabled("no-summary", in: responses)) + } + + /// A part that cannot be evaluated does not settle `all` or `any`, also under `not`. + @Test + func openPartsDoNotSettleTheirCondition() throws { + let questionnaire = Questionnaire( + metadata: .init(id: "", url: nil, title: "", explainer: ""), + sections: [ + .init(id: "section", tasks: [ + .init(id: "flag", title: "", kind: .boolean), + .init(id: "gated", title: "", kind: .boolean, enabledCondition: .not(.all([ + .hasResponse(taskId: "missing"), + .responseValueComparison(taskId: "flag", operator: .notEqual, value: .bool(true)) + ]))) + ]) + ] + ) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + let gated = try #require(questionnaire.task(withId: "gated")) + #expect(!responses.isEnablementSettled(for: gated)) + responses.responses["flag"] = .init(value: .bool(true)) + #expect(responses.shouldEnable(task: gated)) + } + + /// A condition on a follow-up task that has no occurrence yet stays unsettled, since an option selected later + /// can still make it occur. + @Test + func conditionOnAFollowUpWithoutOccurrenceIsUnsettled() throws { + let questionnaire = Questionnaire( + metadata: .init(id: "", url: nil, title: "", explainer: ""), + sections: [ + .init(id: "section", tasks: [ + .init(id: "rounds", title: "", kind: .choice(.init( + options: [.init(id: "first", title: "First")], + allowsMultipleSelection: true, + followUpTasks: [ + .init(id: "played", title: "", kind: .boolean), + .init(id: "scored", title: "", kind: .boolean, enabledCondition: .hasResponse(taskId: "played")) + ] + ))), + .init(id: "summary", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "played", operator: .equal, value: .bool(true) + )), + // A follow-up target with a condition of its own is unsettled in the same way. + .init(id: "conditioned-summary", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "scored", operator: .equal, value: .bool(true) + )) + ]) + ] + ) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + let summary = try #require(questionnaire.task(withId: "summary")) + let conditioned = try #require(questionnaire.task(withId: "conditioned-summary")) + #expect(!responses.isEnablementSettled(for: summary)) + #expect(!responses.isEnablementSettled(for: conditioned)) + responses.responses["rounds"] = .init(value: .choice(.init(selectedOptions: ["first"]))) + responses.view(appending: .init().appending(taskId: "rounds").appending(choiceOption: "first")) + .responses["played"] = .init(value: .bool(true)) + #expect(responses.isEnablementSettled(for: summary)) + } + + /// Resolving a condition searches only the follow-up containers that can hold its question, so many + /// conditional choice tasks with follow-ups stay fast to evaluate. + @Test(.timeLimit(.minutes(1))) + func manyConditionalChoiceTasksEvaluateQuickly() throws { + let tasks: [GroveQuestionnaire.Questionnaire.Task] = (0..<12).map { index in + .init( + id: "choice\(index)", + title: "", + kind: .choice(.init( + options: [.init(id: "yes", title: "Yes")], + allowsMultipleSelection: false, + followUpTasks: [.init(id: "detail\(index)", title: "", kind: .boolean)] + )), + enabledCondition: index == 0 ? .none : .responseValueComparison( + taskId: "detail\(index - 1)", operator: .notEqual, value: .bool(false) + ) + ) + } + let questionnaire = Questionnaire( + metadata: .init(id: "", url: nil, title: "", explainer: ""), + sections: [.init(id: "section", tasks: tasks + [ + .init(id: "summary", title: "", kind: .boolean, enabledCondition: .responseValueComparison( + taskId: "detail11", operator: .notEqual, value: .bool(false) + )) + ])] + ) + let responses = QuestionnaireResponses(questionnaire: questionnaire) + #expect(try enabled("summary", in: responses)) + } + + /// Exported answers follow the order of the options, which is the order conditions read them in. + @Test + func exportedAnswersFollowTheOptionOrder() throws { + let questionnaire = try codingQuestionnaire() + let responses = QuestionnaireResponses(questionnaire: questionnaire) + responses.responses["color"] = .init(value: .choice(.init(selectedOptions: ["red", "\(Self.colors)|blue", "\(Self.colors)|red"]))) + let exported = try ModelsR4.QuestionnaireResponse( + responses, + renderedIn: questionnaireResponseTestLocale, + authored: questionnaireResponseTestAuthoredAt, + authoredTimeZone: questionnaireResponseTestTimeZone + ) + let codes = (exported.item?.first { $0.linkId.value?.string == "color" }?.answer ?? []).map { answer -> String in + guard case .coding(let coding)? = answer.value else { + return "?" + } + return [coding.system?.value?.url.absoluteString, coding.code?.value?.string].compactMap(\.self).joined(separator: "|") + } + #expect(codes == ["\(Self.colors)|red", "\(Self.colors)|blue", "red"]) + } +} + + +extension EnableWhenTests { + private func item( + _ linkId: String, + _ type: QuestionnaireItemType, + when conditions: [QuestionnaireItemEnableWhen] = [] + ) -> ModelsR4.QuestionnaireItem { + var item = ModelsR4.QuestionnaireItem(linkId: linkId.asFHIRStringPrimitive(), type: FHIRPrimitive(type)) + item.text = linkId.asFHIRStringPrimitive() + item.enableWhen = conditions.isEmpty ? nil : conditions + return item + } + + private func condition( + _ question: String, + _ operation: QuestionnaireItemOperator, + _ answer: QuestionnaireItemEnableWhen.AnswerX + ) -> QuestionnaireItemEnableWhen { + QuestionnaireItemEnableWhen(answer: answer, operator: FHIRPrimitive(operation), question: question.asFHIRStringPrimitive()) + } + + private func questionnaire(_ items: [ModelsR4.QuestionnaireItem]) throws -> GroveQuestionnaire.Questionnaire { + var questionnaire = ModelsR4.Questionnaire(status: FHIRPrimitive(PublicationStatus.active)) + questionnaire.language = "en-US" + questionnaire.url = "https://example.org/fhir/Questionnaire/enable-when".asFHIRURIPrimitive() + questionnaire.version = "1.0.0".asFHIRStringPrimitive() + questionnaire.item = items + return try GroveQuestionnaire.Questionnaire(questionnaire, clock: questionnaireResponseTestClock) + } + + /// A repeating choice with red and blue in one system and red without a system, gated by coding conditions. + private func codingQuestionnaire() throws -> GroveQuestionnaire.Questionnaire { + func coding(_ code: String, system: String?) -> Coding { + Coding(code: code.asFHIRStringPrimitive(), system: system.map { FHIRPrimitive(FHIRURI(stringLiteral: $0)) }) + } + var color = item("color", .choice) + color.repeats = true + color.answerOption = [ + .init(value: .coding(coding("red", system: Self.colors))), + .init(value: .coding(coding("blue", system: Self.colors))), + .init(value: .coding(coding("red", system: nil))) + ] + return try questionnaire([ + color, + item("with-system", .display, when: [condition("color", .equal, .coding(coding("red", system: Self.colors)))]), + item("without-system", .display, when: [condition("color", .equal, .coding(coding("red", system: nil)))]), + item("other-system", .display, when: [condition("color", .equal, .coding(coding("red", system: "http://other.example/colors")))]), + item("not-blue", .display, when: [condition("color", .notEqual, .coding(coding("blue", system: Self.colors)))]), + item("not-red-without-system", .display, when: [condition("color", .notEqual, .coding(coding("red", system: nil)))]) + ]) + } + + private func enabled(_ taskId: String, in responses: QuestionnaireResponses) throws -> Bool { + let task = try #require(responses.questionnaire.sections.flatMap(\.tasks).first { $0.id == taskId }) + return responses.shouldEnable(task: task) + } +} diff --git a/Tests/GroveQuestionnaireTests/FHIRConformanceTests.swift b/Tests/GroveQuestionnaireTests/FHIRConformanceTests.swift index 4bc52f913..3332bb36a 100644 --- a/Tests/GroveQuestionnaireTests/FHIRConformanceTests.swift +++ b/Tests/GroveQuestionnaireTests/FHIRConformanceTests.swift @@ -78,10 +78,10 @@ struct FHIRConformanceTests { #expect(tasks.first { $0.id == "q2" }?.isOptional == false) } - // MARK: A2 — `!=` is false while the source is unanswered + // MARK: A2: `!=` holds while the source is unanswered @Test - func notEqualIsFalseWhenSourceUnanswered() throws { + func notEqualHoldsWhenSourceUnanswered() throws { let enableWhen = QuestionnaireItemEnableWhen( answer: .boolean(FHIRPrimitive(FHIRBool(true))), operator: FHIRPrimitive(QuestionnaireItemOperator.notEqual), @@ -93,8 +93,8 @@ struct FHIRConformanceTests { ]), clock: questionnaireResponseTestClock) let responses = QuestionnaireResponses(questionnaire: questionnaire) let target = try #require(questionnaire.sections.flatMap(\.tasks).first { $0.id == "q2" }) - // Unanswered source: != must NOT enable the target. - #expect(!responses.shouldEnable(task: target)) + // Unanswered source: no answer is equal, so != enables the target. + #expect(responses.shouldEnable(task: target)) // Equal answer: still disabled. responses.responses["q1"] = .init(value: .bool(true)) #expect(!responses.shouldEnable(task: target)) diff --git a/Tests/GroveQuestionnaireTests/PairEnableWhenTests.swift b/Tests/GroveQuestionnaireTests/PairEnableWhenTests.swift new file mode 100644 index 000000000..56f5b6980 --- /dev/null +++ b/Tests/GroveQuestionnaireTests/PairEnableWhenTests.swift @@ -0,0 +1,568 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +import Foundation +@testable import GroveQuestionnaire +@testable import GroveQuestionnaireFHIR +import ModelsR4 +import Testing + +// The scenarios spell out FHIR JSON and keep each case table next to its test, so that they stay comparable +// with the shared questionnaire scenarios. +// swiftlint:disable large_tuple multiline_literal_brackets type_contents_order + + +/// `enableWhen` as the pair validator evaluates it: which instance a condition reads, exact numeric +/// comparisons, `!=`, and coding identity. +@Suite +struct PairEnableWhenTests { + private typealias JSONObject = [String: Any] + + private static let colors = "http://example.org/colors" + fileprivate static let ucum = "http://unitsofmeasure.org" + + // MARK: Occurrences + + /// Three instances of a repeating group: a question before the gated item is read in the same instance, a + /// question after it in the previous instance (in the first instance, the following one), a nested + /// repeating group reads its enclosing instance, and items outside the group read the nearest instance. + @Test + func repeatingGroupInstancesFollowTheR4Axes() throws { + let items: [JSONObject] = [ + display("preview", when: ["question": "score", "operator": ">", "answerInteger": 5]), + [ + "linkId": "round", "type": "group", "repeats": true, "text": "Round", + "item": [ + ["linkId": "played", "type": "boolean", "text": "Played"], + question("score", "integer", when: ["question": "played", "operator": "=", "answerBoolean": true]), + display("bonus", when: ["question": "next", "operator": "=", "answerBoolean": true]), + ["linkId": "next", "type": "boolean", "text": "Another round"], + [ + "linkId": "detail", "type": "group", "repeats": true, "text": "Detail", + "item": [ + display("inner-note", when: ["question": "played", "operator": "=", "answerBoolean": true]), + display("inner-late", when: ["question": "late", "operator": "=", "answerBoolean": true]) + ] + ], + ["linkId": "late", "type": "boolean", "text": "Late"] + ] + ], + display("summary", when: ["question": "score", "operator": "exists", "answerBoolean": true]) + ] + func round(played: Bool, score: Int?, next: Bool, late: Bool) -> JSONObject { + var children: [JSONObject] = [answered("played", ["valueBoolean": played])] + if let score { + children.append(answered("score", ["valueInteger": score])) + } + children += [ + ["linkId": "bonus"], + answered("next", ["valueBoolean": next]), + ["linkId": "detail", "item": [["linkId": "inner-note"], ["linkId": "inner-late"]]], + answered("late", ["valueBoolean": late]) + ] + return ["linkId": "round", "item": children] + } + let issues = try issues(items: items, response: [ + ["linkId": "preview"], + round(played: true, score: 8, next: false, late: true), + round(played: true, score: 4, next: true, late: false), + round(played: false, score: 9, next: true, late: true), + ["linkId": "summary"] + ]) + #expect(!issues.contains { $0.code == .itemDuplicate }) + #expect(disabled(issues) == [ + // `bonus` reads `next` of the first instance, in the first two instances. + "QuestionnaireResponse.item[1].item[2]", + "QuestionnaireResponse.item[2].item[2]", + // The third instance was not played, so it has no score, and the second instance was not late. + "QuestionnaireResponse.item[3].item[1]", + "QuestionnaireResponse.item[3].item[4].item[0]", + "QuestionnaireResponse.item[3].item[4].item[1]", + // `summary` reads the score of the last instance, which is disabled and so counts as absent. + "QuestionnaireResponse.item[4]" + ]) + } + + /// Items nested under a question's answers read the whole question, every answer included. + @Test + func itemsUnderAnswersReadTheEnclosingQuestion() throws { + let items: [JSONObject] = [ + [ + "linkId": "pain", "type": "boolean", "repeats": true, "text": "Pain", + "item": [question("pain-site", "string", when: ["question": "pain", "operator": "=", "answerBoolean": true])] + ], + display("after-pain", when: ["question": "pain-site", "operator": "exists", "answerBoolean": true]) + ] + let issues = try issues(items: items, response: [ + [ + "linkId": "pain", + "answer": [ + ["valueBoolean": true, "item": [answered("pain-site", ["valueString": "Knee"])]], + ["valueBoolean": false, "item": [answered("pain-site", ["valueString": "Ankle"])]] + ] + ], + ["linkId": "after-pain"] + ]) + #expect(disabled(issues).isEmpty) + } + + /// A non-repeating group still reports a second instance. + @Test + func nonRepeatingGroupInstancesAreDuplicates() throws { + let items: [JSONObject] = [ + ["linkId": "visit", "type": "group", "text": "Visit", "item": [["linkId": "attended", "type": "boolean", "text": "Attended"]]] + ] + let issues = try issues(items: items, response: [ + ["linkId": "visit", "item": [answered("attended", ["valueBoolean": true])]], + ["linkId": "visit", "item": [answered("attended", ["valueBoolean": false])]] + ]) + #expect(issues.contains { $0.code == .itemDuplicate }) + } + + // MARK: Numbers + + struct NumericCase: Sendable, CustomTestStringConvertible { + let itemType: String + let answer: JSONValue + let condition: (key: String, value: JSONValue) + let operation: String + let holds: Bool + + var testDescription: String { "\(answer) \(operation) \(condition.key) \(condition.value) is \(holds)" } + } + + /// A JSON value as a test argument. + enum JSONValue: Sendable, CustomStringConvertible { + case integer(Int) + case decimal(Double) + case string(String) + case quantity(Double, code: String) + + var json: Any { + switch self { + case .integer(let value): value + case .decimal(let value): value + case .string(let value): value + case let .quantity(value, code): ["value": value, "system": PairEnableWhenTests.ucum, "code": code] + } + } + + var description: String { + switch self { + case .integer(let value): "\(value)" + case .decimal(let value): "\(value)" + case .string(let value): value + case let .quantity(value, code): "\(value) \(code)" + } + } + } + + static let numericCases: [NumericCase] = { + let decimalAgainstInteger: [(Double, String, Bool)] = [ + (80.5, ">=", true), (80.5, ">", true), (80.5, "=", false), (80.5, "!=", true), (80.5, "<", false), (80.5, "<=", false), + (80.0, "=", true), (80.0, "!=", false), (80.0, ">=", true), (80.0, "<=", true), (80.0, ">", false), (80.0, "<", false), + (79.9, "<", true), (79.9, "<=", true), (79.9, ">=", false), (79.9, "=", false) + ] + let integerAgainstDecimal: [(Int, Double, String, Bool)] = [ + (80, 80.0, "=", true), (80, 80.5, "<", true), (80, 80.5, "=", false), (80, 79.9, ">", true), (80, 80.0, "!=", false) + ] + let decimalAgainstDecimal: [(Double, Double, String, Bool)] = [ + (79.9, 79.9, "=", true), (36.52, 36.52, "=", true), (36.52, 36.5, ">", true), (0.1, 0.2, "<", true) + ] + return decimalAgainstInteger.map { + NumericCase(itemType: "decimal", answer: .decimal($0.0), condition: ("answerInteger", .integer(80)), operation: $0.1, holds: $0.2) + } + integerAgainstDecimal.map { + NumericCase(itemType: "integer", answer: .integer($0.0), condition: ("answerDecimal", .decimal($0.1)), operation: $0.2, holds: $0.3) + } + decimalAgainstDecimal.map { + NumericCase(itemType: "decimal", answer: .decimal($0.0), condition: ("answerDecimal", .decimal($0.1)), operation: $0.2, holds: $0.3) + } + }() + + /// Integer and decimal values compare numerically and exactly, in either direction. + @Test(arguments: numericCases) + func numbersCompareExactly(testCase: NumericCase) throws { + let answerKey = testCase.itemType == "integer" ? "valueInteger" : "valueDecimal" + let items: [JSONObject] = [ + ["linkId": "weight", "type": testCase.itemType, "text": "Weight"], + display("gated", when: ["question": "weight", "operator": testCase.operation, testCase.condition.key: testCase.condition.value.json]) + ] + let issues = try issues(items: items, response: [answered("weight", [answerKey: testCase.answer.json]), ["linkId": "gated"]]) + #expect(disabled(issues).isEmpty == testCase.holds) + } + + /// A decimal reads back with the digits it was written with, so `79.9` has one decimal place. + @Test + func decimalPlacesUseTheWrittenDigits() throws { + let items: [JSONObject] = [[ + "linkId": "weight", "type": "decimal", "text": "Weight", + "extension": [["url": "http://hl7.org/fhir/StructureDefinition/maxDecimalPlaces", "valueInteger": 1]] + ]] + let issues = try issues(items: items, response: [answered("weight", ["valueDecimal": 79.9])]) + #expect(!issues.contains { $0.code == .answerDecimalPlaces }) + } + + // MARK: Inequality and codings + + /// `!=` holds when no answer equals the value: without an answer, and when the question is disabled, whose + /// answers count as absent. + @Test + func notEqualHoldsWhenNoAnswerIsEqual() throws { + let items: [JSONObject] = [ + ["linkId": "smoker", "type": "boolean", "text": "Smoker"], + question("packs", "integer", when: ["question": "smoker", "operator": "=", "answerBoolean": true]), + display("not-smoker", when: ["question": "smoker", "operator": "!=", "answerBoolean": true]), + display("not-one-pack", when: ["question": "packs", "operator": "!=", "answerInteger": 1]) + ] + let unanswered = try issues(items: items, response: [["linkId": "not-smoker"], ["linkId": "not-one-pack"]]) + #expect(disabled(unanswered).isEmpty) + let smokes = try issues(items: items, response: [ + answered("smoker", ["valueBoolean": true]), + answered("packs", ["valueInteger": 1]), + ["linkId": "not-smoker"], + ["linkId": "not-one-pack"] + ]) + #expect(disabled(smokes) == ["QuestionnaireResponse.item[2]", "QuestionnaireResponse.item[3]"]) + let doesNotSmoke = try issues(items: items, response: [ + answered("smoker", ["valueBoolean": false]), + answered("packs", ["valueInteger": 1]), + ["linkId": "not-smoker"], + ["linkId": "not-one-pack"] + ]) + #expect(disabled(doesNotSmoke) == ["QuestionnaireResponse.item[1]"]) + } + + /// An answer of a choice item with an `answerOption.value[x]` type other than Coding counts for enablement, + /// besides being reported as an answer of the wrong type. + @Test + func choiceAnswersOfOptionValueTypesCount() throws { + let items: [JSONObject] = [ + [ + "linkId": "level", "type": "choice", "text": "Level", + "answerOption": [["valueInteger": 1], ["valueInteger": 3], ["valueInteger": 5]] + ], + display("three", when: ["question": "level", "operator": "=", "answerInteger": 3]), + display("not-three", when: ["question": "level", "operator": "!=", "answerInteger": 3]) + ] + let issues = try issues(items: items, response: [answered("level", ["valueInteger": 3]), ["linkId": "three"], ["linkId": "not-three"]]) + #expect(disabled(issues) == ["QuestionnaireResponse.item[2]"]) + #expect(issues.contains { $0.code == .answerType }) + } + + /// A condition on a calculated item reads the answer the response carries. + @Test + func calculatedAnswersAreRead() throws { + let items: [JSONObject] = [ + [ + "linkId": "score", "type": "integer", "text": "Score", "readOnly": true, + "extension": [[ + "url": "http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-calculatedExpression", + "valueExpression": ["language": "text/fhirpath", "expression": "12"] + ]] + ], + display("high", when: ["question": "score", "operator": ">", "answerInteger": 10]), + display("low", when: ["question": "score", "operator": "<=", "answerInteger": 10]) + ] + let result = try issues(items: items, response: [answered("score", ["valueInteger": 12]), ["linkId": "high"], ["linkId": "low"]]) + #expect(disabled(result) == ["QuestionnaireResponse.item[2]"]) + } + + /// An open choice's free-text answer carries the follow-up items without answers, and a later item reads them. + @Test + func freeTextAnswersHaveEmptyFollowUps() throws { + let items: [JSONObject] = [ + [ + "linkId": "rounds", "type": "open-choice", "text": "Rounds", "repeats": true, + "answerOption": [["valueCoding": ["system": "https://example.org/rounds", "code": "first"]]], + "item": [["linkId": "played", "type": "boolean", "text": "Played"]] + ], + display("summary", when: ["question": "played", "operator": "=", "answerBoolean": true]) + ] + let selected: JSONObject = [ + "valueCoding": ["system": "https://example.org/rounds", "code": "first"], + "item": [answered("played", ["valueBoolean": true])] + ] + let withoutText = try issues(items: items, response: [["linkId": "rounds", "answer": [selected]], ["linkId": "summary"]]) + #expect(disabled(withoutText).isEmpty) + let withText = try issues(items: items, response: [ + ["linkId": "rounds", "answer": [selected, ["valueString": "Other"]]], + ["linkId": "summary"] + ]) + #expect(disabled(withText) == ["QuestionnaireResponse.item[1]"]) + } + + // MARK: Conditions that cannot be evaluated + + /// A condition that names an unknown, shared or unanswerable item, compares an answer of another type, orders an + /// unordered value, or sits among several conditions without `enableBehavior` cannot be evaluated; with `any` or + /// `all`, the other conditions can still decide the outcome. + @Test(arguments: [true, false]) + func conditionsThatCannotBeEvaluated(firstIsTrue: Bool) throws { + let gates: [(String, [JSONObject], String?)] = [ + ("dangling", [["question": "missing", "operator": "=", "answerBoolean": true]], nil), + ("group-target", [["question": "section", "operator": "exists", "answerBoolean": true]], nil), + ("mismatch", [["question": "q1", "operator": "=", "answerInteger": 1]], nil), + ("ordered-bool", [["question": "q1", "operator": ">", "answerBoolean": true]], nil), + ( + "no-behavior", + [["question": "q1", "operator": "=", "answerBoolean": true], ["question": "q1", "operator": "exists", "answerBoolean": true]], + nil + ), + ("dup-ref", [["question": "dup", "operator": "exists", "answerBoolean": true]], nil), + ( + "any-dangling", + [["question": "q1", "operator": "=", "answerBoolean": true], ["question": "missing", "operator": "=", "answerBoolean": true]], + "any" + ), + ( + "all-dangling", + [["question": "q1", "operator": "=", "answerBoolean": true], ["question": "missing", "operator": "=", "answerBoolean": true]], + "all" + ) + ] + var items: [JSONObject] = [ + ["linkId": "q1", "type": "boolean", "text": "First question"], + ["linkId": "section", "type": "group", "text": "Section", "item": [["linkId": "dup", "type": "string", "text": "First use"]]], + ["linkId": "dup", "type": "string", "text": "Second use"] + ] + for (linkId, conditions, behavior) in gates { + var item: JSONObject = ["linkId": linkId, "type": "display", "text": linkId, "enableWhen": conditions] + item["enableBehavior"] = behavior + items.append(item) + } + let issues = try issues( + items: items, + response: [answered("q1", ["valueBoolean": firstIsTrue])] + gates.map { ["linkId": $0.0] }, + evaluable: false + ) + let unevaluated = Set(gates.map(\.0).filter { gate in + issues.contains { $0.code == .enableWhenEvaluation && $0.message.contains("'\(gate)'") } + }) + #expect(unevaluated == Set(gates.map(\.0)).subtracting(firstIsTrue ? ["any-dangling"] : ["all-dangling"])) + // With a false first answer, `all` fails on the condition that can be evaluated. + #expect(disabled(issues) == (firstIsTrue ? [] : ["QuestionnaireResponse.item[8]"])) + } + + /// An item whose enablement depends on itself cannot be evaluated; an item that reads it is decided when its + /// outcome does not depend on whether that item is enabled. + @Test(arguments: [false, true]) + func cyclesCannotBeEvaluated(answered aIsAnswered: Bool) throws { + let items: [JSONObject] = [ + question("a", "boolean", when: ["question": "b", "operator": "exists", "answerBoolean": true]), + question("b", "boolean", when: ["question": "a", "operator": "exists", "answerBoolean": true]), + question("self", "boolean", when: ["question": "self", "operator": "=", "answerBoolean": true]), + [ + "linkId": "outer", "type": "group", "text": "Outer", + "enableWhen": [["question": "inner", "operator": "=", "answerBoolean": true]], + "item": [["linkId": "inner", "type": "boolean", "text": "Inner"]] + ], + display("after-a", when: ["question": "a", "operator": "exists", "answerBoolean": true]), + display("after-a-false", when: ["question": "a", "operator": "exists", "answerBoolean": false]) + ] + let response: [JSONObject] = (aIsAnswered ? [answered("a", ["valueBoolean": true])] : []) + + [["linkId": "after-a"], ["linkId": "after-a-false"]] + let issues = try issues(items: items, response: response, evaluable: false) + let unevaluated = Set(["a", "b", "self", "outer", "after-a", "after-a-false"].filter { linkId in + issues.contains { $0.code == .enableWhenEvaluation && $0.message.contains("'\(linkId)'") } + }) + #expect(unevaluated == (aIsAnswered ? ["a", "b", "self", "outer", "after-a", "after-a-false"] : ["a", "b", "self", "outer"])) + // Without an answer, `a` has no answer whether or not it is enabled. + #expect(disabled(issues) == (aIsAnswered ? [] : ["QuestionnaireResponse.item[0]"])) + } + + // MARK: Typed values + + struct TypedCase: Sendable, CustomTestStringConvertible { + let name: String + let answers: [String: JSONValue] + let disabled: Set + let notEvaluated: Set + + var testDescription: String { name } + } + + static let typedCases: [TypedCase] = [ + TypedCase( + name: "typed values", + answers: [ + "age": .integer(17), "weight": .decimal(70.5), "onset": .string("2019-12-31"), + "visit": .string("2024-03-01T12:30:00+01:00"), "wake": .string("06:45:00"), + "temperature": .quantity(38.5, code: "Cel") + ], + disabled: ["adult", "heavy", "heavy-integer"], + notEvaluated: [] + ), + TypedCase( + name: "precision and units", + answers: [ + "age": .integer(18), "weight": .integer(80), "onset": .string("2020-01"), + "visit": .string("2024-03-01"), "wake": .string("07:30:00"), + "temperature": .quantity(101, code: "[degF]") + ], + disabled: ["early-riser"], + notEvaluated: ["early", "after-visit", "fever"] + ) + ] + + /// Dates, date-times and times compare as points in time at the precision they state, and quantities in the + /// unit of the threshold; values whose precision or unit leaves the order open cannot be evaluated. + @Test(arguments: typedCases) + func typedValuesCompareByTheirType(testCase: TypedCase) throws { + let questions: [(String, String, String, String, Any)] = [ + ("age", "integer", "adult", ">=", ["answerInteger": 18]), + ("weight", "decimal", "heavy", ">", ["answerDecimal": 70.5]), + ("weight", "decimal", "heavy-integer", ">=", ["answerInteger": 80]), + ("onset", "date", "early", "<", ["answerDate": "2020-01-01"]), + ("visit", "dateTime", "after-visit", ">", ["answerDateTime": "2024-03-01T12:00:00+01:00"]), + ("wake", "time", "early-riser", "<=", ["answerTime": "07:00:00"]), + ("temperature", "quantity", "fever", ">=", ["answerQuantity": ["value": 38, "system": Self.ucum, "code": "Cel"]]) + ] + var items: [JSONObject] = [] + var response: [JSONObject] = [] + for (linkId, type, gate, operation, answer) in questions { + if !items.contains(where: { $0["linkId"] as? String == linkId }) { + items.append(["linkId": linkId, "type": type, "text": linkId]) + let key = "value" + type.prefix(1).uppercased() + type.dropFirst() + response.append(answered(linkId, [key: try #require(testCase.answers[linkId]).json])) + } + var condition = try #require(answer as? JSONObject) + condition["question"] = linkId + condition["operator"] = operation + items.append(display(gate, when: condition)) + response.append(["linkId": gate]) + } + let issues = try issues(items: items, response: response, evaluable: testCase.notEvaluated.isEmpty) + let gates = response.enumerated().filter { entry in questions.contains { $0.2 == entry.element["linkId"] as? String } } + #expect(disabled(issues) == Set(gates.filter { testCase.disabled.contains($0.element["linkId"] as? String ?? "") }.map { + "QuestionnaireResponse.item[\($0.offset)]" + })) + let unevaluated = issues.filter { $0.code == .enableWhenEvaluation }.map(\.message) + #expect(unevaluated.count == testCase.notEvaluated.count) + for gate in testCase.notEvaluated { + #expect(unevaluated.contains { $0.contains("'\(gate)'") }, "\(gate)") + } + } + + struct CodingCase: Sendable, CustomTestStringConvertible { + let name: String + let answers: [String?] + /// The gated items that are disabled, by their condition. + let disabled: Set + + var testDescription: String { name } + } + + static let codingCases: [CodingCase] = [ + CodingCase(name: "system red", answers: ["red"], disabled: ["without-system", "other-system"]), + CodingCase(name: "red without a system", answers: [nil], disabled: ["with-system", "other-system", "not-red-without-system"]), + CodingCase(name: "several, none blue", answers: ["red", nil], disabled: ["other-system", "not-red-without-system"]), + CodingCase(name: "several, one blue", answers: ["red", "blue"], disabled: ["without-system", "other-system", "not-blue"]), + CodingCase(name: "unanswered", answers: [], disabled: ["with-system", "without-system", "other-system"]) + ] + + /// A coding matches only when system and code are both equal; a coding without a system matches only an + /// answer without a system. Every coding without a system is reported. + @Test(arguments: codingCases) + func codingsMatchOnSystemAndCode(testCase: CodingCase) throws { + let gates: [(String, String, JSONObject)] = [ + ("with-system", "=", ["system": Self.colors, "code": "red"]), + ("without-system", "=", ["code": "red"]), + ("other-system", "=", ["system": "http://other.example/colors", "code": "red"]), + ("not-blue", "!=", ["system": Self.colors, "code": "blue"]), + ("not-red-without-system", "!=", ["code": "red"]) + ] + let items: [JSONObject] = [[ + "linkId": "color", "type": "choice", "repeats": true, "text": "Colors", + "answerOption": [ + ["valueCoding": ["system": Self.colors, "code": "red"]], + ["valueCoding": ["system": Self.colors, "code": "blue"]], + ["valueCoding": ["code": "red"]] + ] + ]] + gates.map { display($0.0, when: ["question": "color", "operator": $0.1, "answerCoding": $0.2]) } + let answers: [JSONObject] = testCase.answers.map { code in + ["valueCoding": code.map { ["system": Self.colors, "code": $0] } ?? ["code": "red"]] + } + var response: [JSONObject] = answers.isEmpty ? [] : [["linkId": "color", "answer": answers]] + response += gates.map { ["linkId": $0.0] } + let issues = try issues(items: items, response: response) + let offset = response.count - gates.count + #expect(disabled(issues) == Set(gates.enumerated().filter { testCase.disabled.contains($0.element.0) }.map { + "QuestionnaireResponse.item[\($0.offset + offset)]" + })) + #expect(issues.filter { $0.code == .codingSystem }.map(\.path).sorted() == [ + "Questionnaire.item[0].answerOption[2].valueCoding", + "Questionnaire.item[2].enableWhen[0].answerCoding", + "Questionnaire.item[5].enableWhen[0].answerCoding" + ]) + #expect(issues.filter { $0.code == .codingSystem }.allSatisfy { $0.severity == .warning }) + } +} + + +extension PairEnableWhenTests { + private func display(_ linkId: String, when condition: JSONObject) -> JSONObject { + ["linkId": linkId, "type": "display", "text": linkId, "enableWhen": [condition]] + } + + private func question(_ linkId: String, _ type: String, when condition: JSONObject) -> JSONObject { + ["linkId": linkId, "type": type, "text": linkId, "enableWhen": [condition]] + } + + private func answered(_ linkId: String, _ answer: JSONObject) -> JSONObject { + ["linkId": linkId, "answer": [answer]] + } + + private func disabled(_ issues: [ValidationIssue]) -> Set { + Set(issues.filter { $0.code == .itemDisabled }.map(\.path)) + } + + /// The issues of a completed response with `response` items to a questionnaire with `items`. + /// - parameter evaluable: Whether every enableWhen of the pair can be evaluated. + private func issues(items: [JSONObject], response: [JSONObject], evaluable: Bool = true) throws -> [ValidationIssue] { + let base = GroveQuestionnaire.Questionnaire( + url: try #require(URL(string: "https://example.org/fhir/Questionnaire/enable-when")), + version: "1.0.0", + language: "en-US", + title: "Enable When" + ) { + Section("section") { + BooleanQuestion("question", "Question") + } + } + let responses = QuestionnaireResponses(questionnaire: base) + responses.responses["question"] = .init(value: .bool(true)) + let pair = try ResourceBuilder().pair( + from: responses, + renderedIn: questionnaireResponseTestLocale, + authored: questionnaireResponseTestAuthoredAt, + authoredTimeZone: questionnaireResponseTestTimeZone + ) + var questionnaire = try object(pair.questionnaire) + var responseObject = try object(pair.response) + questionnaire["item"] = items + responseObject["item"] = response + let decodedQuestionnaire = try JSONDecoder().decode( + ModelsR4.Questionnaire.self, + from: JSONSerialization.data(withJSONObject: questionnaire) + ) + let decodedResponse = try JSONDecoder().decode( + ModelsR4.QuestionnaireResponse.self, + from: JSONSerialization.data(withJSONObject: responseObject) + ) + let issues = PairValidator().issues(questionnaire: decodedQuestionnaire, response: decodedResponse) + // Only the enablement outcome is under test. + #expect(!issues.contains { [.itemUnknown, .itemMisplaced].contains($0.code) }) + if evaluable { + #expect(!issues.contains { $0.code == .enableWhenEvaluation }) + } + return issues + } + + private func object(_ resource: some Encodable) throws -> JSONObject { + try #require(JSONSerialization.jsonObject(with: JSONEncoder().encode(resource)) as? JSONObject) + } +} diff --git a/Tests/GroveQuestionnaireTests/PairRuleTests.swift b/Tests/GroveQuestionnaireTests/PairRuleTests.swift index 04407e216..210c6c8be 100644 --- a/Tests/GroveQuestionnaireTests/PairRuleTests.swift +++ b/Tests/GroveQuestionnaireTests/PairRuleTests.swift @@ -500,7 +500,7 @@ struct GroveQuestionnaireFHIRPairRuleTests { #expect(pair.warnings.first?.code == .expressionEngineRequired) } - @Test("Coded enableWhen uses a system only when the condition declares one", arguments: [false, true]) + @Test("Coded enableWhen matches only when system and code are both equal", arguments: [false, true]) func codedConditionSystemMatching(negated: Bool) throws { for expectedSystem in [nil, Self.codingSystem, "https://example.org/other-codes"] { var objects = try basePairObjects() @@ -522,12 +522,16 @@ struct GroveQuestionnaireFHIRPairRuleTests { var targetResponse = triggerResponse triggerResponse["answer"] = [["valueCoding": coding]] targetResponse["linkId"] = "target" - let matches = expectedSystem == nil || expectedSystem == Self.codingSystem + let matches = expectedSystem == Self.codingSystem responseGroup["item"] = matches != negated ? [triggerResponse, targetResponse] : [triggerResponse] try replaceGroup(in: &objects.response, with: responseGroup) let pair = try decodePair(objects) let issues = PairValidator().issues(questionnaire: pair.questionnaire, response: pair.response) - #expect(issues.isEmpty) + #expect(!issues.contains { $0.severity == .error }) + // A condition without a system is reported, since it matches only answers without a system. + #expect(issues.filter { $0.code == .codingSystem }.map(\.path) == (expectedSystem == nil + ? ["Questionnaire.item[0].item[1].enableWhen[0].answerCoding"] + : [])) } } diff --git a/Tests/GroveQuestionnaireTests/UITests/TestAppUITests/QuestionKindTests.swift b/Tests/GroveQuestionnaireTests/UITests/TestAppUITests/QuestionKindTests.swift index 8004b04c4..b002bc186 100644 --- a/Tests/GroveQuestionnaireTests/UITests/TestAppUITests/QuestionKindTests.swift +++ b/Tests/GroveQuestionnaireTests/UITests/TestAppUITests/QuestionKindTests.swift @@ -50,9 +50,14 @@ final class QuestionKindTests: TestAppUITests, @unchecked Sendable { XCTAssert(app.buttons["Redo"].exists) XCTAssert(app.buttons["Undo"].isEnabled) XCTAssertFalse(app.buttons["Redo"].isEnabled) + // An empty drawing swaps Done for a Close button in front of Undo and Redo, which moves them. A tap aimed + // at their earlier place lands on Close and dismisses the editor, so each tap waits for the swap and the move. + // "Close" alone would also find the questionnaire's own Close button underneath the editor. + app.buttons["Undo"].waitUntilSettled(timeout: 2) app.buttons["Undo"].tap() XCTAssert(app.buttons["Redo"].isEnabled) - XCTAssert(app.buttons["Close"].exists) + XCTAssert(waitUntil(timeout: 2) { !app.buttons["Done"].exists }) + app.buttons["Redo"].waitUntilSettled(timeout: 2) app.buttons["Redo"].tap() XCTAssert(waitUntil(timeout: 2) { app.buttons["Done"].exists }) @@ -61,11 +66,9 @@ final class QuestionKindTests: TestAppUITests, @unchecked Sendable { XCTAssertFalse(painRegion.isSelected) strokeStart.press(forDuration: 0.1, thenDragTo: strokeEnd) // the pass along the stroke takes it out entirely, and the erase is one step of the history - XCTAssert(waitUntil(timeout: 2) { app.buttons["Close"].exists }) - // The history files the erase 150 ms after the pen lifts, and nothing on screen changes when it does: - // Undo was already enabled. An Undo before then would take back the Redo instead. - sleep(for: .milliseconds(400)) + XCTAssert(waitUntil(timeout: 2) { !app.buttons["Done"].exists }) XCTAssert(app.buttons["Undo"].isEnabled) + app.buttons["Undo"].waitUntilSettled(timeout: 2) app.buttons["Undo"].tap() XCTAssert(waitUntil(timeout: 2) { app.buttons["Done"].exists }) painRegion.tap()