Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 116 additions & 8 deletions lib/statifier_examples/signup/journey.ex
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,23 @@ defmodule StatifierExamples.Signup.Journey do
a field no shipped screen can exercise is a field no test can defend.
`docs/spikes/signup-skeleton-spike.md` carries it as the ask.

## A question's own checks hold a press, against the host's today

A question may carry `checks`, conditions its author wrote over
`responses` and `context` - the patron registration fixture's date of
birth has one refusing a date after today. Riddler's resolve drops them
from the nodes it answers, so `submit/4` puts each shown question's
checks back from the screens document before it validates, and
validates against a root carrying the responses and a `context` built
here. The responses are what the reader typed, over what the chart
holds for the other screens: a question on this screen is checked
against what was typed for it alone, as it always was, and no secret
question's stored response is in the root at all. The `context` is
`"today"`, the ISO 8601 date `opts[:today]` names, today's UTC date when
it names none. The `context` root is the host's, so nothing the reader
sends reaches it. A failing check refuses the press as `{:invalid,
view}`, its finding put in the author's words.

## A secret question is sealed before the chart sees it

A screen may ask a `secret_question` - the patron registration screens
Expand Down Expand Up @@ -281,7 +298,12 @@ defmodule StatifierExamples.Signup.Journey do
has collected so far, keyed by element key; `findings` is empty except in the
`{:invalid, view}` a refused `submit/3` answers with.

`discarded` is the one key that is not always there, and its absence is
`refusals` is there only beside those findings: the same refusals as
riddler's findings, each carrying as its `author_message` the words its
pair carries (`StatifierExamples.Signup.Validation.check/3`), for a
renderer that draws `Riddler.Finding` structs.

`discarded` is the other key that is not always there, and its absence is
the information: a view carries it only when the press it answers was
refused by the chart, and it holds the reason
`StatifierExamples.Charts.Durable.send_event/4` gave. A page can
Expand All @@ -303,6 +325,7 @@ defmodule StatifierExamples.Signup.Journey do
:retry_after_ms => non_neg_integer() | nil,
:result => map() | nil,
:findings => [Validation.finding()],
optional(:refusals) => [Riddler.Finding.t()],
optional(:discarded) => term()
}

Expand Down Expand Up @@ -495,7 +518,10 @@ defmodule StatifierExamples.Signup.Journey do
the screen the reader saw one keystroke ago.

`opts[:screens]` and `opts[:path]` are the screens document and the Path
`start/2` was given, when it was given them.
`start/2` was given, when it was given them. `opts[:today]`, a `Date`,
is the today a question's checks read as `context.today` (the
moduledoc's "A question's own checks hold a press, against the host's
today"); today's UTC date when it is absent.
"""
@spec submit(String.t(), String.t(), %{optional(String.t()) => term()}, keyword()) ::
{:ok, view()} | {:invalid, view()} | {:error, term()}
Expand All @@ -508,23 +534,105 @@ defmodule StatifierExamples.Signup.Journey do
{:ok, settled} <- view(execution_id, run, state, screens, path),
{:ok, drafted} <- parked_on(resolve(settled, responses)),
{:ok, button} <- button(drafted.nodes, outcome),
{:ok, sealed} <- checked(drafted, responses, screens) do
{:ok, sealed} <- checked(drafted, responses, screens, context(opts)) do
pressed(durable, run, execution_id, button, coerce(sealed), {screens, path})
end
end

# The press's responses checked as the reader typed them and then sealed
# (the moduledoc's "A secret question is sealed before the chart sees
# it"), or the drafted view with its findings when the check refuses them.
@spec checked(view(), map(), screens()) ::
@spec checked(view(), map(), screens(), map()) ::
{:ok, map()} | {:invalid, view()} | {:error, {:seal_secrets, term()}}
defp checked(drafted, responses, screens) do
case Validation.validate(drafted.nodes, responses) do
[] -> seal(screens, drafted.screen, responses)
findings -> {:invalid, %{drafted | findings: findings}}
defp checked(drafted, responses, {document, _admitted} = screens, context) do
nodes = authored_checks(drafted.nodes, drafted.screen.nodes)
held = Map.merge(elsewhere(drafted, document), responses)

case Validation.validate(nodes, held, context) do
[] ->
seal(screens, drafted.screen, responses)

findings ->
refusals = Validation.check(nodes, held, context)
{:invalid, Map.put(%{drafted | findings: findings}, :refusals, refusals)}
end
end

# What the chart holds for the other screens: every stored response but
# the ones this screen's questions own and every secret question's,
# whichever screen asks it (the moduledoc's "A question's own checks
# hold a press, against the host's today").
@spec elsewhere(view(), map()) :: map()
defp elsewhere(%{datamodel: datamodel, screen: screen}, document) do
secrets = document |> Screens.screens() |> Enum.flat_map(&secret_keys(&1.nodes))

(Map.get(datamodel, "responses") || %{})
|> Map.drop(owned_keys(screen.nodes))
|> Map.drop(secrets)
end

@spec owned_keys([Screens.node_doc()]) :: [String.t()]
defp owned_keys(nodes) do
Enum.flat_map(nodes, fn node ->
own = if is_binary(node["key"]), do: [node["key"]], else: []
own ++ owned_keys(child_nodes(node))
end)
end

# The shown nodes with each question's `checks` put back from the
# screen's own nodes, a container's children included at any depth on
# both sides (the moduledoc's "A question's own checks hold a press,
# against the host's today").
@spec authored_checks([Screens.node_doc()], [Screens.node_doc()]) :: [Screens.node_doc()]
defp authored_checks(shown, authored), do: put_checks(shown, checks_by_key(authored))

@spec put_checks([Screens.node_doc()], %{optional(String.t()) => list()}) ::
[Screens.node_doc()]
defp put_checks(nodes, checks) do
Enum.map(nodes, fn node ->
node = Enum.reduce(["nodes", "elements"], node, &put_inner_checks(&2, &1, checks))

case Map.fetch(checks, Map.get(node, "key")) do
{:ok, node_checks} -> Map.put(node, "checks", node_checks)
:error -> node
end
end)
end

@spec put_inner_checks(Screens.node_doc(), String.t(), %{optional(String.t()) => list()}) ::
Screens.node_doc()
defp put_inner_checks(node, field, checks) do
case node do
%{^field => inner} when is_list(inner) -> %{node | field => put_checks(inner, checks)}
_no_children -> node
end
end

@spec child_nodes(Screens.node_doc()) :: [Screens.node_doc()]
defp child_nodes(%{"nodes" => inner}) when is_list(inner), do: inner
defp child_nodes(%{"elements" => inner}) when is_list(inner), do: inner
defp child_nodes(_node), do: []

@spec checks_by_key([Screens.node_doc()]) :: %{optional(String.t()) => list()}
defp checks_by_key(nodes) do
Enum.reduce(nodes, %{}, fn node, acc ->
own =
case node do
%{"key" => key, "checks" => checks} when is_list(checks) -> %{key => checks}
_no_checks -> %{}
end

acc |> Map.merge(checks_by_key(child_nodes(node))) |> Map.merge(own)
end)
end

# The host's `context` root for a press's checks.
@spec context(keyword()) :: %{required(String.t()) => String.t()}
defp context(opts) do
today = Keyword.get_lazy(opts, :today, &Date.utc_today/0)
%{"today" => Date.to_iso8601(today)}
end

@doc """
The back half: take the execution keyed `execution_id` back to the step
it entered before the one it is on (the moduledoc's "Back through a
Expand Down
70 changes: 61 additions & 9 deletions lib/statifier_examples/signup/validation.ex
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,29 @@ defmodule StatifierExamples.Signup.Validation do
screen that cannot be finished, which is worse than a page that will not
draw.

## A question's own checks, against the host's context

A question may carry `checks`: conditions its author wrote over
`responses` and `context`, which riddler evaluates after the built-in
rules (`Riddler.Screens.validate_screen/3`). Riddler's resolve drops them
from a resolved node, as it drops a condition, so a caller that wants
them checked puts each shown question's `checks` back from the document
before it calls `validate/3` (`StatifierExamples.Signup.Journey` does).
`context` is the host's: `validate/3` and `check/3` put it in the root
beside the responses, and `validate/2` and `check/2` put an empty one, so
a check reading `context.today` decides nothing there and raises
nothing. A failing check is put to a reader in its author's words, the
check's `message`.

## A finding is a pair, and the key is the element key

`{key, message}` - the same key the response lands at (`responses.<key>`,
ruled by the operator for Riddler, 2026-09-12), so a page can put the
message beside the input it belongs to without a second lookup, and the
order is the document's. The key is riddler's `element_key`; the message is
this app's for the two codes a shipped screen can raise (a format finding
is worded for the format the question names), and riddler's own for any
other, an out-of-range number among them.
is worded for the format the question names), the author's for a failing
check, and riddler's own for any other, an out-of-range number among them.
"""

alias Riddler.Finding
Expand Down Expand Up @@ -95,10 +109,32 @@ defmodule StatifierExamples.Signup.Validation do
[]
"""
@spec validate([Screens.node_doc()], %{optional(String.t()) => term()}) :: [finding()]
def validate(nodes, responses) when is_list(nodes) and is_map(responses) do
def validate(nodes, responses) when is_list(nodes) and is_map(responses),
do: validate(nodes, responses, %{})

@doc """
`validate/2` with `context`, the host's root, beside the responses: what
a question's `checks` read as `context` (the moduledoc's "A question's own
checks, against the host's context").

iex> nodes = [%{"type" => "text_question", "key" => "birth_date", "format" => "date",
...> "checks" => [%{"code" => "check.birth_date_in_future",
...> "condition" => "responses.birth_date::date <= context.today::date",
...> "message" => "A date of birth cannot be in the future."}]}]
iex> StatifierExamples.Signup.Validation.validate(nodes, %{"birth_date" => "2031-04-17"},
...> %{"today" => "2026-11-27"})
[{"birth_date", "A date of birth cannot be in the future."}]
iex> StatifierExamples.Signup.Validation.validate(nodes, %{"birth_date" => "1990-04-17"},
...> %{"today" => "2026-11-27"})
[]
"""
@spec validate([Screens.node_doc()], %{optional(String.t()) => term()}, map()) ::
[finding()]
def validate(nodes, responses, context)
when is_list(nodes) and is_map(responses) and is_map(context) do
formats = formats_by_key(nodes)

nodes |> refusals(responses) |> Enum.map(&pair(&1, formats))
nodes |> refusals(responses, context) |> Enum.map(&pair(&1, formats))
end

@doc """
Expand All @@ -114,21 +150,31 @@ defmodule StatifierExamples.Signup.Validation do
{"response.format", "email", "must look like an email address"}
"""
@spec check([Screens.node_doc()], %{optional(String.t()) => term()}) :: [Finding.t()]
def check(nodes, responses) when is_list(nodes) and is_map(responses) do
def check(nodes, responses) when is_list(nodes) and is_map(responses),
do: check(nodes, responses, %{})

@doc """
`check/2` with `context` beside the responses, as `validate/3` takes it.
"""
@spec check([Screens.node_doc()], %{optional(String.t()) => term()}, map()) :: [Finding.t()]
def check(nodes, responses, context)
when is_list(nodes) and is_map(responses) and is_map(context) do
formats = formats_by_key(nodes)

nodes
|> refusals(responses)
|> refusals(responses, context)
|> Enum.map(&%{&1 | author_message: reader_message(&1, formats) || &1.author_message})
end

@spec refusals([Screens.node_doc()], %{optional(String.t()) => term()}) :: [Finding.t()]
defp refusals(nodes, responses) do
@spec refusals([Screens.node_doc()], %{optional(String.t()) => term()}, map()) ::
[Finding.t()]
defp refusals(nodes, responses, context) do
Enum.each(nodes, &known_format!/1)

document = admit!(nodes)
root = %{"responses" => responses, "context" => context}

case Riddler.Screens.validate_screen(document, @screen_key, %{"responses" => responses}) do
case Riddler.Screens.validate_screen(document, @screen_key, root) do
:ok -> []
{:error, findings} -> findings
end
Expand Down Expand Up @@ -204,5 +250,11 @@ defmodule StatifierExamples.Signup.Validation do
defp reader_message(%Finding{code: "response.format", element_key: key}, formats),
do: Map.get(@format_messages, Map.get(formats, key))

# A failing check is told in its author's words (the moduledoc's "A
# question's own checks, against the host's context").
defp reader_message(%Finding{field: "checks", author_message: message}, _formats)
when is_binary(message),
do: message

defp reader_message(_finding, _formats), do: nil
end
7 changes: 4 additions & 3 deletions lib/statifier_examples_web/journey_host.ex
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ defmodule StatifierExamplesWeb.JourneyHost do
one `Signup.Journey`'s view is drawn from (its `answer`). A submit the
screen refuses answers its findings as `Riddler.Finding` structs, each
carrying this app's words for it as its `author_message`
(`StatifierExamples.Signup.Validation.check/2`), which is what the
(the refused view's `refusals`, `StatifierExamples.Signup.Validation.check/3`'s
answer), which is what the
component draws beside the question. An execution, a Path or a name
this module does not have is `{:error, :no_such_journey}`.

Expand Down Expand Up @@ -83,7 +84,7 @@ defmodule StatifierExamplesWeb.JourneyHost do
alias StatifierExamples.Charts.Durable
alias StatifierExamples.Library.{Onboarding, RegistrationSteps, Setups}
alias StatifierExamples.ScreenEditor.Try
alias StatifierExamples.Signup.{Journey, Validation}
alias StatifierExamples.Signup.Journey
alias StatifierExamplesWeb.JourneyAccess

# The signup Path, named for a start: on the page it is the Path no
Expand Down Expand Up @@ -264,7 +265,7 @@ defmodule StatifierExamplesWeb.JourneyHost do
with {:ok, path, execution_id, {target, opts}} <- target(journey) do
case Journey.submit(target, outcome, responses, opts) do
{:ok, view} -> stepped(path, execution_id, view)
{:invalid, view} -> refused(view, Validation.check(view.nodes, responses))
{:invalid, view} -> refused(view, view.refusals)
{:error, reason} -> failed(reason)
end
end
Expand Down
71 changes: 71 additions & 0 deletions test/statifier_examples/screen_editor/try_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,77 @@ defmodule StatifierExamples.ScreenEditor.TryTest do
assert refused.findings == [{"age", "must be a whole number"}]
end

# Sabotage: made Journey's checked/4 validate the shown nodes without
# putting their checks back; the future date was accepted and the
# :invalid match went red, then reverted from a copy. Sabotage: made
# context/1 ignore opts[:today]; the press on the 19th was accepted,
# then reverted from a copy.
test "holds the date of birth to its check, against the host's today" do
{:ok, document} =
"priv/fixtures/patron_registration_screens.json" |> File.read!() |> Document.from_json()

{:ok, %{execution_id: execution_id, opts: opts}} = Try.start(document)

details = %{
"first_name" => "Rosa",
"email" => "rosa@example.com",
"age" => "34",
"birth_date" => "2026-11-20",
"library_pin" => "1234"
}

on = fn day -> opts ++ [today: Date.from_iso8601!(day)] end

assert {:invalid, refused} =
Journey.submit(execution_id, "details_submitted", details, on.("2026-11-19"))

assert refused.findings == [{"birth_date", "A date of birth cannot be in the future."}]

assert [
%Riddler.Finding{
code: "check.birth_date_in_future",
element_key: "birth_date",
author_message: "A date of birth cannot be in the future."
}
] = refused.refusals

{:ok, still} = Journey.current(execution_id, opts)
assert %{key: "patron_details"} = still.screen
refute Map.has_key?(still, :refusals)

assert {:ok, card} =
Journey.submit(execution_id, "details_submitted", details, on.("2026-11-21"))

assert %{key: "card_choice"} = card.screen
refute Map.has_key?(card, :refusals)
end

# Sabotage: made submit/4 take the context the press carries when it
# carries one; the press was accepted and the :invalid match
# went red, then reverted from a copy. Sabotage: made the default
# today 9999-12-31; the year 2999 was accepted, then reverted.
test "takes its today from the host's clock, never from the press" do
{:ok, document} =
"priv/fixtures/patron_registration_screens.json" |> File.read!() |> Document.from_json()

{:ok, %{execution_id: execution_id, opts: opts}} = Try.start(document)

details = %{
"first_name" => "Rosa",
"email" => "rosa@example.com",
"age" => "34",
"birth_date" => "2999-01-01",
"library_pin" => "1234",
"context" => %{"today" => "3000-01-01"},
"today" => "3000-01-01"
}

assert {:invalid, refused} =
Journey.submit(execution_id, "details_submitted", details, opts)

assert refused.findings == [{"birth_date", "A date of birth cannot be in the future."}]
end

# The fixture is where the boolean and choice blocks' `help` field is
# used. Sabotage: took the boolean question's help out of the fixture; the
# card screen presented one help line and this went red, then reverted
Expand Down
Loading
Loading