commit 8ee32bb6434784be3b21831f40e07312aad02d97
parent 90740da83d21a017387ba6772f4cda37659f9264
Author: Florian Dold <dold@taler.net>
Date: Mon, 23 Nov 2026 17:35:30 +0100
merchant web UI: edit fountain grants and export onboarding codes
Validate the grant in place and focus the field that needs attention.
Allow the merchant to copy, print or download the newly created
credential.
Diffstat:
4 files changed, 876 insertions(+), 0 deletions(-)
diff --git a/packages/taler-merchant-webui/src/routes/fountains.test.tsx b/packages/taler-merchant-webui/src/routes/fountains.test.tsx
@@ -0,0 +1,281 @@
+/*
+ This file is part of GNU Taler
+ (C) 2026 Taler Systems S.A.
+
+ GNU Taler is free software; you can redistribute it and/or modify it under the
+ terms of the GNU General Public License as published by the Free Software
+ Foundation; either version 3, or (at your option) any later version.
+
+ GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
+ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+ A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along with
+ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
+ */
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { render, VNode } from "preact";
+import { act } from "preact/test-utils";
+import {
+ encodeCrock,
+ FountainCreateRequest,
+ Result,
+ TalerUriAction,
+ TalerUris,
+} from "@gnu-taler/taler-util";
+import { FountainFormScreen } from "../screens/FountainFormScreen.js";
+import { FountainCreatedScreen } from "../screens/FountainCreatedScreen.js";
+import {
+ defaultFountain,
+ fountainImportUri,
+ fountainValidationError,
+} from "../utils/fountains.js";
+import { normalizeApiFailure } from "../api/failure.js";
+import { RemoteResource } from "../api/contracts.js";
+import { ok, conflict } from "../testing/fake-http.js";
+import { PRINT_ROOT_ID } from "../utils/print.js";
+import type { TranslateFn } from "../context/translation.js";
+
+const secret = encodeCrock(new Uint8Array(32).fill(43));
+const backend = "https://fountain.example/shop/";
+const translate: TranslateFn = (strings, ...values) =>
+ typeof strings === "string"
+ ? strings
+ : strings.reduce((s, part, i) => s + part + (values[i] ?? ""), "");
+function resource<T>(data: T): RemoteResource<T> {
+ return {
+ data,
+ error: undefined,
+ isLoading: false,
+ isRefreshing: false,
+ refresh: async () => {},
+ };
+}
+async function flush() {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+}
+function mount(view: VNode) {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ act(() => render(view, container));
+ return {
+ container,
+ close() {
+ act(() => render(null, container));
+ container.remove();
+ },
+ };
+}
+function field(container: HTMLElement, selector: string, value: string) {
+ const input = container.querySelector<HTMLInputElement>(selector);
+ assert.ok(input, selector);
+ act(() => {
+ input.value = value;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+async function click(container: HTMLElement, label: string) {
+ const button = [...container.querySelectorAll("button")].find(
+ (b) => b.textContent?.trim() === label,
+ );
+ assert.ok(button, label);
+ await act(async () => button.click());
+ await flush();
+}
+async function submit(container: HTMLElement) {
+ const form = container.querySelector("form");
+ assert.ok(form);
+ await act(async () => {
+ form.dispatchEvent(
+ new Event("submit", { bubbles: true, cancelable: true }),
+ );
+ });
+ await flush();
+}
+function assertSecretNotPersisted() {
+ const values = [window.location.href, JSON.stringify(window.history.state)];
+ for (const storage of [localStorage, sessionStorage])
+ for (let i = 0; i < storage.length; i++)
+ values.push(storage.getItem(storage.key(i)!) ?? "");
+ assert.ok(!values.join(" ").includes(secret));
+}
+
+test("fountain grant validation permits empty grants and enforces protocol bounds", () => {
+ assert.equal(fountainValidationError(defaultFountain, translate), undefined);
+ const valid: FountainCreateRequest = {
+ ...defaultFountain,
+ grants: [
+ {
+ token_family_slug: "student",
+ tokens_per_period_limit: 2,
+ tokens_per_period_stash: 1,
+ key_window_size: 12,
+ },
+ ],
+ };
+ assert.equal(fountainValidationError(valid, translate), undefined);
+ for (const change of [
+ { tokens_per_period_limit: -1 },
+ { tokens_per_period_stash: 3 },
+ { tokens_per_period_stash: 0.5 },
+ { key_window_size: 13 },
+ { token_family_slug: "" },
+ { tokens_per_period_limit: Number.MAX_SAFE_INTEGER + 1 },
+ ]) {
+ assert.ok(
+ fountainValidationError(
+ { ...valid, grants: [{ ...valid.grants[0]!, ...change }] },
+ translate,
+ ),
+ );
+ }
+ assert.ok(
+ fountainValidationError(
+ { ...valid, grants: [...valid.grants, ...valid.grants] },
+ translate,
+ ),
+ );
+ assert.ok(
+ fountainValidationError(
+ {
+ ...valid,
+ grants: Array.from({ length: 193 }, (_, i) => ({
+ ...valid.grants[0]!,
+ token_family_slug: String(i),
+ })),
+ },
+ translate,
+ ),
+ );
+ assert.ok(
+ fountainValidationError({ ...valid, poll_freq: { d_us: NaN } }, translate),
+ );
+ assert.equal(
+ fountainValidationError(
+ { ...valid, poll_freq: { d_us: "forever" } },
+ translate,
+ ),
+ undefined,
+ );
+});
+
+test("fountain editor preserves input on rejection and submits edited grants", async () => {
+ let submitted: FountainCreateRequest | undefined;
+ const view = mount(
+ <FountainFormScreen
+ supportsDisplayName
+ families={resource([{ slug: "student", name: "Student pass" }])}
+ onCancel={() => {}}
+ onSave={async (body) => {
+ submitted = body;
+ return {
+ type: "failure",
+ error: normalizeApiFailure(conflict({ code: 1, hint: "denied" })),
+ };
+ }}
+ />,
+ );
+ try {
+ field(view.container, "#fountain-description", "Campus promotion");
+ await submit(view.container);
+ assert.equal(Boolean(submitted), false);
+ assert.equal(document.activeElement?.id, "fountain-name");
+ field(view.container, "#fountain-name", " Student benefits ");
+ await click(view.container, "Add grant");
+ const select = view.container.querySelector<HTMLSelectElement>(
+ "select#fountain-family-0",
+ )!;
+ act(() => {
+ select.value = "student";
+ select.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ field(view.container, "#fountain-tokens_per_period_limit-0", "5");
+ field(view.container, "#fountain-key_window_size-0", "2");
+ await submit(view.container);
+ assert.equal(submitted?.description, "Campus promotion");
+ assert.equal(submitted?.name, "Student benefits");
+ assert.deepEqual(submitted?.grants, [
+ {
+ token_family_slug: "student",
+ tokens_per_period_limit: 5,
+ tokens_per_period_stash: 1,
+ key_window_size: 2,
+ },
+ ]);
+ assert.equal(
+ view.container.querySelector<HTMLInputElement>("#fountain-description")!
+ .value,
+ "Campus promotion",
+ );
+ assert.match(view.container.textContent ?? "", /Could not save fountain/);
+ await click(view.container, "Remove");
+ await submit(view.container);
+ assert.deepEqual(submitted?.grants, []);
+ } finally {
+ view.close();
+ }
+});
+
+test("import URI preserves the merchant instance and HTTP scheme", () => {
+ for (const scheme of ["http", "https"]) {
+ const base = `${scheme}://merchant.example/shop/instances/campus/`;
+ const uri = fountainImportUri(base, "campaign", secret);
+ const parsed = Result.orUndefined(
+ TalerUris.parseRestricted(uri, TalerUriAction.Fountain),
+ );
+ assert.ok(parsed);
+ assert.equal(parsed.merchantBaseUrl, base);
+ assert.equal(parsed.fountainSecret, secret);
+ assert.equal(uri.startsWith("taler+http:"), scheme === "http");
+ }
+});
+
+test("creation view copies, prints and downloads the same import URI", async (t) => {
+ const uri = fountainImportUri(backend, "campaign", secret);
+ let printed = "",
+ copied = "";
+ const originalPrint = window.print;
+ window.print = () => {
+ printed = document.getElementById(PRINT_ROOT_ID)?.textContent ?? "";
+ };
+ t.after(() => {
+ window.print = originalPrint;
+ });
+ t.mock.method(navigator.clipboard, "writeText", async (text: string) => {
+ copied = text;
+ });
+ const view = mount(
+ <FountainCreatedScreen
+ fountain={{ id: "campaign", description: "Campus", uri }}
+ onDone={() => {}}
+ />,
+ );
+ try {
+ await click(view.container, "Copy URI");
+ assert.equal(copied, uri);
+ await click(view.container, "Print QR code");
+ assert.ok(printed.includes(uri));
+ assert.equal(document.getElementById(PRINT_ROOT_ID)?.textContent, "");
+ const links = [
+ ...view.container.querySelectorAll<HTMLAnchorElement>("a[download]"),
+ ];
+ assert.equal(links.length, 2);
+ assert.ok(
+ decodeURIComponent(
+ links.find((a) => a.download.endsWith(".txt"))!.href,
+ ).includes(uri),
+ );
+ assert.ok(
+ links
+ .find((a) => a.download.endsWith(".svg"))!
+ .href.startsWith("data:image/svg+xml"),
+ );
+ assertSecretNotPersisted();
+ } finally {
+ view.close();
+ }
+});
diff --git a/packages/taler-merchant-webui/src/screens/FountainCreatedScreen.tsx b/packages/taler-merchant-webui/src/screens/FountainCreatedScreen.tsx
@@ -0,0 +1,92 @@
+/*
+ This file is part of GNU Taler
+ (C) 2026 Taler Systems S.A.
+
+ GNU Taler is free software; you can redistribute it and/or modify it under the
+ terms of the GNU General Public License as published by the Free Software
+ Foundation; either version 3, or (at your option) any later version.
+
+ GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
+ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+ A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along with
+ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
+ */
+
+import type { VNode } from "preact";
+import { useRef } from "preact/hooks";
+import { Header } from "../ui/Header.js";
+import { Button } from "../ui/Button.js";
+import { TalerQrCode, generateQrDataUrl } from "../ui/TalerQrCode.js";
+import { printElement } from "../utils/print.js";
+import { useTranslation } from "../context/translation.js";
+import type { CreatedFountain } from "../utils/fountains.js";
+
+export function FountainCreatedScreen({
+ fountain,
+ onDone,
+}: {
+ fountain: CreatedFountain;
+ onDone: () => void;
+}): VNode {
+ const { t } = useTranslation();
+ const sheet = useRef<HTMLDivElement>(null);
+ const qr = generateQrDataUrl(fountain.uri);
+ const downloadClass =
+ "inline-block rounded-lg bg-gray-100 px-4 py-2 text-xs font-bold text-gray-800 hover:bg-gray-200";
+ return (
+ <div class="space-y-6">
+ <Header
+ title={t`Fountain created`}
+ onBack={onDone}
+ backLabel={t`Fountain details`}
+ />
+ <p class="rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">{t`Save this import code now. It is shown only once. Anyone with the code can withdraw this fountain’s discounts and passes.`}</p>
+ <div
+ ref={sheet}
+ data-print-sheet
+ class="max-w-2xl rounded-xl border bg-white p-6 text-center space-y-4"
+ >
+ <h2 class="font-bold text-lg break-words">
+ {fountain.description || fountain.id}
+ </h2>
+ <div class="flex justify-center [&_.taler-qr-copy-button]:print:hidden">
+ <TalerQrCode
+ url={fountain.uri}
+ copyUrl={fountain.uri}
+ size={280}
+ alt={t`Fountain import QR code`}
+ />
+ </div>
+ <p class="text-sm text-gray-600">{t`Scan with a Taler wallet to import this fountain.`}</p>
+ <div
+ data-print-uri
+ class="select-all break-all rounded-lg bg-gray-50 p-3 text-xs font-mono"
+ aria-label={t`Wallet import URI`}
+ >
+ {fountain.uri}
+ </div>
+ <div data-print-hide class="flex flex-wrap justify-center gap-3">
+ <Button
+ variant="secondary"
+ onClick={() => printElement(sheet.current)}
+ >{t`Print QR code`}</Button>
+ {qr.type === "success" && (
+ <a
+ class={downloadClass}
+ href={qr.url}
+ download={`fountain-${fountain.id}.svg`}
+ >{t`Download QR code`}</a>
+ )}
+ <a
+ class={downloadClass}
+ href={`data:text/plain;charset=utf-8,${encodeURIComponent(fountain.uri + "\n")}`}
+ download={`fountain-${fountain.id}.txt`}
+ >{t`Download URI`}</a>
+ </div>
+ </div>
+ <Button onClick={onDone}>{t`I have saved it — Done`}</Button>
+ </div>
+ );
+}
diff --git a/packages/taler-merchant-webui/src/screens/FountainFormScreen.tsx b/packages/taler-merchant-webui/src/screens/FountainFormScreen.tsx
@@ -0,0 +1,387 @@
+/*
+ This file is part of GNU Taler
+ (C) 2026 Taler Systems S.A.
+
+ GNU Taler is free software; you can redistribute it and/or modify it under the
+ terms of the GNU General Public License as published by the Free Software
+ Foundation; either version 3, or (at your option) any later version.
+
+ GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
+ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+ A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along with
+ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
+ */
+
+import type { VNode } from "preact";
+import { useLayoutEffect, useRef, useState } from "preact/hooks";
+import type {
+ FountainCreateRequest,
+ FountainGrant,
+} from "@gnu-taler/taler-util";
+import type { MutationResult, RemoteResource } from "../api/contracts.js";
+import { Header } from "../ui/Header.js";
+import { Button } from "../ui/Button.js";
+import { DurationInput } from "../ui/DurationInput.js";
+import { ReadErrorBanner } from "../ui/ReadErrorBanner.js";
+import { useFormFeedback } from "../ui/FormActionFooter.js";
+import { ApiErrorBanner } from "../ui/ApiErrorBanner.js";
+import { useTranslation } from "../context/translation.js";
+import {
+ defaultFountain,
+ fountainValidationError,
+ FountainFamilyChoice,
+} from "../utils/fountains.js";
+
+export interface FountainFormScreenProps {
+ initial?: FountainCreateRequest;
+ editing?: boolean;
+ supportsDisplayName?: boolean;
+ families: RemoteResource<FountainFamilyChoice[]>;
+ onSave: (body: FountainCreateRequest) => Promise<MutationResult<void>>;
+ onCancel: () => void;
+}
+export function FountainFormScreen({
+ initial = defaultFountain,
+ editing = false,
+ supportsDisplayName = false,
+ families,
+ onSave,
+ onCancel,
+}: FountainFormScreenProps): VNode {
+ const { t } = useTranslation();
+ const [value, setValue] = useState<FountainCreateRequest>(() =>
+ structuredClone(initial),
+ );
+ const [pending, setPending] = useState(false);
+ const lock = useRef(false);
+ const [error, setError] = useState<unknown>();
+ const { fieldProps, fieldError, field, feedbackId, setErrorMsg } =
+ useFormFeedback();
+ useLayoutEffect(() => {
+ if (field) document.getElementById(field)?.focus();
+ }, [field, feedbackId]);
+ const [durationValid, setDurationValid] = useState(true);
+ const [uncertain, setUncertain] = useState(false);
+ const fieldClass =
+ "w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500";
+ const choices = families.data ?? [];
+ const nameRequired =
+ supportsDisplayName && (!editing || value.name !== undefined);
+ const changeGrant = (index: number, update: Partial<FountainGrant>) =>
+ setValue((v) => ({
+ ...v,
+ grants: v.grants.map((g, i) => (i === index ? { ...g, ...update } : g)),
+ }));
+ return (
+ <div class="space-y-6">
+ <Header
+ title={editing ? t`Edit fountain` : t`Create fountain`}
+ onBack={pending ? undefined : onCancel}
+ backLabel={t`Fountains`}
+ subtitle={t`Choose which discounts or passes wallets can collect and how many they may receive.`}
+ />
+ <ApiErrorBanner error={error} title={t`Could not save fountain`} />
+ {uncertain && (
+ <p
+ role="alert"
+ class="rounded-lg bg-amber-50 p-4 text-sm text-amber-900"
+ >{t`The fountain may have been created, but its import code was not received. Check the fountain list before creating another one. A lost import code cannot be retrieved.`}</p>
+ )}
+ <form
+ noValidate
+ onInput={() => {
+ if (field) setErrorMsg("");
+ }}
+ onSubmit={async (e) => {
+ e.preventDefault();
+ if (lock.current) return;
+ if (nameRequired && !value.name?.trim()) {
+ setErrorMsg(
+ t`Enter a name customers will recognize.`,
+ "fountain-name",
+ );
+ return;
+ }
+ const invalid = durationValid
+ ? fountainValidationError(value, t)
+ : {
+ field: "fountain-polling",
+ message: t`Enter a valid wallet polling interval.`,
+ };
+ if (invalid) {
+ setErrorMsg(invalid.message, invalid.field);
+ return;
+ }
+ setErrorMsg("");
+ lock.current = true;
+ setPending(true);
+ setError(undefined);
+ setUncertain(false);
+ try {
+ const result = await onSave(
+ structuredClone({
+ description: value.description,
+ poll_freq: value.poll_freq,
+ grants: value.grants,
+ ...(supportsDisplayName &&
+ value.name !== initial.name && { name: value.name?.trim() }),
+ }),
+ );
+ if (result.type === "failure") {
+ setError(result.error);
+ setUncertain(
+ !editing &&
+ (result.error.outcome === "indeterminate" ||
+ (result.error.httpStatus ?? 0) >= 500),
+ );
+ }
+ } finally {
+ lock.current = false;
+ setPending(false);
+ }
+ }}
+ class="space-y-6"
+ >
+ <fieldset disabled={pending} class="space-y-6">
+ <section class="rounded-xl border border-gray-200 bg-white p-5 space-y-4">
+ {supportsDisplayName && (
+ <div>
+ <label
+ class="block text-sm font-bold mb-1"
+ for="fountain-name"
+ >{t`Name`}</label>
+ <input
+ id="fountain-name"
+ class={fieldClass}
+ required={nameRequired}
+ {...fieldProps("fountain-name")}
+ aria-describedby={
+ field === "fountain-name"
+ ? "fountain-name-error"
+ : "fountain-name-help"
+ }
+ value={value.name ?? ""}
+ onInput={(e) =>
+ setValue({ ...value, name: e.currentTarget.value })
+ }
+ />
+ {field === "fountain-name" ? (
+ fieldError("fountain-name")
+ ) : (
+ <p
+ id="fountain-name-help"
+ class="mt-1 text-xs text-gray-500"
+ >{t`Enter a name customers will recognize.`}</p>
+ )}
+ </div>
+ )}
+ <div>
+ <label
+ class="block text-sm font-bold mb-1"
+ for="fountain-description"
+ >{t`Description`}</label>
+ <input
+ id="fountain-description"
+ class={fieldClass}
+ value={value.description}
+ onInput={(e) =>
+ setValue({ ...value, description: e.currentTarget.value })
+ }
+ />
+ <p class="mt-1 text-xs text-gray-500">{t`Use a campaign or reference name rather than personal information.`}</p>
+ </div>
+ <DurationInput
+ id="fountain-polling"
+ {...fieldProps("fountain-polling")}
+ label={t`Wallet polling interval`}
+ helpText={t`How often wallets check for changes to these grants.`}
+ valueUs={value.poll_freq.d_us}
+ onChangeUs={(d_us) =>
+ setValue((v) => ({ ...v, poll_freq: { d_us } }))
+ }
+ onValidityChange={setDurationValid}
+ required
+ />
+ {fieldError("fountain-polling")}
+ </section>
+ <section class="space-y-4">
+ <h2
+ id="fountain-grants"
+ tabindex={-1}
+ {...fieldProps("fountain-grants")}
+ class="font-bold text-lg"
+ >{t`Grants`}</h2>
+ {fieldError("fountain-grants")}
+ <ReadErrorBanner
+ resource={families}
+ title={t`Could not load discounts and passes`}
+ />
+ {families.isLoading && families.data === undefined && (
+ <p
+ role="status"
+ class="text-sm text-gray-600"
+ >{t`Loading discounts and passes…`}</p>
+ )}
+ {families.data?.length === 0 && (
+ <p class="text-sm text-gray-600">
+ {t`Create a discount or pass before adding grants.`}{" "}
+ <a
+ class="text-blue-700 underline"
+ href="#/subscriptions/new"
+ >{t`Create discount or pass`}</a>
+ </p>
+ )}
+ {value.grants.length === 0 && (
+ <p class="rounded-lg bg-gray-50 p-4 text-sm text-gray-600">{t`No grants. Wallets can import this fountain and wait for grants to be added.`}</p>
+ )}
+ {value.grants.map((grant, index) => (
+ <fieldset
+ key={index}
+ class="rounded-xl border border-gray-200 bg-white p-5 space-y-4"
+ >
+ <legend class="px-1 text-sm font-bold">{t`Grant ${index + 1}`}</legend>
+ <div class="flex items-end gap-3">
+ <div class="min-w-0 flex-1">
+ <label
+ class="block mb-1 text-sm font-bold"
+ for={`fountain-family-${index}`}
+ >{t`Discount or pass`}</label>
+ <select
+ id={`fountain-family-${index}`}
+ {...fieldProps(`fountain-family-${index}`)}
+ class={fieldClass}
+ value={grant.token_family_slug}
+ onChange={(e) =>
+ changeGrant(index, {
+ token_family_slug: e.currentTarget.value,
+ })
+ }
+ required
+ >
+ <option value="">{t`Choose a discount or pass`}</option>
+ {grant.token_family_slug &&
+ !choices.some(
+ (f) => f.slug === grant.token_family_slug,
+ ) && (
+ <option value={grant.token_family_slug}>
+ {grant.token_family_slug}
+ </option>
+ )}
+ {choices.map((f) => (
+ <option
+ key={f.slug}
+ value={f.slug}
+ disabled={value.grants.some(
+ (g, i) =>
+ i !== index && g.token_family_slug === f.slug,
+ )}
+ >
+ {f.name} ({f.slug})
+ </option>
+ ))}
+ </select>
+ {fieldError(`fountain-family-${index}`)}
+ </div>
+ <Button
+ variant="ghost"
+ aria-label={t`Remove grant ${index + 1}`}
+ onClick={() => {
+ setErrorMsg("");
+ setValue((v) => ({
+ ...v,
+ grants: v.grants.filter((_, i) => i !== index),
+ }));
+ }}
+ >{t`Remove`}</Button>
+ </div>
+ <div class="grid gap-4 sm:grid-cols-3">
+ {(
+ [
+ [
+ "tokens_per_period_limit",
+ t`Per-period limit`,
+ Number.MAX_SAFE_INTEGER,
+ ],
+ [
+ "tokens_per_period_stash",
+ t`Stocking target`,
+ Number.MAX_SAFE_INTEGER,
+ ],
+ ["key_window_size", t`Future periods`, 12],
+ ] as const
+ ).map(([field, label, max]) => (
+ <div key={field}>
+ <label
+ class="block mb-1 text-sm font-bold"
+ for={`fountain-${field}-${index}`}
+ >
+ {label}
+ </label>
+ <input
+ id={`fountain-${field}-${index}`}
+ {...fieldProps(`fountain-${field}-${index}`)}
+ type="number"
+ min={0}
+ max={max}
+ step={1}
+ required
+ class={fieldClass}
+ value={Number.isNaN(grant[field]) ? "" : grant[field]}
+ onInput={(e) =>
+ changeGrant(index, {
+ [field]:
+ e.currentTarget.value === ""
+ ? NaN
+ : Number(e.currentTarget.value),
+ })
+ }
+ />
+ {fieldError(`fountain-${field}-${index}`)}
+ </div>
+ ))}
+ </div>
+ <p class="text-xs text-gray-500">{t`The limit counts all tokens issued in a validity period. The stocking target is how many a wallet tries to keep. Future periods allow collecting tokens in advance.`}</p>
+ </fieldset>
+ ))}
+ <Button
+ variant="secondary"
+ disabled={
+ value.grants.length >= 192 ||
+ !choices.some(
+ (f) =>
+ !value.grants.some((g) => g.token_family_slug === f.slug),
+ )
+ }
+ onClick={() =>
+ setValue((v) => ({
+ ...v,
+ grants: [
+ ...v.grants,
+ {
+ token_family_slug: "",
+ tokens_per_period_limit: 1,
+ tokens_per_period_stash: 1,
+ key_window_size: 0,
+ },
+ ],
+ }))
+ }
+ >{t`Add grant`}</Button>
+ </section>
+ </fieldset>
+ <div class="flex justify-end gap-3 border-t pt-4">
+ <Button
+ variant="secondary"
+ disabled={pending}
+ onClick={onCancel}
+ >{t`Cancel`}</Button>
+ <Button type="submit" isLoading={pending}>
+ {editing ? t`Save changes` : t`Create fountain`}
+ </Button>
+ </div>
+ </form>
+ </div>
+ );
+}
diff --git a/packages/taler-merchant-webui/src/utils/fountains.ts b/packages/taler-merchant-webui/src/utils/fountains.ts
@@ -0,0 +1,116 @@
+/*
+ This file is part of GNU Taler
+ (C) 2026 Taler Systems S.A.
+
+ GNU Taler is free software; you can redistribute it and/or modify it under the
+ terms of the GNU General Public License as published by the Free Software
+ Foundation; either version 3, or (at your option) any later version.
+
+ GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
+ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+ A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along with
+ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
+ */
+
+import {
+ FountainCreateRequest,
+ HostPortPath,
+ TalerUriAction,
+ TalerUris,
+ decodeCrockFixed,
+} from "@gnu-taler/taler-util";
+import type { TranslateFn } from "../context/translation.js";
+
+export const defaultFountain: FountainCreateRequest = {
+ description: "",
+ poll_freq: { d_us: 3600_000_000 },
+ grants: [],
+};
+
+export function fountainValidationError(
+ value: FountainCreateRequest,
+ t: TranslateFn,
+): { field: string; message: string } | undefined {
+ const frequency = value.poll_freq.d_us;
+ if (
+ frequency !== "forever" &&
+ (!Number.isSafeInteger(frequency) || frequency < 0)
+ )
+ return {
+ field: "fountain-polling",
+ message: t`Enter a valid wallet polling interval.`,
+ };
+ if (value.grants.length > 192)
+ return {
+ field: "fountain-grants",
+ message: t`A fountain can have at most 192 grants.`,
+ };
+ const families = new Set<string>();
+ for (const [index, grant] of value.grants.entries()) {
+ if (!grant.token_family_slug)
+ return {
+ field: `fountain-family-${index}`,
+ message: t`Choose a discount or pass for every grant.`,
+ };
+ if (families.has(grant.token_family_slug))
+ return {
+ field: `fountain-family-${index}`,
+ message: t`Each discount or pass can appear only once.`,
+ };
+ families.add(grant.token_family_slug);
+ for (const field of [
+ "tokens_per_period_limit",
+ "tokens_per_period_stash",
+ "key_window_size",
+ ] as const) {
+ if (!Number.isSafeInteger(grant[field]) || grant[field] < 0)
+ return {
+ field: `fountain-${field}-${index}`,
+ message: t`Grant quantities must be nonnegative whole numbers.`,
+ };
+ if (
+ field === "tokens_per_period_stash" &&
+ grant.tokens_per_period_stash > grant.tokens_per_period_limit
+ )
+ return {
+ field: `fountain-tokens_per_period_stash-${index}`,
+ message: t`The stocking target must not exceed the per-period limit.`,
+ };
+ }
+ if (grant.key_window_size > 12)
+ return {
+ field: `fountain-key_window_size-${index}`,
+ message: t`Future periods must be between 0 and 12.`,
+ };
+ }
+ return undefined;
+}
+
+export function fountainImportUri(
+ baseUrl: string,
+ id: string,
+ secret: string,
+): string {
+ // Reject a malformed successful response before showing an unusable QR code.
+ decodeCrockFixed(secret, 32);
+ if (!/^[a-zA-Z0-9_-]+$/.test(id))
+ throw new Error("Invalid fountain identifier");
+ return TalerUris.stringify({
+ type: TalerUriAction.Fountain,
+ merchantBaseUrl: baseUrl as HostPortPath,
+ fountainId: id,
+ fountainSecret: secret,
+ });
+}
+
+export interface CreatedFountain {
+ id: string;
+ description: string;
+ uri: string;
+}
+export interface FountainFamilyChoice {
+ slug: string;
+ name: string;
+}