Render every notice through one part, and refuse a hand-written alert
A notice is now a closed Go value, notice.Notice, in a package that imports nothing of the console, rendered by one template part. It carries one of five tones named by meaning (Problem, Warning, Done, Information, Preview), its words as escaped runs (plain, strong, code), an optional link, an optional action that posts, a body only the console's own templates fill, and an optional close route. The part sets the glyph, the hidden "Error: " or "Warning: " a screen reader hears, and the role: alert for a Problem, status for the rest. A box takes its size from where it sits, full on a page and compact inside a card, a modal or a form's box; a line has no box. The preview tone is a pale fill with a 1px dashed edge, worn only by the form part's preview box and the Rows tray. Every alert at HEAD renders through the part: 83 in 49 files, plus the status lines and the checkout refusals. The 29 visible "Error:" prefixes go. A notice is closable only when its owner records the closing on its own row; the organization types error loses the close button that recorded nothing. The raw-notice lint refuses alert markup and alert roles outside the part, in templates and Go strings. The toasts move into one shared partial on every layout, member pages gain the load-time flash, the error toast stays until it is closed, the filler-copy lint reads the console's own scripts, and three toast strings drop "Please". The no-JS lookup's no-match answered 500 and now renders its notice. The organization type card showed a refused default change twice and now shows it once, in the form. The tier reorder preview's failed read moves to the form's own slot, outside the preview's status region. Closes #167 and #22.
This commit is contained in:
+47
-21
@@ -131,12 +131,12 @@ Use `text-bg-*` badge variants (`text-bg-secondary`, `text-bg-success`, etc.)
|
||||
rather than bare `bg-*` where contrast matters — `text-bg-*` pairs the
|
||||
background with a contrast-checked foreground.
|
||||
|
||||
### Alerts
|
||||
### Notices
|
||||
|
||||
`alert-success` / `alert-danger` / `alert-warning` are fine for **in-page,
|
||||
persistent** messaging (e.g. validation summaries rendered into a swap target).
|
||||
For **transient** success/error feedback that must survive an HTMX swap or
|
||||
navigation, use the toast primitives (§3) instead.
|
||||
Bootstrap's alert classes render only through the `notice` part (§6) and the
|
||||
form part's preview box and tray (§8); `member-console lint` fails one
|
||||
written anywhere else (`raw-notice`). Success and error feedback that must
|
||||
survive a swap is a toast (§3), never a notice.
|
||||
|
||||
### Forms
|
||||
|
||||
@@ -224,7 +224,9 @@ that comes before `shown.bs.modal` until that event fires.
|
||||
|
||||
### Error toast
|
||||
|
||||
Transient error feedback. Markup (`#errorToast`) lives in each layout's
|
||||
Error feedback that stays until its close button is pressed (W3C APG: avoid
|
||||
designing alerts that disappear automatically). Markup (`#errorToast`) lives in
|
||||
`partials/shell_toasts.html`, included by every layout inside its
|
||||
`.toast-container`; behavior in `static/error-handler.js`. It is shown
|
||||
automatically by the `htmx:response:error` handler (HTTP 4xx/5xx; silent for
|
||||
422, whose body lands inline per the validation contract) and the
|
||||
@@ -237,8 +239,10 @@ script: see §7 "Error responses".
|
||||
|
||||
### Success toast
|
||||
|
||||
Transient success feedback. Markup (`#successToast`) lives in each layout's
|
||||
`.toast-container`; behavior in `static/success-toast.js`.
|
||||
Transient success feedback that hides after five seconds. Markup
|
||||
(`#successToast`) lives in `partials/shell_toasts.html`, included by every
|
||||
layout inside its `.toast-container`; behavior in `static/success-toast.js`.
|
||||
Both surfaces support the load-time flash through the shell's `Flash`.
|
||||
|
||||
Triggered from the server via an `HX-Trigger` response header:
|
||||
|
||||
@@ -260,8 +264,9 @@ convention and timing for adopting it across flows.
|
||||
A create-then-land landing (`?flash=created`; design D20, round 2: "a
|
||||
success toast, not a banner") is a fresh top-level navigation, not an
|
||||
htmx-driven exchange, so no `HX-Trigger` header can reach it. Its confirmation
|
||||
instead rides `OperatorPageData.FlashSuccess`: `operator.html` pre-renders
|
||||
the message into `#successToast` and marks it `data-show-on-load`;
|
||||
instead rides `Shell.Flash` (`OperatorPageData.FlashSuccess` on the operator
|
||||
surface): `shell_toasts.html` pre-renders the message into `#successToast` and
|
||||
marks it `data-show-on-load`;
|
||||
`success-toast.js`'s load-time init shows it once and removes the marker.
|
||||
The `?flash=missing` bounce on a list page is unrelated — it is an error, not
|
||||
a confirmation, and stays an in-page `alert-danger`.
|
||||
@@ -279,8 +284,8 @@ confirm modal form).
|
||||
Empty collections render through the `emptyState` part (§6): build a
|
||||
`server.EmptyStateParams` in Go and `{{ template "emptyState" ... }}` in
|
||||
the template — never a hand-rolled centered block (lint-caught). The
|
||||
part's blocked branch names a missing prerequisite with a link to create
|
||||
it; the plain branch is centered muted text with an optional note. Keep
|
||||
part's blocked branch is a Warning notice whose link names the prerequisite
|
||||
and leads to where it is created; the plain branch is centered muted text with an optional note. Keep
|
||||
the copy specific ("No plan ladders yet.") rather than generic ("No
|
||||
data").
|
||||
|
||||
@@ -310,7 +315,8 @@ by itself.
|
||||
- **`aria-live` for async regions.** Content that appears without a navigation —
|
||||
toasts, and HTMX swap targets that surface validation or results — must be in
|
||||
an `aria-live` region so screen readers announce the change. Use `assertive`
|
||||
only for errors; `polite` for everything else.
|
||||
only for errors; `polite` for everything else. The notice part sets the role
|
||||
from the tone.
|
||||
- **Focus management.** Modals trap and restore focus (Bootstrap handles this for
|
||||
`.modal`). Do not remove focus outlines. Interactive controls must be
|
||||
reachable and operable by keyboard.
|
||||
@@ -488,7 +494,8 @@ exists.
|
||||
| `sectionSummary` | the same header as the `<summary>` of a native `<details>`, for a secondary section that opens on demand; the count rides in parentheses | `server.SectionHeader` |
|
||||
| `readout` | one headline count or amount: a small semibold uppercase muted label (the eyebrow, the console's one uppercase text) over an `fs-3` semibold value, with an optional small muted caption. A value that could not be loaded renders the em dash marker with its title and the caption "Count unavailable", never a zero; a value that needs an operator renders in the danger colour. The part renders no anchor and its label is never a link: when a readout navigates, its box is the link ("A linked card", below). The overview's tiles, the Stripe page's delivery queue and the Products page's catalog overview are its consumers | `server.Readout` |
|
||||
| `statusBadge` | a status badge from one state-to-style map: title-case label, one tone per state (`success`, `secondary`, `warning`, `danger`, `info`, `light` with a border), and an optional title that explains the state on its row ("Resumes when Pro ends" on an On hold badge). The part renders the title twice: as the badge's `title`, which a pointer shows on hover, and as visually hidden text after the label, so assistive technology reads it; a touch screen does not show the hover, an accepted cost (grant-resumption D8). The only `.badge` | `server.StatusBadge(state)`; an unknown state renders raw and `secondary`, and `TestStatusBadgeMapIsComplete` names it |
|
||||
| `emptyState` | the one empty-collection idiom: a warning alert naming the missing prerequisite when blocked, otherwise centered muted text with an optional note and outline action; no borders, no boxes, no bare "No X found." The branches and copy are `empty-state-guidance`'s | `server.EmptyStateParams` |
|
||||
| `emptyState` | the one empty-collection idiom: a Warning notice naming the missing prerequisite, its link the notice's link, when blocked, otherwise centered muted text with an optional note and outline action; no borders, no boxes, no bare "No X found." The branches and copy are `empty-state-guidance`'s | `server.EmptyStateParams` |
|
||||
| `notice` | a message about the page, a section or an outcome in one of five tones named by meaning (Problem, Warning, Done, Information; Preview only in the form part's preview box and the Rows tray), with the tone's glyph, a visually hidden "Error: " or "Warning: " before a Problem's or a Warning's words, `role="alert"` on a Problem and `role="status"` on the rest; a box whose size follows its container (page size outside any box, compact inside a card, a modal or the form part's box) or a boxless line; words as plain, strong and code runs built in Go, an optional link, one optional posting button (`notice.Action`), a body from the console's own templates only for rows, a list or more than one control, and a close button only when its owner names the route that records the closing; the only `.alert` besides the form part's preview box and tray; the zero value renders nothing | `notice.Notice` (`notice.Problem`, `notice.Warning`, `notice.Done`, `notice.Information`) |
|
||||
| `disabledControl` | a disabled button plus the reason it is disabled, always in the DOM and referenced by `aria-describedby`: a tooltip on a focusable wrapper (operator) or ordinary `<small>` text (member, the `Visible` variant); no hand-rolled `<span title="...">` | `server.DisabledControl` (`NewDisabledControl`, `.AsVisible()`) |
|
||||
| `helpIcon` | a help icon: a button that opens a Bootstrap popover on click, titled with the field or column it explains, with a close button in its header; Escape and a click outside the popover or its trigger also close it (`help-init.js`); no hand-rolled `<span title="...">` gloss (design D23) | `forms.Help` / `forms.HelpIcon` (`helpIcon(label, text string)`) |
|
||||
| the date-time part | a date-time cell on the organization page as two lines: the date on the first ("Sep 28, 2026"), the time on the second, muted and in 24-hour form ("19:35"), at the table's own text size. The grants ledger's Activated, Valid until and Ended cells, the When cells of Entitlement changes and Tier changes, the operator overview's Recent activity When and an entitlement set's History When render through it, so the page reads one way and a narrow column holds the cell without cutting it off; a date with no time of day (the Members table's Joined) stays one line and does not use it (grant-resumption D20) | the cell's date-time, formatted on the server |
|
||||
@@ -581,6 +588,22 @@ Rules the parts carry, stated once:
|
||||
`sectionSummary`; nothing else hides sections.
|
||||
- UI copy has no em dashes (the lone "—" empty-value marker is exempt);
|
||||
destructive actions confirm through the modal (§3), never `hx-confirm`.
|
||||
- A notice has a tone named by what happened, never by a colour. Problem,
|
||||
Warning, Done and Information each carry their own glyph, so colour is
|
||||
never the only signal (Carbon, Polaris and USWDS name tones by meaning),
|
||||
and a visually hidden "Error: " or "Warning: " leads a Problem's or a
|
||||
Warning's words, where a visible "Error:" would repeat what the glyph and
|
||||
the colour already say (GOV.UK writes the hidden word the same way). A
|
||||
Problem announces itself (`role="alert"`) and the other tones wait
|
||||
(`role="status"`). A box takes its size from its container, page size by
|
||||
itself and compact inside a card, a modal or the form part's box, so no
|
||||
author writes a padding, margin or text-size utility on a notice (Polaris
|
||||
gives a section's banner less spacing than a page's). A notice has a close
|
||||
button only when its owner stores the closing on its own record and names
|
||||
the route that records it, because a button that hides a message for one
|
||||
page load and brings it back on the next hides nothing (Carbon's
|
||||
dismissible notification). A field's notice (`forms.Field.Notice`) is one
|
||||
line under its control and is not this part.
|
||||
- A page arrives complete: every region that also exists as a partial is
|
||||
composed on the server through `server.Include` (an in-process request to
|
||||
the partial's route; integrations get it through `Deps`), never fetched
|
||||
@@ -592,7 +615,8 @@ What holds it: `member-console lint` fails a template that renders an
|
||||
`ui_section_header.html` and the shell's confirm dialog), a `.badge`, or a
|
||||
centered empty block outside the parts, an
|
||||
`hx-confirm`, a load-triggered fetch, an em dash in copy, a heading skip, a page body without the header,
|
||||
or an Actions column without its treatment (`actions-column`: the table's
|
||||
an alert class, a `role="alert"` or a `data-bs-dismiss="alert"` outside the
|
||||
notice part (`raw-notice`), or an Actions column without its treatment (`actions-column`: the table's
|
||||
`align-middle`, `text-end` on the header and on every cell holding a
|
||||
control, the header's word visually hidden, `ms-1` on every button in such
|
||||
a cell, Actions as the last column)
|
||||
@@ -827,9 +851,10 @@ library draws no box for a preview whose way out closes the modal
|
||||
(`form-library`, "A preview in the shared dialog renders no box of its own").
|
||||
|
||||
A `Preview` form (the tier reorder and removal previews, the org-type
|
||||
default-change card) is Stacked, rendered inside an
|
||||
`alert alert-secondary` box, its explanation (`Binding.Message`) in the
|
||||
same box, its commit labelled to match what it does ("Apply change") and
|
||||
default-change card) is Stacked, rendered inside the preview box (the
|
||||
preview tone: a pale fill and a dashed edge, §6), which carries no live
|
||||
role, its explanation (`Binding.Message`) in the same box with
|
||||
`role="status"`, its commit labelled to match what it does ("Apply change") and
|
||||
its way out "Discard": nothing was written, so there is nothing to undo,
|
||||
only a pending, server-rendered choice to drop (`forms.Discard`, a scoped
|
||||
GET that re-fetches the resting state).
|
||||
@@ -872,8 +897,8 @@ own shape and takes none.
|
||||
- A mutation refused for any reason answers **422**, with the same form
|
||||
re-rendered in submission mode: every submitted value carried back
|
||||
(including checkbox and radio state), each field's error under its
|
||||
control, the form-level error in the slot every form renders (empty
|
||||
when unused, `role="alert"`), and `autofocus` on the first errored
|
||||
control, the form-level error, a Problem notice, in the slot every form renders (empty
|
||||
when unused, no role of its own), and `autofocus` on the first errored
|
||||
control. The 200 body and the 422 body of one form share the outer
|
||||
element, so either swaps into the same target.
|
||||
- A mutation that **navigates** (a create page landing on the record, a
|
||||
@@ -1025,7 +1050,8 @@ to`, `Note that`, `It's worth noting`, `Keep in mind`. The lint rule
|
||||
`filler-copy` fails on these, case-insensitively on word boundaries, in
|
||||
template text, in an attribute value, and in a Go string literal under
|
||||
`internal/server`, `internal/web` or an integration's `web` package
|
||||
(tests excluded). The registry's own invariants separately refuse a hint
|
||||
(tests excluded); it also reads the string literals of the console's own
|
||||
scripts under `internal/embeds/static` (vendored bundles excluded). The registry's own invariants separately refuse a hint
|
||||
over 100 characters (the sources state the cap qualitatively, "a single
|
||||
short sentence"; this is the repo's own number) and a hint whose content
|
||||
words, once stopwords are dropped, are all already present in its label
|
||||
|
||||
@@ -56,7 +56,7 @@ Every mutation form on the operator surface uses HTMX, not native `<form method=
|
||||
| Pattern | When |
|
||||
|---------|------|
|
||||
| `HX-Trigger: {"showSuccessToast": "<message>"}` response header | A mutation handler returns success |
|
||||
| `<div class="alert alert-info">` rendered in the response body | The page itself is reporting a durable in-progress state (e.g., "Backfill in progress") |
|
||||
| An Information notice (`notice.Information`) in the region | The page itself is reporting a durable in-progress state (e.g., "Backfill in progress") |
|
||||
|
||||
The toast container lives outside the swap target so it survives `hx-boost` navigations and partial swaps (see [`design-system.md`](design-system.md) §3 "Success feedback"). The toast driver is `internal/embeds/static/success-toast.js`.
|
||||
|
||||
@@ -74,7 +74,7 @@ Keep it short. Operators read toasts in <1s of glance time — every extra word
|
||||
|
||||
**A toast reports the outcome of the work, not that the handler reached its end.** A handler that iterates rows states how many succeeded and how many failed; a run in which every row failed answers with `fireErrorToast`, because a green toast beside a failure banner leaves the operator with two contradictory readings of one mass mutation.
|
||||
|
||||
**Retired:** rendering `<div class="alert alert-success">` inside the response body of a mutation. That pattern pre-dated `showSuccessToast`; the forms library's outcome contract (`form-library`, `form-conventions`; `docs/design-system.md` §8) names the two mechanisms above as the only ones a mutation answers with, and the two remaining alert-in-body successes (org types, workspaces) were converted to the toast when their forms moved onto the library.
|
||||
**Retired:** rendering `<div class="alert alert-success">` inside the response body of a mutation. That pattern pre-dated `showSuccessToast`; the forms library's outcome contract (`form-library`, `form-conventions`; `docs/design-system.md` §8) names the two mechanisms above as the only ones a mutation answers with, and the two remaining alert-in-body successes (org types, workspaces) were converted to the toast when their forms moved onto the library. The notice part's change converted the two member answers left: a completed plan move (a plan change or a scheduled cancellation) and a released domain.
|
||||
|
||||
---
|
||||
|
||||
@@ -88,7 +88,7 @@ Keep it short. Operators read toasts in <1s of glance time — every extra word
|
||||
- 5xx → red toast; suppressed by `noSwap`, user input preserved
|
||||
- network failure / timeout → red toast
|
||||
|
||||
**Handler responsibility:** return proper HTTP status codes. Never return a 200 with an `.alert-danger` banner for a failure — the error handler keys off status, not body content. An error answer carries no `HX-` header: htmx 4 follows `HX-Redirect` and reloads the page on `HX-Refresh` whatever the status, so the session layer's 503 deletes every `HX-` header a handler set before the session store failed.
|
||||
**Handler responsibility:** return proper HTTP status codes. Never return a 200 with a Problem notice for a failure — the error handler keys off status, not body content. An error answer carries no `HX-` header: htmx 4 follows `HX-Redirect` and reloads the page on `HX-Refresh` whatever the status, so the session layer's 503 deletes every `HX-` header a handler set before the session store failed.
|
||||
|
||||
| Failure type | Status to return |
|
||||
|--------------|------------------|
|
||||
@@ -231,9 +231,9 @@ Every mutation waits for server confirmation before the UI updates. HTMX's reque
|
||||
| Don't | Do instead |
|
||||
|-------|------------|
|
||||
| `<form method="POST" action="...">` | `hx-post` (CSRF Origin-check is brittle on native POST) |
|
||||
| `<div class="alert alert-success">` in a mutation response (retired, design D9) | `HX-Trigger: {"showSuccessToast": "..."}` header for a mutation that stays, or `redirectToRecord`'s `HX-Redirect`/`303` pair for one that navigates |
|
||||
| A Done notice (`notice.Done`) in a mutation response (retired, design D9) | `HX-Trigger: {"showSuccessToast": "..."}` header for a mutation that stays, or `redirectToRecord`'s `HX-Redirect`/`303` pair for one that navigates |
|
||||
| `HX-Redirect` on a refusal (retired, design D9; integration settings did this before this change) | `422` with the same declared form re-rendered in submission mode |
|
||||
| Return 200 + `.alert-danger` for a failure | Return proper status code (422 / 4xx / 5xx); let `error-handler.js` funnel it |
|
||||
| Return 200 + a Problem notice (`notice.Problem`) for a failure | Return proper status code (422 / 4xx / 5xx); let `error-handler.js` funnel it |
|
||||
| `hx-confirm="Are you sure?"` | The confirm-action-modal contract |
|
||||
| `<span class="badge bg-info">` | `<span class="badge text-bg-info">` (bare `bg-*` fails WCAG AA contrast against Bootstrap defaults) |
|
||||
| Inline `<script>` in templates | Put JS in `internal/embeds/static/` and reference via `<script defer src>` (CSP `script-src 'self'` blocks inline) |
|
||||
@@ -273,6 +273,6 @@ Don't filter on `grants.status` for the "currently active" question. The status
|
||||
|
||||
## See also
|
||||
|
||||
- [`design-system.md`](design-system.md) — primitive definitions (modal, toast, badges, error handler)
|
||||
- [`design-system.md`](design-system.md) — primitive definitions (modal, toast, badges, error handler); §6 for the notice part
|
||||
- [`operator-ia.md`](operator-ia.md) — IA contract that forms/actions must not break
|
||||
- [`openspec/specs/operator-panel-navigation/spec.md`](../openspec/specs/operator-panel-navigation/spec.md) — the spec these conventions implement
|
||||
|
||||
+4
-2
@@ -323,12 +323,14 @@ checks, and `make lint-templates` is a sixth that runs on its own:
|
||||
`raw-page-title`, `raw-section-title`, `raw-badge`, `raw-empty-state`,
|
||||
`raw-form-control`, `form-without-part`, `disabled-outside-part`,
|
||||
`table-without-list-controls`, `actions-column`, `hx-confirm`,
|
||||
`load-fetch`, `heading-skip`.
|
||||
`load-fetch`, `heading-skip`, `raw-notice` (a notice written outside the
|
||||
notice part, in a template or a Go literal; it has no allowlist).
|
||||
Templates not yet rebuilt on the parts are listed in
|
||||
`internal/lint/anatomy_allowlist.txt`, which only shrinks:
|
||||
`allowlist-stale` fails an entry that no longer matches, and
|
||||
`allowlist-unreadable` a list it cannot read;
|
||||
- copy: `em-dash-copy`, `filler-copy`;
|
||||
- copy: `em-dash-copy`, `filler-copy` (which also reads the string literals
|
||||
of the console's own scripts);
|
||||
- specs: `spec-purpose-placeholder`, a spec under `openspec/specs/` whose
|
||||
Purpose is the archive's placeholder or empty;
|
||||
- locks: `advisory-lock-site`, `pool-lock-site`, `lock-families`;
|
||||
|
||||
+114
-15
@@ -12,7 +12,8 @@
|
||||
* - Use Bootstrap utilities/components directly in templates.
|
||||
* - Add a rule here only when Bootstrap genuinely cannot express it
|
||||
* (e.g. the HTMX loading-indicator hook, fixed toast positioning,
|
||||
* cross-browser <meter> styling, the linked card's hover shade).
|
||||
* cross-browser <meter> styling, the linked card's hover shade, the
|
||||
* notice part's layout and the preview tone).
|
||||
* - Reference Bootstrap CSS variables (var(--bs-*)) instead of
|
||||
* hardcoded color values so this file stays in sync if Bootstrap's
|
||||
* defaults change.
|
||||
@@ -364,6 +365,118 @@ legend.form-label {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* The notice part (templates/partials/ui_notice.html; spec page-anatomy
|
||||
* "Every notice renders through one part", "A notice is a box sized by its
|
||||
* container, or a line"). The box and the line are flex rows that do not
|
||||
* wrap and align to the first baseline: with flex-wrap the sentence dropped
|
||||
* under the glyph, so wrapped words now hang beside it, in their own
|
||||
* column, while the glyph, a control and the close button keep their size
|
||||
* (design decision 5). A line's words take only the room they need, so a
|
||||
* control sits .5rem after the last word; a box's words take the rest,
|
||||
* which keeps the close button at the right. A box inside a card, a modal
|
||||
* or the form part's box is compact; the preview box carries no
|
||||
* app-notice, so it keeps its own padding. A box that ends a card's or a
|
||||
* modal's body drops its bottom margin, because that body's padding
|
||||
* already closes it. A line is coloured with the tone's text-emphasis
|
||||
* variable, which holds 4.5:1 on white and on the preview fill where
|
||||
* Bootstrap's danger red and warning yellow do not. A link in a box reads
|
||||
* in the alert's own link colour and bold, because Bootstrap's blue falls
|
||||
* under 4.5:1 on every tinted fill. An action in a box takes the alert's
|
||||
* text colour, because the primary outline falls under 4.5:1 on every
|
||||
* tinted fill. */
|
||||
.app-notice {
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
align-items: baseline;
|
||||
gap: .5rem;
|
||||
}
|
||||
.app-notice-glyph,
|
||||
.app-notice > .btn,
|
||||
.app-notice > .btn-close {
|
||||
flex: none;
|
||||
}
|
||||
.app-notice-glyph {
|
||||
width: 1em;
|
||||
height: 1em;
|
||||
position: relative;
|
||||
top: .125em;
|
||||
}
|
||||
.app-notice-words {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.app-notice-line > .app-notice-words {
|
||||
flex: 0 1 auto;
|
||||
}
|
||||
:is(.card, .modal, .app-form-box) .alert.app-notice {
|
||||
--bs-alert-padding-y: .5rem;
|
||||
font-size: .875em;
|
||||
}
|
||||
:is(.card-body, .modal-body) > .alert.app-notice:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.app-notice-line {
|
||||
font-size: .875em;
|
||||
}
|
||||
.app-notice-line.app-notice-problem { color: var(--bs-danger-text-emphasis); }
|
||||
.app-notice-line.app-notice-warning { color: var(--bs-warning-text-emphasis); }
|
||||
.app-notice-line.app-notice-done { color: var(--bs-success-text-emphasis); }
|
||||
.app-notice-line.app-notice-information { color: var(--bs-info-text-emphasis); }
|
||||
.alert.app-notice a:not(.alert-link),
|
||||
.alert.app-notice .btn-link {
|
||||
color: var(--bs-alert-link-color);
|
||||
font-weight: 700;
|
||||
}
|
||||
.alert.app-notice > .btn-outline-primary {
|
||||
--bs-btn-color: var(--bs-alert-color);
|
||||
--bs-btn-border-color: var(--bs-alert-color);
|
||||
--bs-btn-hover-bg: var(--bs-alert-color);
|
||||
--bs-btn-hover-border-color: var(--bs-alert-color);
|
||||
--bs-btn-active-bg: var(--bs-alert-color);
|
||||
--bs-btn-active-border-color: var(--bs-alert-color);
|
||||
}
|
||||
|
||||
/* The preview tone (spec page-anatomy "Every notice renders through one
|
||||
* part"; worn only by the form part's preview box and the Rows tray, never
|
||||
* by the notice part): a pale fill and a dashed edge, because a preview
|
||||
* shows what a pending change will do with nothing written and is never a
|
||||
* warning. The edge is an image because a browser's own 1px dashes are
|
||||
* barely perceptible; the box keeps its size through border: 0 and
|
||||
* padding: calc(1rem + 1px). The edge colour is a literal because an image
|
||||
* cannot read a CSS variable, and #868e96 is no Bootstrap 5 variable; it
|
||||
* holds 3:1 on white and on the fill. The fill and the text colours are
|
||||
* Bootstrap's variables. The forced-colours rule removes the image and
|
||||
* restores a border, because Chromium keeps a url() background image under
|
||||
* forced colours and the box would show two edges. img-src data: is
|
||||
* already allowed (internal/middleware/security.go). */
|
||||
.app-notice-preview {
|
||||
--bs-alert-color: var(--bs-body-color);
|
||||
--bs-alert-bg: var(--bs-tertiary-bg);
|
||||
--bs-alert-link-color: var(--bs-body-color);
|
||||
border: 0;
|
||||
padding: calc(1rem + 1px);
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23868e96' stroke-width='2' stroke-dasharray='3 2'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat;
|
||||
background-size: 100% 100%;
|
||||
}
|
||||
/* A control inside the preview box takes the box's text colour: Bootstrap's
|
||||
* secondary outline (#6c757d) measures 4.45:1 on the preview fill, under AA. */
|
||||
.app-notice-preview .btn-outline-secondary {
|
||||
--bs-btn-color: var(--bs-alert-color);
|
||||
--bs-btn-border-color: var(--bs-alert-color);
|
||||
--bs-btn-hover-bg: var(--bs-alert-color);
|
||||
--bs-btn-hover-border-color: var(--bs-alert-color);
|
||||
--bs-btn-active-bg: var(--bs-alert-color);
|
||||
--bs-btn-active-border-color: var(--bs-alert-color);
|
||||
}
|
||||
@media (forced-colors: active) {
|
||||
.app-notice-preview {
|
||||
border: 1px dashed CanvasText;
|
||||
background-image: none;
|
||||
padding: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* The form library's four layout families (spec form-conventions "Forms use
|
||||
* the layout family their kind names"; design D10, D20, D21, D22).
|
||||
* Everything else a form needs is a Bootstrap class the form part already
|
||||
@@ -630,20 +743,6 @@ legend.form-label {
|
||||
}
|
||||
}
|
||||
|
||||
/* A control inside an alert takes the alert's own text colour. Bootstrap's
|
||||
* secondary outline (#6c757d) on the warning alert's background (#fff3cd)
|
||||
* measures 4.23:1, under AA; the alert's text colour (#664d03 on warning)
|
||||
* clears it on every alert tone (2026-09-02 Lighthouse re-run: the
|
||||
* not-configured state's Settings link on the FedWiki and Discourse pages). */
|
||||
.alert .btn-outline-secondary {
|
||||
--bs-btn-color: var(--bs-alert-color);
|
||||
--bs-btn-border-color: var(--bs-alert-color);
|
||||
--bs-btn-hover-bg: var(--bs-alert-color);
|
||||
--bs-btn-hover-border-color: var(--bs-alert-color);
|
||||
--bs-btn-active-bg: var(--bs-alert-color);
|
||||
--bs-btn-active-border-color: var(--bs-alert-color);
|
||||
}
|
||||
|
||||
/* Rail link colour (ACC-40, change acceptance-fixes 2026-09-02; chrome-
|
||||
* conventions "The shell meets AA contrast"). Bootstrap's default
|
||||
* --bs-link-color (#0d6efd) on the rail's bg-light (#f8f9fa) measures
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
// script steers that swap anymore. This script only reports:
|
||||
// htmx:response:error HTTP >= 400 — toast by status; 422 stays silent
|
||||
// htmx:error network failure or timeout — toast
|
||||
// The error toast stays until its close button is pressed (W3C APG: avoid
|
||||
// designing alerts that disappear automatically); the success toast hides
|
||||
// after five seconds (success-toast.js).
|
||||
|
||||
// Signal that a request's swap was suppressed or never landed (CSRF expiry,
|
||||
// 5xx, network error). sortable-reorder.js listens for this to recover a
|
||||
@@ -35,7 +38,7 @@ function showErrorToast(message) {
|
||||
return;
|
||||
}
|
||||
toastBody.textContent = message;
|
||||
const toast = new bootstrap.Toast(toastEl, { delay: 8000 });
|
||||
const toast = bootstrap.Toast.getOrCreateInstance(toastEl, { autohide: false });
|
||||
toast.show();
|
||||
}
|
||||
|
||||
@@ -66,7 +69,7 @@ document.body.addEventListener('htmx:response:error', function(evt) {
|
||||
// 401 with HX-Redirect and never reaches here.
|
||||
showErrorToast('Refused: the request did not come from this site.');
|
||||
} else {
|
||||
showErrorToast('Access denied. Please refresh the page and try again.');
|
||||
showErrorToast('Access denied. Refresh the page and try again.');
|
||||
}
|
||||
signalReorderRecover();
|
||||
return;
|
||||
@@ -81,7 +84,7 @@ document.body.addEventListener('htmx:response:error', function(evt) {
|
||||
|
||||
// Other 4xx swap by default — the server may return helpful error HTML —
|
||||
// but show a toast as backup.
|
||||
showErrorToast('Request failed. Please check your input and try again.');
|
||||
showErrorToast('Request failed. Check your input and try again.');
|
||||
});
|
||||
|
||||
// Request-level failures: network errors, timeouts (htmx 4 defaults to 60s).
|
||||
@@ -92,7 +95,7 @@ document.body.addEventListener('htmx:error', function(evt) {
|
||||
if (evt.target && evt.target.dataset && evt.target.dataset.loadCancelled === "true") {
|
||||
return;
|
||||
}
|
||||
showErrorToast('Network error. Please check your connection and try again.');
|
||||
showErrorToast('Network error. Check your connection and try again.');
|
||||
// No swap ever lands, so a drag-to-reorder started here stays frozen too.
|
||||
signalReorderRecover();
|
||||
});
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
// fresh top-level navigation, not an htmx-driven exchange, so no
|
||||
// HX-Trigger header can reach it. The server instead pre-renders the
|
||||
// message into #successToast and marks it `data-show-on-load`
|
||||
// (operator.html); this file's load-time init shows it once, then
|
||||
// (shell_toasts.html); this file's load-time init shows it once, then
|
||||
// removes the marker.
|
||||
//
|
||||
// CSP-safe: lives in static/ and is loaded via <script defer src>.
|
||||
@@ -47,7 +47,7 @@
|
||||
// navigation (the create panel's HX-Redirect), not an htmx-driven
|
||||
// exchange, so the HX-Trigger convention above cannot reach it: the
|
||||
// server instead pre-renders the message into #successToast and marks
|
||||
// it with data-show-on-load (operator.html). Shown once on load, then
|
||||
// it with data-show-on-load (shell_toasts.html). Shown once on load, then
|
||||
// the marker is removed so a later swap never re-fires it.
|
||||
function showFlashToastOnLoad() {
|
||||
var toastEl = document.getElementById("successToast");
|
||||
|
||||
@@ -49,29 +49,7 @@
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- Toast Container -->
|
||||
<div class="toast-container">
|
||||
<div id="errorToast" class="toast align-items-center text-bg-danger border-0" role="alert" aria-live="assertive"
|
||||
aria-atomic="true">
|
||||
<div class="d-flex">
|
||||
<div class="toast-body" id="errorToastBody">
|
||||
An error occurred. Try again.
|
||||
</div>
|
||||
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"
|
||||
aria-label="Close"></button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="successToast" class="toast align-items-center text-bg-success border-0" role="status" aria-live="polite"
|
||||
aria-atomic="true">
|
||||
<div class="d-flex">
|
||||
<div class="toast-body" id="successToastBody">
|
||||
Done.
|
||||
</div>
|
||||
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"
|
||||
aria-label="Close"></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{ template "shell_toasts.html" .Shell }}
|
||||
|
||||
{{ template "shell_confirm_modal.html" . }}
|
||||
|
||||
|
||||
@@ -50,39 +50,15 @@
|
||||
<main id="member-main" class="flex-fill p-4">
|
||||
<div class="container-xxl px-0">
|
||||
{{ template "pageHeader" .Header }}
|
||||
{{ if eq .CheckoutStatus "success" }}
|
||||
<div class="alert alert-success" role="alert">
|
||||
<strong>Thanks!</strong> We're finalizing your upgrade; this can take a moment.
|
||||
<a href="/products">View your plan on the Products page</a>.
|
||||
{{/* The billing facts the Products page showed (merchant-disclosure
|
||||
D5), repeated where the member is most likely to remember them.
|
||||
A plain line: muted text in a coloured alert falls under the
|
||||
contrast floor. */}}
|
||||
{{ if .BillingFacts.Shown }}<div class="mt-1">{{ range $i, $s := .BillingFacts.Sentences }}{{ if $i }} {{ end }}{{ $s }}{{ end }}</div>{{ end }}
|
||||
</div>
|
||||
{{ else if eq .CheckoutStatus "cancel" }}
|
||||
<div class="alert alert-secondary" role="alert">
|
||||
Checkout canceled. Your current plan is unchanged.
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .CheckoutNotice }}
|
||||
{{/* Pending domain claims (dissolve-member-domains): the durable
|
||||
re-entry point for an in-flight DNS verification now that the
|
||||
standalone Domains page is gone. Server-side conditional: no
|
||||
empty chrome when there is nothing pending. Opening a claim swaps
|
||||
the claim-status partial into this same .domains-surface wrapper;
|
||||
reopening mints nothing (pure read). */}}
|
||||
{{ if .PendingDomainClaims }}
|
||||
<div class="alert alert-info mt-3 domains-surface" role="status">
|
||||
<strong>Domain verification in progress.</strong>
|
||||
{{ range .PendingDomainClaims }}
|
||||
<div class="d-flex align-items-center gap-2 mt-1">
|
||||
<code class="text-break">{{ .Root }}</code>
|
||||
<button type="button" class="btn btn-link btn-sm p-0 align-baseline"
|
||||
hx-get="{{ routeURL "/partials/domains/claims/{claimID}" .ClaimID }}"
|
||||
hx-target="closest .domains-surface" hx-swap="innerHTML">View DNS records</button>
|
||||
</div>
|
||||
{{ end }}
|
||||
</div>
|
||||
the claim-status partial into this .domains-surface wrapper, which
|
||||
the notice no longer is; reopening mints nothing (pure read). */}}
|
||||
{{ if not .PendingClaimsNotice.Empty }}
|
||||
<div class="domains-surface mt-3">{{ template "notice" .PendingClaimsNotice }}</div>
|
||||
{{ end }}
|
||||
{{ template "sectionHeader" .AccountHeader }}
|
||||
<div class="card mb-3">
|
||||
@@ -140,32 +116,19 @@
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- Toast Container -->
|
||||
<div class="toast-container">
|
||||
<div id="errorToast" class="toast align-items-center text-bg-danger border-0" role="alert" aria-live="assertive"
|
||||
aria-atomic="true">
|
||||
<div class="d-flex">
|
||||
<div class="toast-body" id="errorToastBody">
|
||||
An error occurred. Try again.
|
||||
</div>
|
||||
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"
|
||||
aria-label="Close"></button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="successToast" class="toast align-items-center text-bg-success border-0" role="status" aria-live="polite"
|
||||
aria-atomic="true">
|
||||
<div class="d-flex">
|
||||
<div class="toast-body" id="successToastBody">
|
||||
Done.
|
||||
</div>
|
||||
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"
|
||||
aria-label="Close"></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{ template "shell_toasts.html" .Shell }}
|
||||
|
||||
{{ template "shell_confirm_modal.html" . }}
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
</html>
|
||||
|
||||
{{/* The checkout return's words (the notice's Body): the success's lead and
|
||||
link, then the billing facts the Products page showed (merchant-disclosure
|
||||
D5), repeated where the member is most likely to remember them. A plain
|
||||
line: muted text in a coloured alert falls under the contrast floor. */}}
|
||||
{{ define "checkoutReturnWords" }}<strong>Thanks!</strong> We're finalizing your upgrade; this can take a moment. <a href="/products">View your plan on the Products page</a>.{{ if .Shown }}<div class="mt-1">{{ range $i, $s := .Sentences }}{{ if $i }} {{ end }}{{ $s }}{{ end }}</div>{{ end }}{{ end }}
|
||||
|
||||
{{/* The pending claims' words: the bold lead and one row per claim. */}}
|
||||
{{ define "pendingClaimsWords" }}<strong>Domain verification in progress.</strong>{{ range . }}<div class="d-flex align-items-center gap-2 mt-1"><code class="text-break">{{ .Root }}</code><button type="button" class="btn btn-link btn-sm p-0 align-baseline" hx-get="{{ routeURL "/partials/domains/claims/{claimID}" .ClaimID }}" hx-target="closest .domains-surface" hx-swap="innerHTML">View DNS records</button></div>{{ end }}{{ end }}
|
||||
|
||||
@@ -149,28 +149,20 @@
|
||||
============================================================ -->
|
||||
{{ template "pageHeader" .LandingHeader }}
|
||||
|
||||
<!-- Setup banner (design D12/D28). The blue Bootstrap info alert;
|
||||
the maintainer's pick over a plain card on 2026-09-03,
|
||||
"I back the blue", keeping round 4's copy, which names no
|
||||
step count, matching the wording of the Getting started
|
||||
idiom. Renders above the lookup while the dismissal has not
|
||||
been recorded and at least one step is still incomplete;
|
||||
once every step derives complete the banner withdraws on
|
||||
its own, dismissed or not (SetupState.ShowBanner). The
|
||||
close button posts to the dismiss route and swaps the
|
||||
banner out with an empty response; dismissal is
|
||||
deployment-wide state (core.instance_settings), not a
|
||||
cookie, so no operator sees it again on any browser while
|
||||
the setting stands. The post carries no CSRF token: the
|
||||
server's origin check (internal/middleware/csrf.go) admits
|
||||
it as same-origin, as it does every other operator HTMX
|
||||
control on this page. -->
|
||||
{{ if .Setup.ShowBanner }}
|
||||
<div id="setup-banner" class="alert alert-info d-flex align-items-center justify-content-between gap-3" role="status">
|
||||
<span><strong>Getting started.</strong> Finish setting up {{ deploymentName }}. <a href="/operator/setup" class="alert-link">Continue setup</a></span>
|
||||
<button type="button" class="btn-close" aria-label="Dismiss the getting-started banner" hx-post="/partials/operator/setup/dismiss" hx-target="#setup-banner" hx-swap="outerHTML"></button>
|
||||
</div>
|
||||
{{ end }}
|
||||
<!-- Setup notice (design D12/D28). An information notice from
|
||||
OperatorPageData.SetupBanner: it renders above the lookup
|
||||
while the dismissal has not been recorded and at least one
|
||||
step is still incomplete; once every step derives complete
|
||||
it withdraws on its own, dismissed or not
|
||||
(SetupState.ShowBanner). Its close button posts to the
|
||||
dismiss route and swaps the notice out with an empty
|
||||
response; dismissal is deployment-wide state
|
||||
(core.instance_settings), not a cookie, so no operator sees
|
||||
it again on any browser while the setting stands. The post
|
||||
carries no CSRF token: the server's origin check
|
||||
(internal/middleware/csrf.go) admits it as same-origin, as
|
||||
it does every other operator HTMX control on this page. -->
|
||||
{{ template "notice" .SetupBanner }}
|
||||
|
||||
<!-- Region 1, Lookup. Single typed input resolves to person
|
||||
detail (email-exact or name-substring), org composite
|
||||
@@ -362,36 +354,7 @@
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
<!-- Toast Container — sibling of <main> so toasts survive hx-boost
|
||||
navigations and partial swaps (see docs/design-system.md §3). -->
|
||||
<div class="toast-container">
|
||||
<div id="errorToast" class="toast align-items-center text-bg-danger border-0" role="alert" aria-live="assertive"
|
||||
aria-atomic="true">
|
||||
<div class="d-flex">
|
||||
<div class="toast-body" id="errorToastBody">
|
||||
An error occurred. Try again.
|
||||
</div>
|
||||
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"
|
||||
aria-label="Close"></button>
|
||||
</div>
|
||||
</div>
|
||||
{{/* design D20, round 2 ("a success toast, not a banner"): a
|
||||
create-then-land page (?flash=created) pre-renders its
|
||||
confirmation into this shared toast, marked to auto-show on
|
||||
load; success-toast.js's init reads the marker (CSP-safe, no
|
||||
inline script), shows the toast, then removes the marker so it
|
||||
never re-fires on a later swap. */}}
|
||||
<div id="successToast" class="toast align-items-center text-bg-success border-0" role="status"
|
||||
aria-live="polite" aria-atomic="true"{{ if .FlashSuccess }} data-show-on-load="true"{{ end }}>
|
||||
<div class="d-flex">
|
||||
<div class="toast-body" id="successToastBody">
|
||||
{{ if .FlashSuccess }}{{ .FlashSuccess }}{{ else }}Done.{{ end }}
|
||||
</div>
|
||||
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"
|
||||
aria-label="Close"></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{ template "shell_toasts.html" .Shell }}
|
||||
|
||||
<!-- Shared confirmation modal (partials/shell_confirm_modal.html), a
|
||||
sibling of <main> so it survives boosted navigations. -->
|
||||
|
||||
@@ -9,10 +9,7 @@
|
||||
synced, recurring price is not listed (buildAddonsData; maintainer,
|
||||
2026-09-19), so no row carries text where its Add would be. Category
|
||||
chips render through statusBadge. */}}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else if eq (len .Addons) 0 }}
|
||||
{{/* No qualifying products: render nothing so the section is hidden. */}}
|
||||
{{ else }}
|
||||
@@ -49,7 +46,7 @@
|
||||
<button type="button" class="btn btn-outline-primary btn-sm ms-1"
|
||||
hx-post="/billing/checkout" hx-vals='{"price_id": "{{ .PriceID }}"}'
|
||||
hx-target="#addon-checkout-error-{{ .ProductID }}" hx-swap="innerHTML"{{ if $.BillingFacts.Shown }} aria-describedby="{{ $.BillingFacts.ID }}"{{ end }}>Add</button>
|
||||
<div id="addon-checkout-error-{{ .ProductID }}" class="small text-danger mt-1"></div>
|
||||
<div id="addon-checkout-error-{{ .ProductID }}"></div>
|
||||
</td>
|
||||
</tr>
|
||||
{{ end }}
|
||||
|
||||
@@ -10,12 +10,7 @@
|
||||
button is hx-post: a native form POST would fail CSRF (Origin is null
|
||||
under the no-referrer policy), while HTMX inherits the page's
|
||||
cross-origin protection, which needs no token. -->
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">{{ .Error }}</div>
|
||||
{{ end }}
|
||||
{{ if .Notice }}
|
||||
<div class="alert alert-success" role="status">{{ .Notice }}</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
|
||||
{{ if eq (len .Claims) 0 }}
|
||||
{{ template "emptyState" .Empty }}
|
||||
|
||||
@@ -19,42 +19,9 @@
|
||||
<h3 class="mt-2 mb-0 h6"><code class="text-break">{{ .Domain }}</code></h3>
|
||||
</div>
|
||||
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">{{ .Error }}</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
|
||||
{{ if .Hosted }}
|
||||
<div class="alert alert-secondary" role="status">
|
||||
<strong>{{ .Domain }}</strong> is part of our hosting; there's nothing for you to publish in DNS.
|
||||
Any name inside it is yours to use.
|
||||
</div>
|
||||
{{ else if .Canceled }}
|
||||
<div class="alert alert-secondary" role="status">
|
||||
Verification for <strong>{{ .Domain }}</strong> was canceled. The domain is free again; start
|
||||
over when you're ready.
|
||||
</div>
|
||||
{{ else if .Released }}
|
||||
<div class="alert alert-secondary" role="status">
|
||||
<strong>{{ .Domain }}</strong> was released. The domain is free again; claim it back at
|
||||
any time.
|
||||
</div>
|
||||
{{ else if .Expired }}
|
||||
<div class="alert alert-warning" role="alert">
|
||||
Verification for <strong>{{ .Domain }}</strong> expired before the DNS record was found. The
|
||||
domain is free again; restart verification at any time.
|
||||
</div>
|
||||
{{ else if .Verified }}
|
||||
{{ if .Placed }}
|
||||
<div class="alert alert-success" role="status">
|
||||
<strong>{{ .Domain }}</strong> is verified ✓ and in use. Any name inside it is yours too:
|
||||
creating a site there needs no further DNS verification.
|
||||
</div>
|
||||
{{ else }}
|
||||
<div class="alert alert-success" role="status">
|
||||
<strong>{{ .Domain }}</strong> is verified ✓. Create a site with it from the service card on your
|
||||
dashboard; creation is instant now, with no further DNS verification.
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ if not .Outcome.Empty }}{{ template "notice" .Outcome }}
|
||||
{{ else }}
|
||||
<p>To connect <strong>{{ .Domain }}</strong>, add these records at your DNS provider:</p>
|
||||
<div class="table-responsive">
|
||||
|
||||
@@ -10,10 +10,7 @@
|
||||
only; ui-vocabulary D4.3 bans raw-key badges, so the raw resource
|
||||
key is demoted to a title attribute). A suspended plan's line carries
|
||||
a Payment due or Paused badge after the tier name. */}}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else if and (not .HasEntitlements) (not .Enrolled) }}
|
||||
{{ template "emptyState" .Empty }}
|
||||
{{ else }}
|
||||
|
||||
@@ -20,11 +20,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
|
||||
<dl class="row mb-3">
|
||||
<dt class="col-sm-3">Amount due</dt>
|
||||
|
||||
@@ -11,10 +11,7 @@
|
||||
derivation the operator surface uses (Overdue wins; a paid invoice
|
||||
that did not cover its amount presents as partially paid). */}}
|
||||
{{ template "sectionHeader" .Header }}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else if eq (len .Invoices) 0 }}
|
||||
{{ template "emptyState" .Empty }}
|
||||
{{ else }}
|
||||
|
||||
@@ -7,10 +7,7 @@
|
||||
the plan cancel and keep controls (cancel through the shared confirm modal;
|
||||
design-system.md §3 bans hx-confirm). Badges render through statusBadge; the cancel chip
|
||||
carries the date itself, which is the fact a member needs. */}}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else if eq (len .Ladders) 0 }}
|
||||
{{ template "emptyState" .Empty }}
|
||||
{{ else }}
|
||||
@@ -19,11 +16,6 @@
|
||||
every ladder, only when a tier here offers a move that costs money
|
||||
and a name would not be recognised. */}}
|
||||
{{ template "billingFacts" .BillingFacts }}
|
||||
{{ if .Success }}
|
||||
<div class="alert alert-success" role="alert">
|
||||
{{ .Success }}
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ range .Ladders }}
|
||||
<div class="border-start border-3 ps-3 mb-4{{ if .Enrolled }} border-primary{{ else }} border-secondary-subtle{{ end }}">
|
||||
<h3 class="fw-bold mb-3 h6{{ if not .Enrolled }} text-muted{{ end }}">
|
||||
@@ -112,9 +104,7 @@
|
||||
{{ else if .Granted }}
|
||||
<p class="text-muted small mb-2">Granted</p>
|
||||
{{ end }}
|
||||
{{- if and .Suspension (or (not .PaidUnderGrant) (eq .Suspension "paused")) }}
|
||||
<p class="small text-danger mb-2">{{ if eq .Suspension "paused" }}Entitlements are suspended.{{ else }}Entitlements are suspended until the invoice is paid.{{ end }}</p>
|
||||
{{- end }}
|
||||
{{ template "notice" .SuspendedLine }}
|
||||
{{ else if .Held }}
|
||||
<p class="text-muted small mb-2">Granted</p>
|
||||
{{ else if .NoPriceTier }}
|
||||
@@ -190,7 +180,7 @@
|
||||
<button type="button" class="btn btn-outline-primary btn-sm w-100 mt-auto"
|
||||
hx-post="/billing/checkout" hx-vals='{"price_id": "{{ .PriceID }}"}'
|
||||
hx-target="#checkout-error-{{ .MoveLadderID }}-{{ .ProductID }}" hx-swap="innerHTML"{{ if $.BillingFacts.Shown }} aria-describedby="{{ $.BillingFacts.ID }}"{{ end }}>{{ .MoveLabel }}</button>
|
||||
<div id="checkout-error-{{ .MoveLadderID }}-{{ .ProductID }}" class="small text-danger mt-1"></div>
|
||||
<div id="checkout-error-{{ .MoveLadderID }}-{{ .ProductID }}"></div>
|
||||
{{ else if eq .MoveKind "switch" }}
|
||||
<button type="button" class="btn btn-outline-primary btn-sm w-100 mt-auto"
|
||||
data-bs-toggle="modal"
|
||||
|
||||
@@ -22,9 +22,7 @@
|
||||
renderBody. */}}
|
||||
{{ template "pageHeader" .Header }}
|
||||
|
||||
{{ if .TestMode }}
|
||||
<div class="alert alert-warning mb-3" role="alert">{{ .TestModeBanner.Sentence }} <a class="alert-link" href="{{ .TestModeBanner.SettingsLink.URL }}">{{ .TestModeBanner.SettingsLink.Label }}</a></div>
|
||||
{{ end }}
|
||||
{{ if .TestMode }}{{ template "notice" .TestModeBanner.Notice }}{{ end }}
|
||||
|
||||
{{ if not .Detail }}
|
||||
<ul class="nav nav-pills mb-3">
|
||||
|
||||
@@ -7,10 +7,7 @@
|
||||
through statusBadge, the empty and blocked states through emptyState.
|
||||
The organization cell is a cross-reference link; accounts have no
|
||||
detail page of their own today, so no first-column link. */}}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else }}
|
||||
{{ template "environmentNotice" .EnvNotice }}
|
||||
{{ if eq (len .Accounts) 0 }}
|
||||
|
||||
@@ -61,10 +61,7 @@
|
||||
<p class="text-body-secondary small mb-3">Period: {{ .Period }}</p>
|
||||
|
||||
{{ template "sectionHeader" .LineItemsHeader }}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else if eq (len .LineItems) 0 }}
|
||||
{{ template "emptyState" .NoLineItems }}
|
||||
{{ else }}
|
||||
|
||||
@@ -8,11 +8,7 @@
|
||||
page-anatomy parts (docs/design-system.md §6): the header, section
|
||||
headers, badges, and empty states come from ui_*.html; their values
|
||||
from OperatorDomainsData's methods. -->
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
|
||||
{{ template "pageHeader" .Header }}
|
||||
|
||||
|
||||
@@ -11,17 +11,11 @@
|
||||
render through statusBadge; empty sections through emptyState. This
|
||||
is a Go-template comment (stripped at render), not an HTML comment,
|
||||
so its own wording never leaks into the rendered page. */}}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}
|
||||
{{ template "notice" .Error }}
|
||||
{{ else }}
|
||||
{{ template "pageHeader" .Header }}
|
||||
{{ if .ActionError }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .ActionError }}
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .ActionError }}
|
||||
|
||||
<div class="card mb-3">
|
||||
<div class="card-body">
|
||||
@@ -94,9 +88,7 @@
|
||||
<small class="text-muted">· {{ .BillingSummary.SubscriptionNote }}</small>
|
||||
{{ end }}
|
||||
</div>
|
||||
{{- if .BillingSummary.DisplacementError }}
|
||||
<div class="small text-danger" role="alert">{{ .BillingSummary.DisplacementError }}</div>
|
||||
{{- end }}
|
||||
{{- template "notice" .BillingSummary.DisplacementError }}
|
||||
{{ else }}
|
||||
<div class="text-muted small">No subscriptions</div>
|
||||
{{ end }}
|
||||
@@ -129,11 +121,7 @@
|
||||
with none is broken, not merely empty (ux-honest-surfaces: "a pool-less
|
||||
organization is presented as broken, not empty"). The Issue Grant
|
||||
section below renders the same reason instead of a submittable form. -->
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Missing default resource pool.</strong> This organization has no
|
||||
resource pool. Every organization should have exactly one; without it,
|
||||
grant delivery is impossible until the pool is repaired.
|
||||
</div>
|
||||
{{ template "notice" .PoolMissingNotice }}
|
||||
{{ else if eq (len .Pools) 0 }}
|
||||
{{ template "emptyState" .NoPools }}
|
||||
{{ else }}
|
||||
@@ -145,9 +133,7 @@
|
||||
<h3 class="h6 mb-1">
|
||||
{{ .PoolName }} {{ if .ShowsTypeBadge }}{{ template "statusBadge" .TypeBadge }} {{ end }}{{ template "statusBadge" .StateBadge }}
|
||||
</h3>
|
||||
{{ if ne .Status "active" }}
|
||||
<p class="text-danger small mb-1">This pool is not active; it is not delivering entitlements.</p>
|
||||
{{ end }}
|
||||
{{ template "notice" .InactiveLine }}
|
||||
{{ if not .HasAttachment }}
|
||||
<p class="text-muted mb-0">No plan is delivering into this pool</p>
|
||||
{{ end }}
|
||||
@@ -203,19 +189,13 @@
|
||||
"Grants" because the table holds only grants, the operator's and the
|
||||
system's default; a plan a member buys shows under Billing and Pools
|
||||
(grant-resumption D9). */}}
|
||||
{{ if .GrantsError }}
|
||||
<div class="alert alert-danger" role="alert">{{ .GrantsError }}</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .GrantsError }}
|
||||
{{ if .PoolMissing }}
|
||||
<!-- ux-honest-surfaces: issuance is blocked with the reason; the Pools
|
||||
section above carries the full alarm. -->
|
||||
<div class="alert alert-danger mb-3" role="alert">
|
||||
<strong>Issue grant unavailable.</strong> This organization is missing
|
||||
its default resource pool, so grant delivery is impossible until the
|
||||
pool is repaired. See the Resource Pools section above.
|
||||
</div>
|
||||
{{ else if .ProductsError }}
|
||||
<div class="alert alert-danger" role="alert">{{ .ProductsError }}</div>
|
||||
{{ template "notice" .IssueGrantUnavailable }}
|
||||
{{ else if not .ProductsError.Empty }}
|
||||
{{ template "notice" .ProductsError }}
|
||||
{{ end }}
|
||||
{{ template "sectionHeader" .GrantsHeader }}
|
||||
{{/* The Issue grant control sits inside the card because its disclosure
|
||||
@@ -231,7 +211,7 @@
|
||||
<div class="card-header d-flex justify-content-between align-items-center gap-2">
|
||||
{{ template "listTabs" .GrantsNav }}
|
||||
<div class="flex-shrink-0">
|
||||
{{ if or .PoolMissing .ProductsError (eq (len .IssuanceProducts) 0) }}
|
||||
{{ if or .PoolMissing (not .ProductsError.Empty) (eq (len .IssuanceProducts) 0) }}
|
||||
{{ template "disabledControl" .IssueGrantControl }}
|
||||
{{ else }}
|
||||
{{/* A panel opener is tertiary, with the plus glyph that
|
||||
@@ -243,7 +223,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
{{ if and (not .PoolMissing) (not .ProductsError) (gt (len .IssuanceProducts) 0) }}
|
||||
{{ if and (not .PoolMissing) .ProductsError.Empty (gt (len .IssuanceProducts) 0) }}
|
||||
{{/* Collapsed by default; forced open when this form's submission
|
||||
just failed so field errors are never hidden. Issue grant is a
|
||||
stacked form (grant-resumption D21): the form part's own box is
|
||||
@@ -281,9 +261,7 @@
|
||||
{{ template "sectionHeader" .MembersHeader }}
|
||||
<div class="card mb-3">
|
||||
<div class="card-body">
|
||||
{{ if .MembersError }}
|
||||
<div class="alert alert-danger" role="alert">{{ .MembersError }}</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .MembersError }}
|
||||
{{ if eq (len .Members) 0 }}
|
||||
{{ template "emptyState" .NoMembers }}
|
||||
{{ else }}
|
||||
@@ -328,9 +306,7 @@
|
||||
<div id="entitlement-changes-panel">
|
||||
<div class="card mb-3">
|
||||
<div class="card-body">
|
||||
{{ if .EntitlementChangesError }}
|
||||
<div class="alert alert-danger" role="alert">{{ .EntitlementChangesError }}</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .EntitlementChangesError }}
|
||||
{{ if eq (len .EntitlementChanges) 0 }}
|
||||
{{ template "emptyState" .NoEntitlementChanges }}
|
||||
{{ else }}
|
||||
@@ -380,9 +356,7 @@
|
||||
<div id="tier-changes-panel">
|
||||
<div class="card mb-3">
|
||||
<div class="card-body">
|
||||
{{ if .TransitionsError }}
|
||||
<div class="alert alert-danger" role="alert">{{ .TransitionsError }}</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .TransitionsError }}
|
||||
{{ if eq (len .Transitions) 0 }}
|
||||
{{ template "emptyState" .NoTierChanges }}
|
||||
{{ else }}
|
||||
|
||||
@@ -12,9 +12,7 @@
|
||||
operator_entitlement_set_edit.html and
|
||||
operator_entitlement_set_rules.html. */}}
|
||||
{{ template "pageHeader" .Header }}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">{{ .Error }}</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
{{ template "operator_entitlement_set_edit.html" .Edit }}
|
||||
|
||||
{{ template "operator_entitlement_set_rules.html" .Rules }}
|
||||
@@ -31,8 +29,7 @@
|
||||
<div id="set-history-panel">
|
||||
<div class="card mb-3">
|
||||
<div class="card-body">
|
||||
{{ if .History.Error }}
|
||||
<div class="alert alert-danger" role="alert">{{ .History.Error }}</div>
|
||||
{{ if not .History.Error.Empty }}{{ template "notice" .History.Error }}
|
||||
{{ else if eq (len .History.Changes) 0 }}
|
||||
{{ template "emptyState" .History.NoHistory }}
|
||||
{{ else }}
|
||||
|
||||
@@ -18,9 +18,7 @@
|
||||
flag, and the query already lists active rules only
|
||||
(entitlement-set-management "The Rules table is the rule form"). */}}
|
||||
<div id="entitlement-set-rules">
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">{{ .Error }}</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
|
||||
{{ template "sectionHeader" .RulesHeader }}
|
||||
|
||||
@@ -40,15 +38,5 @@
|
||||
{{ with .DrainingLine }}
|
||||
<p class="small mb-2">{{ . }}</p>
|
||||
{{ end }}
|
||||
{{ if .FailedLine }}
|
||||
<p class="small text-danger mb-3">{{ .FailedLine }}
|
||||
<button type="button" class="btn btn-sm btn-outline-primary ms-2"
|
||||
hx-post="{{ routeURL "/partials/operator/entitlement-sets/{setID}/recompute/retry" .EntitlementSet.SetID }}"
|
||||
hx-target="#operator-body"
|
||||
hx-swap="innerHTML"
|
||||
hx-sync="this:replace">
|
||||
Retry
|
||||
</button>
|
||||
</p>
|
||||
{{ end }}
|
||||
{{ template "notice" .RecomputeFailedNotice }}
|
||||
</div>
|
||||
|
||||
@@ -12,11 +12,7 @@
|
||||
(entitlement-set-management "The set's flag is called Active"). */}}
|
||||
{{ template "pageHeader" .Header }}
|
||||
{{ template "catalogPills" "entitlement-sets" }}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
|
||||
{{/* design D20 (round 4) "record creation gets its own page": the list is
|
||||
the page's one section; its header's "New entitlement set" action is
|
||||
|
||||
@@ -25,10 +25,7 @@
|
||||
delivery-state filter, and true-total pagination
|
||||
(operator_list_controls.html, driven by .Nav). */}}
|
||||
{{ template "pageHeader" .Header }}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else }}
|
||||
{{ if eq (len .Grants) 0 }}
|
||||
{{ if .Nav.Filtered }}
|
||||
|
||||
@@ -59,9 +59,7 @@
|
||||
<div class="col">{{ template "readout" .DeliveryQueue.DeadLetterReadout }}</div>
|
||||
</div>
|
||||
{{ if .DeliveryQueue.NeedsAttention }}
|
||||
<p class="small text-danger">
|
||||
Dead-lettered work has exhausted its retries and needs an operator.
|
||||
</p>
|
||||
{{ template "notice" .DeliveryQueue.AttentionLine }}
|
||||
{{ if .DeliveryQueueEntries }}
|
||||
<div class="table-responsive">
|
||||
{{/* list-scale exempt: detail page, the Stripe integration's own delivery queue */}}
|
||||
@@ -102,11 +100,7 @@
|
||||
above, same alarm rule: only dead-lettered events carry it. */}}
|
||||
{{ template "sectionHeader" .InboundEventsHeader }}
|
||||
{{ if .InboundEvents.Available }}
|
||||
{{ if .InboundEvents.NeedsAttention }}
|
||||
<p class="small text-danger">
|
||||
{{ .InboundEvents.DeadLetter }} event{{ if ne .InboundEvents.DeadLetter 1 }}s{{ end }} could not be processed after retries and need{{ if eq .InboundEvents.DeadLetter 1 }}s{{ end }} an operator.
|
||||
</p>
|
||||
{{ end }}
|
||||
{{ template "notice" .InboundEvents.AttentionLine }}
|
||||
{{/* Events from the other Stripe environment: captured and not processed
|
||||
(stripe-environment-stamp D6). Not alarm styling, because no operator
|
||||
can move them; the line renders only when some arrived. */}}
|
||||
|
||||
@@ -11,8 +11,7 @@
|
||||
values from IntegrationsData's methods. -->
|
||||
{{ template "pageHeader" .Header }}
|
||||
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert"><strong>Error:</strong> {{ .Error }}</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else if eq (len .Integrations) 0 }}
|
||||
{{ template "emptyState" .Empty }}
|
||||
{{ else }}
|
||||
|
||||
@@ -9,10 +9,7 @@
|
||||
"Default" account name retired, maintainer 2026-08-30), states render
|
||||
through statusBadge (Overdue is the derived danger state), the
|
||||
Currency column is gone because the amounts carry their ISO code. */}}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else }}
|
||||
{{ template "environmentNotice" .EnvNotice }}
|
||||
{{ if eq (len .Invoices) 0 }}
|
||||
|
||||
@@ -7,14 +7,7 @@
|
||||
unique matches return an HX-Redirect header instead and HTMX
|
||||
full-page navigates.
|
||||
*/}}
|
||||
{{ if .LookupNoMatch }}
|
||||
<div class="alert alert-warning mt-2 mb-0 py-2" role="alert">
|
||||
{{/* Generated from the resolver registry (lookupNoMatchClasses,
|
||||
operator.go) so this sentence can never name a class the registry
|
||||
doesn't resolve, or omit one it does (design D4). */}}
|
||||
No {{ .LookupNoMatchClasses }} matches <code>{{ .LookupTerm }}</code>.
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .LookupNoMatchNotice }}
|
||||
{{ if gt (len .LookupCandidates) 0 }}
|
||||
<div class="card mt-2">
|
||||
<div class="card-body">
|
||||
|
||||
@@ -30,11 +30,10 @@
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger py-2 small" role="alert">{{ .Error }}</div>
|
||||
{{ end }}
|
||||
|
||||
{{ if eq (len .PlanLadders) 0 }}
|
||||
{{/* With no ladders the form does not render, so the card
|
||||
carries the refusal itself; otherwise the form's slot does. */}}
|
||||
{{ template "notice" .Error }}
|
||||
<p class="text-muted small mb-0">No plan ladders exist yet. A plan ladder with a rank-0 tier must exist before this type can have a default plan. <a href="/operator/plan-ladders">Go to Plan ladders</a>.</p>
|
||||
{{ else }}
|
||||
{{/* The select and, once a preview exists, the disposition
|
||||
|
||||
@@ -11,12 +11,7 @@
|
||||
Default plan tooltip and contextual hints, not in page prose
|
||||
(maintainer, 2026-08-30). */}}
|
||||
{{ template "pageHeader" .Header }}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger alert-dismissible fade show" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
{{ if eq (len .OrgTypes) 0 }}
|
||||
{{ template "emptyState" .Empty }}
|
||||
{{ else }}
|
||||
|
||||
@@ -22,10 +22,7 @@
|
||||
controls (nothing to search or clear).
|
||||
*/}}
|
||||
{{ template "pageHeader" .Header }}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else if eq (len .Organizations) 0 }}
|
||||
{{ if .Nav.Filtered }}
|
||||
{{ template "listControls" .Nav }}
|
||||
|
||||
@@ -10,10 +10,7 @@
|
||||
the always-"Default" billing account name and the truncated ID
|
||||
column are retired (maintainer, 2026-08-30); a payment has no
|
||||
detail page today, so no cell links its own. */}}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else }}
|
||||
{{ template "environmentNotice" .EnvNotice }}
|
||||
{{ if eq (len .Payments) 0 }}
|
||||
|
||||
@@ -10,10 +10,7 @@
|
||||
parts (docs/design-system.md §6): the header carries the location
|
||||
trail above the person's name, outside the details card.
|
||||
*/}}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else }}
|
||||
{{ template "pageHeader" .Header }}
|
||||
|
||||
|
||||
@@ -20,10 +20,7 @@
|
||||
exist, no controls (nothing to search or clear).
|
||||
*/}}
|
||||
{{ template "pageHeader" .Header }}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else if eq (len .Persons) 0 }}
|
||||
{{ if .Nav.Filtered }}
|
||||
{{ template "listControls" .Nav }}
|
||||
|
||||
@@ -7,32 +7,20 @@
|
||||
it did not move"; design.md "The places"). Data: PlanActLinesView. One
|
||||
block for each act, so one Reference and one Retry belong to one act:
|
||||
the organizations the act has not reached, with no tone; the ones it did
|
||||
not move, in the danger tone with Retry beside them, each linked to its
|
||||
not move, as a problem line with Retry beside it, each linked to its
|
||||
page with the sentence for the step that failed, at most fifty, then the
|
||||
act's reference. They are lines, as the entitlement set's failed-recompute
|
||||
act's reference. They are notice lines, as the entitlement set's failed-recompute
|
||||
line is, not the page-anatomy readout part. When the lines could not be
|
||||
read, that sentence stands in their place. The org type card and the
|
||||
ladder page both include it; .Target and .Swap say what a Retry swaps. */}}
|
||||
{{ if .Error }}
|
||||
<p class="small text-danger mt-3 mb-0" role="alert">{{ .Error }}</p>
|
||||
{{ end }}
|
||||
{{ $target := .Target }}
|
||||
{{ $swap := or .Swap "outerHTML" }}
|
||||
{{ template "notice" .Error }}
|
||||
{{ range .Acts }}
|
||||
<div class="mt-3" id="plan-act-{{ .ActID }}">
|
||||
{{ if .NotYetReached }}
|
||||
<p class="small mb-1">{{ .NotYetReached }}</p>
|
||||
{{ end }}
|
||||
{{ if .NotMoved }}
|
||||
<p class="small text-danger mb-1">{{ .NotMoved }}
|
||||
<button type="button" class="btn btn-sm btn-outline-primary ms-2"
|
||||
hx-post="{{ .RetryURL }}"
|
||||
hx-target="{{ $target }}"
|
||||
hx-swap="{{ $swap }}"
|
||||
hx-sync="this:replace">
|
||||
Retry
|
||||
</button>
|
||||
</p>
|
||||
{{ template "notice" ($.NotMovedLine .) }}
|
||||
<ul class="small list-unstyled mb-1">
|
||||
{{ range .Unmoved }}<li><strong><a href="/operator/organizations/{{ .OrgID }}">{{ .OrgName }}</a></strong>: {{ .Reason }}</li>{{ end }}
|
||||
{{ if .More }}<li>{{ .More }}</li>{{ end }}
|
||||
|
||||
@@ -16,9 +16,7 @@
|
||||
check it ran is impossible under the database's exclusion
|
||||
constraint. */}}
|
||||
{{ template "pageHeader" .Header }}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">{{ .Error }}</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
{{ template "operator_plan_ladder_edit.html" .Edit }}
|
||||
|
||||
{{ template "operator_plan_ladder_tiers.html" .Tiers }}
|
||||
|
||||
@@ -18,8 +18,9 @@
|
||||
whose set has no active rule to rank 0. It does not disable the commit. */}}
|
||||
<p class="small mb-2">{{ . }}</p>
|
||||
{{ end }}
|
||||
{{ if .OrgTypesError }}
|
||||
<p class="small text-danger mb-2" role="alert">{{ .OrgTypesError }}</p>
|
||||
{{ if not .OrgTypesError.Empty }}
|
||||
{{/* The failed read renders in the form's own slot, outside this message's
|
||||
status region (reorderPreviewForm), so it is announced once. */}}
|
||||
{{ else if not .RankZeroChanged }}
|
||||
<p class="small text-muted mb-2">Display order only; rank 0 is unchanged.</p>
|
||||
{{ else if not .TypePreviews }}
|
||||
|
||||
@@ -16,9 +16,7 @@
|
||||
Below the table, the lines of the reorders that still owe work
|
||||
(plan-acts "The place where an act was made lists the organizations it
|
||||
did not move"). */}}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">{{ .Error }}</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
|
||||
{{ template "sectionHeader" .TiersHeader }}
|
||||
<div class="collapse{{ if .TierForm.HasErrors }} show{{ end }} mb-3" id="tierAddPanel">
|
||||
@@ -77,7 +75,7 @@
|
||||
<span class="sortable-handle text-muted me-2" role="button" tabindex="-1" title="Drag to reorder" aria-label="Drag to reorder {{ .ProductName }}">⣿</span>
|
||||
{{ end }}
|
||||
<a href="{{ routeURL "/operator/products/{productID}" .ProductID }}">{{ .ProductName }}</a>
|
||||
{{ if eq .Rank 0 }}{{ if $.DefaultTypesError }} <span class="small text-danger">{{ $.DefaultTypesError }}</span>{{ else }}{{ range $.DefaultBadges }} {{ template "statusBadge" . }}{{ end }}{{ end }}{{ end }}
|
||||
{{ if eq .Rank 0 }}{{ if not $.DefaultTypesError.Empty }}{{ template "notice" $.DefaultTypesError }}{{ else }}{{ range $.DefaultBadges }} {{ template "statusBadge" . }}{{ end }}{{ end }}{{ end }}
|
||||
</th>
|
||||
<td>{{ if $pending }}{{ template "statusBadge" .PendingRankBadge }}{{ else }}{{ template "statusBadge" .RankBadge }}{{ end }}</td>
|
||||
<td>{{ if .HasActiveAttachments }}{{ .ActiveAttachmentCount }}{{ else }}<span class="text-muted">0</span>{{ end }}</td>
|
||||
|
||||
@@ -13,11 +13,7 @@
|
||||
own page"). */}}
|
||||
{{ template "pageHeader" .Header }}
|
||||
{{ template "catalogPills" "plan-ladders" }}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
|
||||
{{ template "sectionHeader" .TopologyHeader }}
|
||||
{{ template "operator_plan_topology.html" .Topology }}
|
||||
|
||||
@@ -15,8 +15,7 @@
|
||||
<p class="text-muted small mb-2">The whole plan catalog at a glance. Ladders are columns in member-facing order; ranks are rows. Drag a ladder column by its handle (⣿) to reorder.</p>
|
||||
<p class="text-muted small mb-2">Open a ladder to reorder its tiers.</p>
|
||||
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">{{ .Error }}</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else }}
|
||||
|
||||
{{/* The cross-ladder grid. */}}
|
||||
|
||||
@@ -12,9 +12,7 @@
|
||||
titled by sectionHeader outside their boxes, supplied by
|
||||
operator_product_edit.html and operator_product_prices.html. */}}
|
||||
{{ template "pageHeader" .Header }}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">{{ .Error }}</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
{{ template "operator_product_edit.html" .Edit }}
|
||||
|
||||
{{ template "operator_product_prices.html" .Prices }}
|
||||
|
||||
@@ -14,11 +14,7 @@
|
||||
Deactivate control confirms through the shared modal (page-anatomy
|
||||
"Destructive actions confirm through the shared modal on every
|
||||
surface"). */}}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
|
||||
{{/* design D20 sub-record panels: Add price opens from the Prices section
|
||||
header's own tertiary action, closed by default. */}}
|
||||
@@ -27,7 +23,7 @@
|
||||
{{ template "form" .PriceForm }}
|
||||
</div>
|
||||
|
||||
{{ if not .Error }}
|
||||
{{ if .Error.Empty }}
|
||||
{{ if eq (len .Prices) 0 }}
|
||||
{{ template "emptyState" .Empty }}
|
||||
{{ else }}
|
||||
|
||||
@@ -27,11 +27,7 @@
|
||||
an unlisted product, "Inactive", "Incomplete; missing: ..."), and
|
||||
never a literal (such as "Purchasable.") derived from the
|
||||
Purchasable boolean in its place. */}}
|
||||
{{ if .Readiness.Purchasable }}
|
||||
<div class="alert alert-success py-2 mb-3"><strong>{{ .Readiness.Verdict }}</strong></div>
|
||||
{{ else }}
|
||||
<div class="alert alert-warning py-2 mb-3"><strong>{{ .Readiness.Verdict }}</strong></div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Readiness.VerdictNotice }}
|
||||
|
||||
<ul class="list-group list-group-flush">
|
||||
{{ range .Readiness.Rows }}
|
||||
@@ -89,9 +85,7 @@
|
||||
</button>
|
||||
</div>
|
||||
{{ else if not .Readiness.StripeConfigured }}
|
||||
<div class="alert alert-secondary py-2 small mt-3 mb-0" role="alert">
|
||||
Stripe is not configured for this deployment, so payment processing is unavailable. Set the Stripe API key and webhook secret to enable purchases; grant-based access still works without Stripe.
|
||||
</div>
|
||||
{{ template "notice" .Readiness.StripeNotice }}
|
||||
{{ end }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -32,11 +32,7 @@
|
||||
established in-section navigation vocabulary). Entitlement sets and
|
||||
Plan ladders adopt the same row in their own sweep groups. */}}
|
||||
{{ template "catalogPills" "products" }}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
|
||||
{{ template "sectionHeader" .CatalogOverviewHeader }}
|
||||
<div class="card mb-3">
|
||||
|
||||
@@ -10,8 +10,8 @@
|
||||
deployment's model says so in its own Description rather than through
|
||||
a class. The operator overview no longer embeds this list — it shows a
|
||||
dismissible one-line banner instead (design D12's "The overview
|
||||
carries a dismissible setup banner"; operator.html's setup-banner
|
||||
region). -->
|
||||
carries a dismissible setup banner"; operator.html's setup
|
||||
notice). -->
|
||||
{{ template "pageHeader" .Header }}
|
||||
<p class="text-muted small mb-3">This checklist is always here; it does not gate or reorder any other operator surface, and it is safe to leave any step undone.</p>
|
||||
|
||||
|
||||
@@ -13,10 +13,7 @@
|
||||
(DisplacementError); the always-"Default" billing account name and the
|
||||
truncated ID column are retired (maintainer, 2026-08-30); a
|
||||
subscription has no detail page today, so no cell links its own. */}}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else }}
|
||||
{{ template "environmentNotice" .EnvNotice }}
|
||||
{{ if eq (len .Subscriptions) 0 }}
|
||||
@@ -28,7 +25,7 @@
|
||||
{{ end }}
|
||||
{{ else }}
|
||||
{{ template "listControls" .Nav }}
|
||||
{{ if .DisplacementError }}<div class="small text-danger mb-2" role="alert">{{ .DisplacementError }}</div>{{ end }}
|
||||
{{ template "notice" .DisplacementError }}
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover table-sm table-record">
|
||||
<thead>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
{{- /* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial */ -}}
|
||||
{{- /* SPDX-FileCopyrightText: 2025-2026 Christian Galo */ -}}
|
||||
|
||||
{{/* The toasts, one shared partial on every surface (page-anatomy: "Toasts
|
||||
are one shared partial on every surface"). Pipeline: server.Shell.
|
||||
Included by every layout as a sibling of <main> so the toasts survive
|
||||
hx-boost navigations and partial swaps (docs/design-system.md §3).
|
||||
|
||||
A page that lands after a create pre-renders its confirmation into
|
||||
#successToast through Shell.Flash and marks it to auto-show on load;
|
||||
success-toast.js's init reads the marker (CSP-safe, no inline script),
|
||||
shows the toast, then removes the marker so it never re-fires on a later
|
||||
swap. */}}
|
||||
<div class="toast-container">
|
||||
<div id="errorToast" class="toast align-items-center text-bg-danger border-0" role="alert" aria-live="assertive"
|
||||
aria-atomic="true">
|
||||
<div class="d-flex">
|
||||
<div class="toast-body" id="errorToastBody">
|
||||
An error occurred. Try again.
|
||||
</div>
|
||||
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"
|
||||
aria-label="Close"></button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="successToast" class="toast align-items-center text-bg-success border-0" role="status"
|
||||
aria-live="polite" aria-atomic="true"{{ if .Flash }} data-show-on-load="true"{{ end }}>
|
||||
<div class="d-flex">
|
||||
<div class="toast-body" id="successToastBody">
|
||||
{{ if .Flash }}{{ .Flash }}{{ else }}Done.{{ end }}
|
||||
</div>
|
||||
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"
|
||||
aria-label="Close"></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -5,17 +5,14 @@
|
||||
page-anatomy "One empty-state idiom"; branches and copy per
|
||||
empty-state-guidance). Pipeline: server.EmptyStateParams, computed in
|
||||
Go so the branch is never guessed in a template. The only template
|
||||
that renders an empty collection: a warning alert naming the missing
|
||||
prerequisite when Blocked, otherwise centered muted text with an
|
||||
that renders an empty collection: a Warning notice naming the missing
|
||||
prerequisite, with the prerequisite as its link, when Blocked, otherwise centered muted text with an
|
||||
optional note and an optional outline action. No borders, no boxes, no
|
||||
bare "No X found." Parsed into every set by the surface constructors of internal/web; the
|
||||
searched-to-nothing state is the list scaffold's listNoMatch. */}}
|
||||
{{ define "emptyState" }}
|
||||
{{ if .Blocked }}
|
||||
<div class="alert alert-warning" role="alert">
|
||||
<p class="mb-2">{{ .BlockerCopy }}</p>
|
||||
<a href="{{ .PrerequisiteURL }}" class="btn btn-outline-secondary btn-sm">{{ .PrerequisiteLabel }}</a>
|
||||
</div>
|
||||
{{ template "notice" .BlockedNotice }}
|
||||
{{ else }}
|
||||
<div class="text-center py-4">
|
||||
<p class="text-muted mb-2">{{ .Headline }}</p>
|
||||
|
||||
@@ -16,8 +16,10 @@
|
||||
native form, findings FA-53), the layout family, the form-level
|
||||
error slot, and the commit row. The form-level slot renders on every
|
||||
form and is empty when unused, so a refusal that belongs to no field
|
||||
always has somewhere to land (findings FA-22, FA-26, FA-27); it
|
||||
carries role="alert" so it is announced without a navigation.
|
||||
always has somewhere to land (findings FA-22, FA-26, FA-27); it holds
|
||||
the refusal as a Problem notice whose own role announces it without a
|
||||
navigation. The preview box and the tray wear the preview tone and
|
||||
carry no live role; their message carries role="status".
|
||||
|
||||
A 200 body and a 422 body of one form are the same outer element, so
|
||||
either swaps into the same target: htmx 4 swaps every response except
|
||||
@@ -64,8 +66,8 @@
|
||||
{{ define "form" }}
|
||||
{{ if eq .Box "card" }}
|
||||
<div class="card app-form-box mb-3"><div class="card-body">{{ template "formTag" . }}</div></div>
|
||||
{{ else if eq .Box "alert" }}
|
||||
<div class="alert alert-secondary app-form-box mb-3" role="status">{{ template "formTag" . }}</div>
|
||||
{{ else if eq .Box "preview" }}
|
||||
<div class="alert app-notice-preview app-form-box mb-3">{{ template "formTag" . }}</div>
|
||||
{{ else }}
|
||||
{{ template "formTag" . }}
|
||||
{{ end }}
|
||||
@@ -74,7 +76,7 @@
|
||||
{{/* formTag is the form element itself, which the box wraps. */}}
|
||||
{{ define "formTag" }}
|
||||
<form id="{{ .ID }}" data-form="{{ .Name }}" data-form-kind="{{ .Kind }}" class="app-form{{ if .Dense }} app-form-dense{{ end }}{{ if .Table }} app-form-table{{ end }}{{ if .Bar }}{{ if .Wide }} app-form-bar-wide{{ else }} app-form-bar{{ end }}{{ end }}"{{ if .NoValidate }} novalidate{{ end }}{{ if .Native }} method="{{ .Method }}" action="{{ .Action }}" role="search"{{ end }} {{ .HX }}>
|
||||
<div id="{{ .FormErrorID }}" class="app-form-error" role="alert">{{ if .FormError }}<div class="alert alert-danger mb-3">{{ .FormError }}</div>{{ end }}</div>
|
||||
<div id="{{ .FormErrorID }}" class="app-form-error">{{ template "notice" .FormErrorNotice }}</div>
|
||||
{{ if and (not .MessageAfter) (not .Rows) }}{{ template "formMessage" . }}{{ end }}
|
||||
{{ if .Bar }}
|
||||
{{/* Bar (design D20): one input group, no box. The magnifier is an
|
||||
@@ -156,8 +158,8 @@
|
||||
{{ end }}
|
||||
{{ .Body }}
|
||||
{{ if .Tray }}
|
||||
<div class="alert alert-secondary app-form-box app-form-box-wide mt-3">
|
||||
<div class="app-form-message mb-2"{{ if .TrayFocus }} tabindex="-1" autofocus{{ end }}>{{ .Message }}</div>
|
||||
<div class="alert app-notice-preview app-form-box app-form-box-wide mt-3">
|
||||
<div class="app-form-message mb-2" role="status"{{ if .TrayFocus }} tabindex="-1" autofocus{{ end }}>{{ .Message }}</div>
|
||||
{{ if .Deltas }}
|
||||
<ul class="app-form-tray-lines mb-2">
|
||||
{{ range .Deltas }}
|
||||
@@ -209,7 +211,7 @@
|
||||
FormSpec.MessageAfter moves the region below the field it names, for a
|
||||
message that is the consequence of one control (design D23). */}}
|
||||
{{ define "formMessage" }}
|
||||
{{ if .MessageID }}<p id="{{ .MessageID }}" class="app-form-message mb-2">{{ .Message }}</p>{{ else if .Message }}<div class="app-form-message mb-2">{{ .Message }}</div>{{ end }}
|
||||
{{ if .MessageID }}<p id="{{ .MessageID }}" class="app-form-message mb-2">{{ .Message }}</p>{{ else if .Message }}<div class="app-form-message mb-2"{{ if eq .Box "preview" }} role="status"{{ end }}>{{ .Message }}</div>{{ end }}
|
||||
{{ end }}
|
||||
|
||||
{{/* formRowAction is one control of a batch form (design D2 of
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
{{- /* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial */ -}}
|
||||
{{- /* SPDX-FileCopyrightText: 2025-2026 Christian Galo */ -}}
|
||||
|
||||
{{/* Page anatomy: the notice (docs/design-system.md §6; spec page-anatomy
|
||||
"Every notice renders through one part", "A notice signals its tone
|
||||
besides colour and announces by tone", "A notice is a box sized by its
|
||||
container, or a line", "What a notice may contain", "A notice is
|
||||
closable only when its owner records the closing"). Pipeline:
|
||||
notice.Notice, built in Go where the meaning is known; a template writes
|
||||
{{ template "notice" .Error }} and nothing else. The part decides the
|
||||
tone's look, glyph, hidden word and role, the markup of emphasis and of
|
||||
an action, and the close button. The zero value renders nothing. The
|
||||
only template that renders an alert besides the form part's preview box
|
||||
and tray (member-console lint, rule raw-notice). Parsed into every set
|
||||
by the surface constructors of internal/web. */}}
|
||||
{{ define "notice" }}{{ if not .Empty }}{{ .Check }}{{ if .Line }}<div class="app-notice app-notice-line app-notice-{{ .Tone.Name }}" role="{{ .Tone.Role }}">{{ template "noticeGlyph" .Tone.Name }}<span class="app-notice-words">{{ template "noticeWords" . }}</span>{{ template "noticeAction" .Action }}</div>{{ else }}<div class="alert {{ if eq .Tone.Name "problem" }}alert-danger{{ else if eq .Tone.Name "warning" }}alert-warning{{ else if eq .Tone.Name "done" }}alert-success{{ else }}alert-info{{ end }} app-notice app-notice-{{ .Tone.Name }}" role="{{ .Tone.Role }}">{{ template "noticeGlyph" .Tone.Name }}<div class="app-notice-words">{{ template "noticeWords" . }}</div>{{ template "noticeAction" .Action }}{{ with .Dismiss }}<button type="button" class="btn-close" aria-label="{{ .Label }}" hx-post="{{ .Route }}" hx-target="closest .app-notice" hx-swap="outerHTML"></button>{{ end }}</div>{{ end }}{{ end }}{{ end }}
|
||||
|
||||
{{ define "noticeWords" }}{{ if eq .Tone.Name "problem" }}<span class="visually-hidden">Error: </span>{{ else if eq .Tone.Name "warning" }}<span class="visually-hidden">Warning: </span>{{ end }}{{ range .Text }}{{ if .Strong }}<strong>{{ .Text }}</strong>{{ else if .Code }}<code>{{ .Text }}</code>{{ else }}{{ .Text }}{{ end }}{{ end }}{{ if and .Text.String .Body }} {{ end }}{{ .Body }}{{ with .Link }} <a class="alert-link" href="{{ .URL }}">{{ .Label }}</a>{{ end }}{{ end }}
|
||||
|
||||
{{ define "noticeAction" }}{{ with . }}<button type="button" class="btn btn-sm btn-outline-primary" hx-post="{{ .URL }}" hx-target="{{ .Target }}" hx-swap="{{ .Swap }}" hx-sync="this:replace">{{ .Label }}</button>{{ end }}{{ end }}
|
||||
|
||||
{{ define "noticeGlyph" }}<svg class="app-notice-glyph" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">{{ if eq . "problem" }}<polygon points="7.86 2 16.14 2 22 7.86 22 16.14 16.14 22 7.86 22 2 16.14 2 7.86 7.86 2"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>{{ else if eq . "warning" }}<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>{{ else if eq . "done" }}<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/>{{ else }}<circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/>{{ end }}</svg>{{ end }}
|
||||
@@ -13,11 +13,7 @@
|
||||
this partial is the create form's own swap target, so an in-body
|
||||
alert-success would flash and then be swapped away by the very next
|
||||
navigation. */}}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
|
||||
<div class="mb-2 text-end">
|
||||
<button class="btn btn-outline-primary btn-sm"
|
||||
|
||||
@@ -60,29 +60,7 @@
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- Toast Container -->
|
||||
<div class="toast-container">
|
||||
<div id="errorToast" class="toast align-items-center text-bg-danger border-0" role="alert" aria-live="assertive"
|
||||
aria-atomic="true">
|
||||
<div class="d-flex">
|
||||
<div class="toast-body" id="errorToastBody">
|
||||
An error occurred. Try again.
|
||||
</div>
|
||||
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"
|
||||
aria-label="Close"></button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="successToast" class="toast align-items-center text-bg-success border-0" role="status" aria-live="polite"
|
||||
aria-atomic="true">
|
||||
<div class="d-flex">
|
||||
<div class="toast-body" id="successToastBody">
|
||||
Done.
|
||||
</div>
|
||||
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"
|
||||
aria-label="Close"></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{ template "shell_toasts.html" .Shell }}
|
||||
|
||||
{{ template "shell_confirm_modal.html" . }}
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"html/template"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
)
|
||||
|
||||
// Rendering (design D5, D9, D11, D12; spec form-library "One declaration
|
||||
@@ -438,6 +440,11 @@ type FieldView struct {
|
||||
// Invalid reports whether the field was refused.
|
||||
func (f FieldView) Invalid() bool { return f.Error != "" }
|
||||
|
||||
// FormErrorNotice is the form-level refusal as a Problem notice, which the
|
||||
// form part renders in the error slot; it is empty when the form has no
|
||||
// form-level refusal.
|
||||
func (v FormView) FormErrorNotice() notice.Notice { return notice.Problem(v.FormError) }
|
||||
|
||||
// HasErrors reports whether this render carries any refusal: a field error
|
||||
// or the form-level error. A page uses it to force a collapsed sub-record
|
||||
// panel open, so a refused submission's errors are never hidden behind a
|
||||
@@ -545,8 +552,8 @@ type FormView struct {
|
||||
NoValidate bool
|
||||
// Box names the section box the part renders around the form (spec
|
||||
// form-library, "The form part owns the container"): "card" for a
|
||||
// create page or an edit form, "alert" for the preview idiom's muted
|
||||
// box (design D10), and empty for a dense sub-record row, whose panel
|
||||
// create page or an edit form, "preview" for the preview idiom's box
|
||||
// (design D10), which wears the preview tone, and empty for a dense sub-record row, whose panel
|
||||
// is already its box, for a bar, which sits in a list's header, and
|
||||
// for a settings table, which is its own shape. A stacked box is capped at the
|
||||
// readable measure and hugs its fields, so the box ends where the
|
||||
@@ -924,7 +931,7 @@ func boxFor(family Family, kind Kind, wayOut WayOutKind) string {
|
||||
}
|
||||
switch kind {
|
||||
case KindPreview:
|
||||
return "alert"
|
||||
return "preview"
|
||||
case KindConfirm:
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ package forms
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
)
|
||||
|
||||
// The three modes and the rules the render decides (design D5, D8, D9,
|
||||
@@ -1289,7 +1291,7 @@ func TestPreviewInTheDialogRendersNoBox(t *testing.T) {
|
||||
want string
|
||||
}{
|
||||
{name: "a preview leaving by the dialog", spec: preview(DismissModal("Keep")), want: ""},
|
||||
{name: "a preview leaving by Discard", spec: preview(Discard("Discard", "/partials/test")), want: "alert"},
|
||||
{name: "a preview leaving by Discard", spec: preview(Discard("Discard", "/partials/test")), want: "preview"},
|
||||
{name: "a create form leaving by the dialog", want: "card", spec: FormSpec{
|
||||
Name: "test.create", Kind: KindCreate, Family: Stacked,
|
||||
Method: "POST", Path: "/partials/test",
|
||||
@@ -1306,3 +1308,15 @@ func TestPreviewInTheDialogRendersNoBox(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFormErrorNotice pins that the form-level refusal is a Problem notice,
|
||||
// and that a form without one yields an empty notice.
|
||||
func TestFormErrorNotice(t *testing.T) {
|
||||
refused := FormView{FormError: "Refused."}
|
||||
if got, want := refused.FormErrorNotice(), notice.Problem("Refused."); got.Tone != want.Tone || got.Text.String() != want.Text.String() {
|
||||
t.Errorf("FormErrorNotice() = %#v, want %#v", got, want)
|
||||
}
|
||||
if got := (FormView{}).FormErrorNotice(); !got.Empty() {
|
||||
t.Errorf("FormErrorNotice() = %#v, want %#v", got, notice.Notice{})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,10 +5,7 @@
|
||||
Rendered by MemberForumHandler (web/member.go); the card shell around
|
||||
it is core's generic dashboard chrome (dashboard-display-genericity).
|
||||
Absence of access is a rendered state, never a hidden card. -->
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else if not .AccessGranted }}
|
||||
<p class="text-muted mb-0">Forum access isn't included in your current plan.</p>
|
||||
{{ else if .Linked }}
|
||||
|
||||
@@ -16,11 +16,7 @@
|
||||
{{ template "emptyState" .NotConfigured }}
|
||||
{{ else }}
|
||||
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .Error }}
|
||||
|
||||
{{ template "sectionHeader" .SweepHeader }}
|
||||
<div class="card mb-3">
|
||||
@@ -98,14 +94,11 @@
|
||||
|
||||
{{ if gt (len .Conflicts) 0 }}
|
||||
{{ template "sectionHeader" .ConflictsHeader }}
|
||||
<div class="alert alert-warning">
|
||||
<p class="small mb-2">These links resolved to a forum account that another person's identity also claims. They are excluded from group convergence until resolved; the console never reassigns a forum identity on its own.</p>
|
||||
<ul class="small mb-0">
|
||||
{{ range .Conflicts }}
|
||||
<li>Forum user <strong>{{ .DiscourseUsername }}</strong>: person <a href="/operator/persons/{{ .PersonID }}"><code>{{ .PersonID }}</code></a></li>
|
||||
{{ end }}
|
||||
</ul>
|
||||
</div>
|
||||
{{ template "notice" .ConflictsNotice }}
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
|
||||
{{/* The words of the conflicts warning: the paragraph and the list, set as
|
||||
the notice's body by OperatorPageData.SetConflictsNotice. */}}
|
||||
{{ define "discourseConflictsWords" }}<p class="mb-2">These links resolved to a forum account that another person's identity also claims. They are excluded from group convergence until resolved; the console never reassigns a forum identity on its own.</p><ul class="mb-0">{{ range . }}<li>Forum user <strong>{{ .DiscourseUsername }}</strong>: person <a href="/operator/persons/{{ .PersonID }}"><code>{{ .PersonID }}</code></a></li>{{ end }}</ul>{{ end }}
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/auth"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/discourse/linkage"
|
||||
dcmod "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/discourse/store"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/server"
|
||||
)
|
||||
|
||||
@@ -34,7 +35,7 @@ type MemberForumData struct {
|
||||
Linked bool
|
||||
ForumURL string
|
||||
Mode string // linkage mode; selects the not-yet-linked guidance copy
|
||||
Error string
|
||||
Error notice.Notice
|
||||
}
|
||||
|
||||
// MemberForumHandlerConfig holds configuration for MemberForumHandler.
|
||||
@@ -111,7 +112,7 @@ func (h *MemberForumHandler) RenderForPerson(w http.ResponseWriter, ctx context.
|
||||
})
|
||||
if err != nil {
|
||||
h.Logger.Error("failed to check forum access", slog.Any("error", err))
|
||||
data.Error = "Failed to check forum access"
|
||||
data.Error = notice.Problem("Failed to check forum access")
|
||||
h.Templates.Render(w, "discourse_member_forum.html", data)
|
||||
return
|
||||
}
|
||||
@@ -129,7 +130,7 @@ func (h *MemberForumHandler) RenderForPerson(w http.ResponseWriter, ctx context.
|
||||
// No link yet — the guidance state, not an error.
|
||||
default:
|
||||
h.Logger.Error("failed to look up forum user link", slog.Any("error", err))
|
||||
data.Error = "Failed to check forum account link"
|
||||
data.Error = notice.Problem("Failed to check forum account link")
|
||||
h.Templates.Render(w, "discourse_member_forum.html", data)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -20,8 +20,10 @@ import (
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/discourse/linkage"
|
||||
dcmod "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/discourse/store"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/discourse/web"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/organization"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/htmltest"
|
||||
"github.com/alexedwards/scs/v2"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
@@ -261,3 +263,27 @@ func TestMemberForumUnauthenticated(t *testing.T) {
|
||||
t.Fatalf("unauthenticated request = %d, want 401", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDiscourseMemberForumFailureIsAProblemNotice: a failed access or link
|
||||
// check renders one Problem notice with its sentence and no hidden prefix
|
||||
// shown, and an empty field renders none.
|
||||
func TestDiscourseMemberForumFailureIsAProblemNotice(t *testing.T) {
|
||||
m := newMemberHarness(t, linkage.ModeEmail)
|
||||
render := func(data web.MemberForumData) string {
|
||||
rec := httptest.NewRecorder()
|
||||
m.h.Templates.Render(rec, "discourse_member_forum.html", data)
|
||||
return rec.Body.String()
|
||||
}
|
||||
const sentence = "Failed to check forum access"
|
||||
out := render(web.MemberForumData{Error: notice.Problem(sentence)})
|
||||
notices := htmltest.Parse(t, out).All(`.app-notice[role="alert"]`)
|
||||
if len(notices) != 1 || !strings.Contains(notices[0].Text(), sentence) {
|
||||
t.Fatalf("%s: no notice renders:\n%s", "discourse_member_forum.html", out)
|
||||
}
|
||||
if !notices[0].HasClass("alert-danger") {
|
||||
t.Errorf("%s: the notice is not alert-danger, want alert-danger", "discourse_member_forum.html")
|
||||
}
|
||||
if n := htmltest.Parse(t, render(web.MemberForumData{})).Count(".app-notice"); n != 0 {
|
||||
t.Errorf("an empty field rendered a notice:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/forms"
|
||||
dcclient "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/discourse/client"
|
||||
dcmod "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/discourse/store"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/server"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/web"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/workflows"
|
||||
@@ -82,7 +83,21 @@ type OperatorPageData struct {
|
||||
// to a refused submission of it (form-library).
|
||||
Form forms.FormView
|
||||
|
||||
Error string
|
||||
Error notice.Notice
|
||||
// ConflictsNotice is the Conflicts warning, set by SetConflictsNotice
|
||||
// because its body is rendered markup; the zero value renders nothing.
|
||||
ConflictsNotice notice.Notice
|
||||
}
|
||||
|
||||
// SetConflictsNotice sets ConflictsNotice to the warning that holds the
|
||||
// conflict paragraph and the list of forum accounts, and leaves it empty when
|
||||
// no link conflicts. The handler calls it before rendering; so does every
|
||||
// test that renders the page.
|
||||
func (d *OperatorPageData) SetConflictsNotice(t *server.SafeTemplates) {
|
||||
if len(d.Conflicts) == 0 {
|
||||
return
|
||||
}
|
||||
d.ConflictsNotice = notice.Warning("").WithBody(t.Fragment("discourseConflictsWords", d.Conflicts))
|
||||
}
|
||||
|
||||
// DiscourseOperatorHandler serves the Discourse integration's operator
|
||||
@@ -175,7 +190,7 @@ func (h *DiscourseOperatorHandler) buildPageData(r *http.Request) OperatorPageDa
|
||||
mappings, err := q.ListGroupMappings(ctx)
|
||||
if err != nil {
|
||||
h.logger.Error("discourse operator: list mappings failed", slog.Any("error", err))
|
||||
data.Error = "Failed to load group mappings. Details are in the server logs."
|
||||
data.Error = notice.Problem("Failed to load group mappings. Details are in the server logs.")
|
||||
return data
|
||||
}
|
||||
seenKeys := map[string]bool{}
|
||||
@@ -220,6 +235,8 @@ func (h *DiscourseOperatorHandler) buildPageData(r *http.Request) OperatorPageDa
|
||||
})
|
||||
}
|
||||
|
||||
data.SetConflictsNotice(h.templates)
|
||||
|
||||
data.SweepStatus, data.SweepTime = h.sweepHealth(r)
|
||||
data.Form = forms.Render(mappingForm, forms.Binding{
|
||||
Mode: forms.ModeUnbound,
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package web_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
dcmod "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/discourse/store"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/discourse/web"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/server"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/htmltest"
|
||||
corweb "git.coopcloud.tech/wiki-cafe/member-console/internal/web"
|
||||
)
|
||||
|
||||
// TestDiscourseOperatorNotices renders the operator page body through the
|
||||
// operator template set: the conflicts as one Warning notice holding the
|
||||
// list and each person's link, and a failure as a Problem notice.
|
||||
func TestDiscourseOperatorNotices(t *testing.T) {
|
||||
set, err := corweb.OperatorTemplates(corweb.CoreTemplates(), corweb.OperatorOptions{},
|
||||
corweb.Mount{Key: dcmod.ModuleName, FS: os.DirFS("../templates")})
|
||||
if err != nil {
|
||||
t.Fatalf("build the operator template set: %v", err)
|
||||
}
|
||||
templates := server.NewSafeTemplates(set, slog.Default())
|
||||
render := func(d web.OperatorPageData) string {
|
||||
d.Configured = true
|
||||
d.SetConflictsNotice(templates)
|
||||
var buf bytes.Buffer
|
||||
if err := set.ExecuteTemplate(&buf, "discourse_operator.html", d); err != nil {
|
||||
t.Fatalf("render the operator page: %v", err)
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
rows := []struct {
|
||||
name string
|
||||
data web.OperatorPageData
|
||||
role string
|
||||
tone string
|
||||
want []string
|
||||
}{
|
||||
{"conflicts", web.OperatorPageData{Conflicts: []web.ConflictViewModel{
|
||||
{DiscourseUsername: "ada", PersonID: "person-1"},
|
||||
{DiscourseUsername: "grace", PersonID: "person-2"},
|
||||
}}, "status", "alert-warning", []string{"person-1", "person-2", "ada", "grace"}},
|
||||
{"failure", web.OperatorPageData{Error: notice.Problem("Failed to load group mappings. Details are in the server logs.")}, "alert", "alert-danger", []string{"Failed to load group mappings."}},
|
||||
}
|
||||
for _, row := range rows {
|
||||
out := render(row.data)
|
||||
notices := htmltest.Parse(t, out).All(`.app-notice[role="` + row.role + `"]`)
|
||||
if len(notices) != 1 {
|
||||
t.Errorf("%s: no notice renders:\n%s", row.name, out)
|
||||
continue
|
||||
}
|
||||
if !notices[0].HasClass(row.tone) {
|
||||
t.Errorf("%s: the notice is %s, want %s", row.name, toneClass(notices[0]), row.tone)
|
||||
}
|
||||
for _, want := range row.want {
|
||||
if !strings.Contains(notices[0].Text(), want) {
|
||||
t.Errorf("%s: the notice lacks %q:\n%s", row.name, want, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
links := htmltest.Parse(t, render(rows[0].data)).All(`.app-notice a[href^="/operator/persons/"]`)
|
||||
if len(links) != 2 {
|
||||
t.Errorf("conflicts: %d person links, want 2", len(links))
|
||||
}
|
||||
if n := htmltest.Parse(t, render(web.OperatorPageData{})).Count(".app-notice"); n != 0 {
|
||||
t.Errorf("an empty page renders %d notices", n)
|
||||
}
|
||||
}
|
||||
|
||||
// toneClass names the Bootstrap alert class a notice carries.
|
||||
func toneClass(n *htmltest.Node) string {
|
||||
for _, c := range []string{"alert-danger", "alert-warning", "alert-success", "alert-info"} {
|
||||
if n.HasClass(c) {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return "no tone"
|
||||
}
|
||||
@@ -9,11 +9,7 @@
|
||||
padding the shell already relies on this partial to supply. */}}
|
||||
{{ if not .AllowedDomains }}
|
||||
<div class="modal-body">
|
||||
<div class="alert alert-warning" role="alert">
|
||||
No site domains are configured for this deployment yet. An operator must
|
||||
configure at least one domain before sites can be created; contact your
|
||||
operator.
|
||||
</div>
|
||||
{{ template "notice" .NoDomainsNotice }}
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
|
||||
|
||||
@@ -12,32 +12,7 @@
|
||||
<div id="customDomainStatus"
|
||||
{{ if .Polling }}hx-get="{{ routeURL "/partials/fedwiki/custom-domains/{claimID}" .ClaimID }}" hx-trigger="every 5s" hx-swap="outerHTML"{{ end }}>
|
||||
<div class="modal-body">
|
||||
{{ if .Canceled }}
|
||||
<div class="alert alert-secondary" role="status">
|
||||
Verification for <strong>{{ .Domain }}</strong> was canceled. The domain is free
|
||||
again; start over from Create site when you're ready.
|
||||
</div>
|
||||
{{ else if .Released }}
|
||||
<div class="alert alert-secondary" role="status">
|
||||
<strong>{{ .Domain }}</strong> was released. The domain is free again; claim
|
||||
it back at any time from Create site.
|
||||
</div>
|
||||
{{ else if .Expired }}
|
||||
<div class="alert alert-warning" role="alert">
|
||||
Verification for <strong>{{ .Domain }}</strong> expired before the DNS record was
|
||||
found. The domain is free again; restart verification at any time.
|
||||
</div>
|
||||
{{ else if .Verified }}
|
||||
{{ if .Placed }}
|
||||
<div class="alert alert-success" role="status">
|
||||
<strong>{{ .Domain }}</strong> is verified and in use. Any subdomain of it is
|
||||
yours too: creating a site there needs no further DNS verification.
|
||||
</div>
|
||||
{{ else }}
|
||||
<div class="alert alert-success" role="status">
|
||||
<strong>{{ .Domain }}</strong> is verified. Create your site to start using it.
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ if not .Outcome.Empty }}{{ template "notice" .Outcome }}
|
||||
{{ else }}
|
||||
<p>To connect <strong>{{ .Domain }}</strong>, add these records at your DNS provider:</p>
|
||||
<div class="table-responsive">
|
||||
|
||||
@@ -33,10 +33,7 @@
|
||||
</div>
|
||||
|
||||
{{ template "sectionHeader" .SitesHeader }}
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else if eq (len .Sites) 0 }}
|
||||
{{ if .Nav.Filtered }}
|
||||
{{ template "listControls" .Nav }}
|
||||
|
||||
@@ -35,15 +35,7 @@
|
||||
{{ template "emptyState" .NoEntitlementEmpty }}
|
||||
{{ end }}
|
||||
{{ else }}
|
||||
{{ if .EntitlementCheckFailed }}
|
||||
<div class="alert alert-warning py-2 small" role="alert">
|
||||
We couldn't check your site allowance; your sites are shown below. Refresh in a moment to try again.
|
||||
</div>
|
||||
{{ else if not .HasEntitlement }}
|
||||
<div class="alert alert-warning py-2 small" role="alert">
|
||||
No site access is currently granted; your existing sites are shown below.
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .AllowanceNotice }}
|
||||
<!-- chrome-conventions D2 (one dominant primary action per screen): this
|
||||
card can render alongside other independent dashboard cards that also
|
||||
carry a call-to-action, so Create Site stays outline-styled rather
|
||||
@@ -64,11 +56,7 @@
|
||||
{{ end }}
|
||||
</div>
|
||||
|
||||
{{ if .HasReadonly }}
|
||||
<div class="alert alert-warning py-2 small" role="alert">
|
||||
Some of your sites are <strong>read-only</strong> because you're over your plan's active-site limit. They stay readable and your content is kept; upgrade your plan to make them editable again.
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .ReadOnlyNotice }}
|
||||
|
||||
<!-- Inline target for row-action answers. hx-preserve keeps its text across
|
||||
the list refresh a conflict answer triggers, so the sentence survives
|
||||
@@ -82,30 +70,9 @@
|
||||
now takes to finish. Verified rows only (dissolve-member-domains):
|
||||
pending claims surface via the dashboard notice and the Domains section
|
||||
below instead. -->
|
||||
{{ if .CustomDomainClaims }}
|
||||
<div class="alert alert-info py-2 small" role="status">
|
||||
<strong>Ready to use:</strong>
|
||||
{{ range .CustomDomainClaims }}
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<span><code>{{ .Domain }}</code>: verified and ready</span>
|
||||
<!-- Posts to the ordinary create route; the active claim makes it the
|
||||
instant path. The modal opens on the response. -->
|
||||
<button type="button" class="btn btn-link btn-sm p-0"
|
||||
data-bs-toggle="modal" data-bs-target="#createSiteModal"
|
||||
hx-post="/partials/fedwiki/sites"
|
||||
hx-vals='{"domain": "{{ .Domain }}", "isCustomDomain": "true", "customDomainsEnabled": "true", "instance": "{{ .Instance }}", "generation": "{{ .Generation }}"}'
|
||||
hx-target="#createSiteModalBody" hx-swap="innerHTML">
|
||||
Create your site
|
||||
</button>
|
||||
</div>
|
||||
{{ end }}
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ template "notice" .ReadyNotice }}
|
||||
|
||||
{{ if .Error }}
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>Error:</strong> {{ .Error }}
|
||||
</div>
|
||||
{{ if not .Error.Empty }}{{ template "notice" .Error }}
|
||||
{{ else if eq (len .Sites) 0 }}
|
||||
{{ template "emptyState" .NoSitesEmpty }}
|
||||
{{ else }}
|
||||
@@ -287,20 +254,16 @@
|
||||
<!-- Declined and failed requests the member has not dismissed, newest
|
||||
first (integration-delivery-core design D32): an outcome is something
|
||||
that happened, not a state of a site, so it is a notice above the list
|
||||
and never a row. The markup is the operator setup banner's (a flex
|
||||
alert with the close beside the text), at this card's alert density
|
||||
(py-2 small): its close posts the dismissal and swaps the notice out
|
||||
with the empty answer; a failed dismissal answers 500, which is not
|
||||
swapped, so the notice stays. The notices sit inside #fedwiki-sites,
|
||||
so the poller's swap brings in the notice of a request that finishes
|
||||
while the page is open. -->
|
||||
{{ define "fedwikiRequestNotices" }}
|
||||
{{ range . }}
|
||||
<div class="alert alert-{{ .Tone }} py-2 small d-flex align-items-center justify-content-between gap-3" role="alert">
|
||||
<span>{{ .Sentence }}</span>
|
||||
<button type="button" class="btn-close" aria-label="Dismiss"
|
||||
hx-post="{{ routeURL "/partials/fedwiki/requests/{instance}/{generation}/dismiss" .Instance .Generation }}"
|
||||
hx-target="closest .alert" hx-swap="outerHTML"></button>
|
||||
</div>
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
and never a row. The notice part renders the close button, and the
|
||||
request records the closing: the close posts the dismissal and swaps the
|
||||
notice out with the empty answer; a failed dismissal answers 500, which
|
||||
is not swapped, so the notice stays. The notices sit inside
|
||||
#fedwiki-sites, so the poller's swap brings in the notice of a request
|
||||
that finishes while the page is open. -->
|
||||
{{ define "fedwikiRequestNotices" }}{{ range . }}{{ template "notice" . }}{{ end }}{{ end }}
|
||||
|
||||
{{/* The verified domains with no site yet (the ready notice's Body): the
|
||||
lead, then a row per domain with the one-click create. Posts to the
|
||||
ordinary create route; the active claim makes it the instant path. The
|
||||
modal opens on the response. */}}
|
||||
{{ define "fedwikiReadyWords" }}<strong>Ready to use:</strong>{{ range . }}<div class="d-flex align-items-center gap-2"><span><code>{{ .Domain }}</code>: verified and ready</span><button type="button" class="btn btn-link btn-sm p-0" data-bs-toggle="modal" data-bs-target="#createSiteModal" hx-post="/partials/fedwiki/sites" hx-vals='{"domain": "{{ .Domain }}", "isCustomDomain": "true", "customDomainsEnabled": "true", "instance": "{{ .Instance }}", "generation": "{{ .Generation }}"}' hx-target="#createSiteModalBody" hx-swap="innerHTML">Create your site</button></div>{{ end }}{{ end }}
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"time"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/domains"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
wfdomains "git.coopcloud.tech/wiki-cafe/member-console/internal/workflows/domains"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/workflows/queues"
|
||||
"go.temporal.io/sdk/client"
|
||||
@@ -290,6 +291,24 @@ type CustomDomainPendingData struct {
|
||||
Released bool
|
||||
}
|
||||
|
||||
// Outcome is the notice a settled claim shows in place of its DNS records,
|
||||
// and the empty notice while the claim is pending.
|
||||
func (d CustomDomainPendingData) Outcome() notice.Notice {
|
||||
switch {
|
||||
case d.Canceled:
|
||||
return notice.Information("Verification for ", notice.Strong(d.Domain), " was canceled. The domain is free again; start over from Create site when you're ready.")
|
||||
case d.Released:
|
||||
return notice.Information(notice.Strong(d.Domain), " was released. The domain is free again; claim it back at any time from Create site.")
|
||||
case d.Expired:
|
||||
return notice.Warning("Verification for ", notice.Strong(d.Domain), " expired before the DNS record was found. The domain is free again; restart verification at any time.")
|
||||
case d.Verified && d.Placed:
|
||||
return notice.Done(notice.Strong(d.Domain), " is verified and in use. Any subdomain of it is yours too: creating a site there needs no further DNS verification.")
|
||||
case d.Verified:
|
||||
return notice.Done(notice.Strong(d.Domain), " is verified. Create your site to start using it.")
|
||||
}
|
||||
return notice.Notice{}
|
||||
}
|
||||
|
||||
// splitObserved undoes RecordProbeActivity's newline join.
|
||||
func splitObserved(joined string) []string {
|
||||
if joined == "" {
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package web
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/htmltest"
|
||||
)
|
||||
|
||||
// TestCustomDomainOutcomes: each outcome of a custom domain claim renders as
|
||||
// one notice with the domain in a strong run, and a pending claim renders its
|
||||
// DNS records and no notice.
|
||||
func TestCustomDomainOutcomes(t *testing.T) {
|
||||
const domain = "example.org"
|
||||
h := newRenderHandler(t)
|
||||
for _, row := range []struct {
|
||||
name string
|
||||
set func(d *CustomDomainPendingData)
|
||||
want string
|
||||
words string
|
||||
}{
|
||||
{"canceled", func(d *CustomDomainPendingData) { d.Canceled = true }, "alert-info", "was canceled"},
|
||||
{"released", func(d *CustomDomainPendingData) { d.Released = true }, "alert-info", "was released"},
|
||||
{"expired", func(d *CustomDomainPendingData) { d.Expired = true }, "alert-warning", "expired before the DNS record was found"},
|
||||
{"verified", func(d *CustomDomainPendingData) { d.Verified = true }, "alert-success", "is verified."},
|
||||
{"verified and placed", func(d *CustomDomainPendingData) { d.Verified, d.Placed = true, true }, "alert-success", "and in use"},
|
||||
} {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
d := CustomDomainPendingData{ClaimID: "claim-1", Domain: domain}
|
||||
row.set(&d)
|
||||
out := render(t, h, "fedwiki_custom_domain_pending.html", d)
|
||||
page := htmltest.Parse(t, out)
|
||||
notices := page.All(".app-notice")
|
||||
if len(notices) != 1 {
|
||||
t.Fatalf("%s: no notice renders:\n%s", row.name, out)
|
||||
}
|
||||
n := notices[0]
|
||||
if !n.HasClass(row.want) {
|
||||
t.Errorf("%s: the notice is %s, want %s", row.name, toneClass(n), row.want)
|
||||
}
|
||||
if !strings.Contains(n.Text(), row.words) {
|
||||
t.Errorf("%s: the words lack %q:\n%s", row.name, row.words, out)
|
||||
}
|
||||
if n.Count("strong") != 1 || n.One(t, "strong").Text() != domain {
|
||||
t.Errorf("%s: the words lack a strong run reading %s:\n%s", row.name, domain, out)
|
||||
}
|
||||
if strings.Contains(out, "alert-secondary") {
|
||||
t.Errorf("%s: the view still carries alert-secondary:\n%s", row.name, out)
|
||||
}
|
||||
})
|
||||
}
|
||||
t.Run("pending", func(t *testing.T) {
|
||||
d := CustomDomainPendingData{
|
||||
ClaimID: "claim-1", Domain: domain, Polling: true,
|
||||
Records: newCustomDomainRecords(domain, "_c.example.org", "v=1", "connect.example.test"),
|
||||
}
|
||||
out := render(t, h, "fedwiki_custom_domain_pending.html", d)
|
||||
page := htmltest.Parse(t, out)
|
||||
if page.Count("table") != 1 || page.Count(".app-notice") != 0 {
|
||||
t.Errorf("pending: the DNS records render and no notice does:\n%s", out)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -118,13 +118,15 @@ func TestVerifiedViewOffersOneClickCreate(t *testing.T) {
|
||||
// no DNS-records affordance at all.
|
||||
func TestSitesBannerRendersVerifiedOnly(t *testing.T) {
|
||||
h := newRenderHandler(t)
|
||||
body := render(t, h, "fedwiki_sites.html", SitesData{
|
||||
data := SitesData{
|
||||
HasEntitlement: true,
|
||||
CanCreate: true,
|
||||
CustomDomainClaims: []CustomDomainClaimViewModel{
|
||||
{ClaimID: "claim-verified", Domain: "ready.example.org", CreatedAt: "Jul 2, 2026"},
|
||||
},
|
||||
})
|
||||
}
|
||||
data.SetReadyNotice(h.Templates)
|
||||
body := render(t, h, "fedwiki_sites.html", data)
|
||||
for _, want := range []string{
|
||||
"Ready to use:",
|
||||
"verified and ready",
|
||||
@@ -142,7 +144,9 @@ func TestSitesBannerRendersVerifiedOnly(t *testing.T) {
|
||||
}
|
||||
|
||||
// No verified-empty claims → no banner chrome at all.
|
||||
empty := render(t, h, "fedwiki_sites.html", SitesData{HasEntitlement: true, CanCreate: true})
|
||||
none := SitesData{HasEntitlement: true, CanCreate: true}
|
||||
none.SetReadyNotice(h.Templates)
|
||||
empty := render(t, h, "fedwiki_sites.html", none)
|
||||
if strings.Contains(empty, "Ready to use:") {
|
||||
t.Error("banner must vanish when no verified-empty claims exist")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package web
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/server"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/htmltest"
|
||||
)
|
||||
|
||||
// noticeTemplates is the integration's template set as production composes
|
||||
// it, for a handler literal that answers through the notice part.
|
||||
func noticeTemplates(t *testing.T) *server.SafeTemplates {
|
||||
t.Helper()
|
||||
return partialsHandlerForNotices(t).Templates
|
||||
}
|
||||
|
||||
// partialsHandlerForNotices builds the partials handler as production does,
|
||||
// from the integration's own templates.
|
||||
func partialsHandlerForNotices(t *testing.T) *FedWikiPartialsHandler {
|
||||
t.Helper()
|
||||
h, err := NewFedWikiPartialsHandler(FedWikiPartialsConfig{
|
||||
Logger: discardLogger(),
|
||||
TemplatesFS: os.DirFS("../templates"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("construct handler: %v", err)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// oneProblemNotice returns the one [role="alert"] element of body holding
|
||||
// sentence, or reports why there is not exactly one.
|
||||
func oneProblemNotice(t *testing.T, label, body, sentence string) {
|
||||
t.Helper()
|
||||
notices := htmltest.Parse(t, body).All(`[role="alert"]`)
|
||||
if len(notices) != 1 || !strings.Contains(notices[0].Text(), sentence) {
|
||||
t.Errorf("%s answered:\n%s", label, body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSiteActionAnswersAProblemNotice pins that a refused row action and a
|
||||
// conflicting one each answer 200 with one Problem notice, the conflict with
|
||||
// the list refresh.
|
||||
func TestSiteActionAnswersAProblemNotice(t *testing.T) {
|
||||
h := partialsHandlerForNotices(t)
|
||||
|
||||
result := httptest.NewRecorder()
|
||||
h.siteActionResult(result, "Site not found")
|
||||
if result.Code != http.StatusOK {
|
||||
t.Errorf("siteActionResult answered %d:\n%s", result.Code, result.Body.String())
|
||||
}
|
||||
oneProblemNotice(t, "siteActionResult", result.Body.String(), "Site not found")
|
||||
|
||||
conflict := httptest.NewRecorder()
|
||||
h.siteActionConflict(conflict)
|
||||
if conflict.Code != http.StatusOK {
|
||||
t.Errorf("siteActionConflict answered %d:\n%s", conflict.Code, conflict.Body.String())
|
||||
}
|
||||
if got := conflict.Header().Get("HX-Trigger"); got != `{"refreshSites": true}` {
|
||||
t.Errorf("siteActionConflict answered:\n%s", "HX-Trigger "+got)
|
||||
}
|
||||
oneProblemNotice(t, "siteActionConflict", conflict.Body.String(), msgSiteChanged)
|
||||
|
||||
ok := httptest.NewRecorder()
|
||||
h.siteActionResult(ok, "")
|
||||
if got := ok.Header().Get("HX-Trigger"); got != `{"refreshSites": true}` || ok.Body.Len() != 0 {
|
||||
t.Errorf("siteActionResult with no message answered:\n%s", ok.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestDomainsSurfaceFailureIsAProblemNotice pins that a failing include
|
||||
// renders one Problem notice in the card.
|
||||
func TestDomainsSurfaceFailureIsAProblemNotice(t *testing.T) {
|
||||
h := partialsHandlerForNotices(t)
|
||||
h.Include = server.Include(func(*http.Request, string) (template.HTML, error) {
|
||||
return "", errors.New("boom")
|
||||
})
|
||||
out := string(h.domainsSurface(httptest.NewRequest(http.MethodGet, "/", nil)))
|
||||
notices := htmltest.Parse(t, out).All(`[role="alert"]`)
|
||||
if len(notices) != 1 || !strings.Contains(notices[0].Text(), "Could not load domains.") {
|
||||
t.Errorf("the domains surface's failure rendered:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOperatorSitesFailureIsAProblemNotice pins that the operator sites
|
||||
// page renders its failed read as one Problem notice, and renders none when
|
||||
// the field is empty.
|
||||
func TestOperatorSitesFailureIsAProblemNotice(t *testing.T) {
|
||||
h, err := NewFedWikiOperatorHandler(FedWikiOperatorHandlerConfig{
|
||||
Logger: discardLogger(),
|
||||
TemplatesFS: os.DirFS("../templates"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("construct handler: %v", err)
|
||||
}
|
||||
render := func(n notice.Notice) string {
|
||||
rec := httptest.NewRecorder()
|
||||
h.Templates.Render(rec, "operator.html", server.OperatorPageData{
|
||||
IAPosition: "integration:fedwiki-sites",
|
||||
ActiveCapability: "fedwiki-sites",
|
||||
BodyTemplate: "fedwiki_operator_sites.html",
|
||||
BodyData: FedWikiSitesData{Configured: true, Error: n},
|
||||
})
|
||||
return rec.Body.String()
|
||||
}
|
||||
|
||||
const name = "fedwiki_operator_sites.html"
|
||||
out := render(notice.Problem("Could not load the rows."))
|
||||
problems := htmltest.Parse(t, out).All(`.app-notice[role="alert"]`)
|
||||
if len(problems) != 1 || !strings.Contains(problems[0].Text(), "Could not load the rows.") {
|
||||
t.Fatalf("%s: %d problem notices, want 1:\n%s", name, len(problems), out)
|
||||
}
|
||||
visible := problems[0].Text()
|
||||
for _, hidden := range problems[0].All(".visually-hidden") {
|
||||
visible = strings.Replace(visible, hidden.Text(), "", 1)
|
||||
}
|
||||
if strings.Contains(visible, "Error:") {
|
||||
t.Errorf("%s: the visible text shows \"Error:\"", name)
|
||||
}
|
||||
empty := render(notice.Notice{})
|
||||
if n := htmltest.Parse(t, empty).Count(".app-notice-problem"); n != 0 {
|
||||
t.Errorf("%s: an empty field rendered a notice:\n%s", name, empty)
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/auth"
|
||||
fwmod "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/store"
|
||||
fwworkflows "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/workflows"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/server"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/web"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/workflows"
|
||||
@@ -50,7 +51,7 @@ type FedWikiSitesData struct {
|
||||
// page leads with the integration's description").
|
||||
Description string
|
||||
Sites []FedWikiSiteViewModel
|
||||
Error string
|
||||
Error notice.Notice
|
||||
// Site maintenance (latest schedule-spawned maintenance execution, from Temporal)
|
||||
// — same panel the Discourse operator page leads with; the shared
|
||||
// anatomy is documented in docs/building-an-integration.md.
|
||||
@@ -193,7 +194,7 @@ func (h *FedWikiOperatorHandler) GetSitesPage(w http.ResponseWriter, r *http.Req
|
||||
})
|
||||
if err != nil {
|
||||
h.Logger.Error("failed to list sites", slog.Any("error", err))
|
||||
bodyData.Error = "Failed to retrieve sites"
|
||||
bodyData.Error = notice.Problem("Failed to retrieve sites")
|
||||
} else {
|
||||
// Same config knob the member-facing FedWikiPartialsHandler.buildSiteURL
|
||||
// uses (default https) — audit finding #37: this page used to hardcode
|
||||
|
||||
@@ -126,10 +126,11 @@ func TestPartialsDeleteSiteOracle(t *testing.T) {
|
||||
// (integration-delivery-core design D31), so it needs the database and
|
||||
// a posted address; no request exists at it, so the site decides.
|
||||
h := &FedWikiPartialsHandler{
|
||||
SiteQ: oracleFixtureSiteQ(),
|
||||
Logger: discardLogger(),
|
||||
Database: newClaimTestDB(t),
|
||||
Temporal: publishedHolder(&mocks.Client{}),
|
||||
SiteQ: oracleFixtureSiteQ(),
|
||||
Logger: discardLogger(),
|
||||
Templates: noticeTemplates(t),
|
||||
Database: newClaimTestDB(t),
|
||||
Temporal: publishedHolder(&mocks.Client{}),
|
||||
}
|
||||
cfg, sctx := oracleSession(t, oracleCallerWorkspace)
|
||||
h.AuthConfig = cfg
|
||||
@@ -164,10 +165,11 @@ func TestPartialsStatusChangeOracle(t *testing.T) {
|
||||
// (integration-delivery-core design D31), so it needs the database and
|
||||
// a posted address; no request exists at it, so the site decides.
|
||||
h := &FedWikiPartialsHandler{
|
||||
SiteQ: oracleFixtureSiteQ(),
|
||||
Logger: discardLogger(),
|
||||
Database: newClaimTestDB(t),
|
||||
Temporal: publishedHolder(&mocks.Client{}),
|
||||
SiteQ: oracleFixtureSiteQ(),
|
||||
Logger: discardLogger(),
|
||||
Templates: noticeTemplates(t),
|
||||
Database: newClaimTestDB(t),
|
||||
Temporal: publishedHolder(&mocks.Client{}),
|
||||
}
|
||||
cfg, sctx := oracleSession(t, oracleCallerWorkspace)
|
||||
h.AuthConfig = cfg
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
fwmod "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/store"
|
||||
siteusage "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/usage"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/workflows"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/server"
|
||||
coreweb "git.coopcloud.tech/wiki-cafe/member-console/internal/web"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/workflows/clientholder"
|
||||
@@ -156,18 +157,6 @@ type SiteViewModel struct {
|
||||
Requested bool
|
||||
}
|
||||
|
||||
// RequestNotice is a declined or failed request the member has not
|
||||
// dismissed. It renders as a notice above the list, never on a row: an
|
||||
// outcome is something that happened, not a state of a site (design D32).
|
||||
// Instance and Generation address the request its close control
|
||||
// acknowledges.
|
||||
type RequestNotice struct {
|
||||
Sentence string // "<domain> wasn't <action>." and the reason
|
||||
Tone string // warning for declined, danger for failed
|
||||
Instance string
|
||||
Generation int64
|
||||
}
|
||||
|
||||
// SitesData holds data for the sites list partial.
|
||||
type SitesData struct {
|
||||
Sites []SiteViewModel // active + read-only (the live list)
|
||||
@@ -218,9 +207,44 @@ type SitesData struct {
|
||||
// stops on the first render with nothing open (design D32).
|
||||
Polling bool
|
||||
// Notices are the workspace's undismissed declined and failed
|
||||
// requests, newest first, shown above the list (design D32).
|
||||
Notices []RequestNotice
|
||||
Error string
|
||||
// requests, newest first, shown above the list (design D32). Each is
|
||||
// closable: its close posts the route that records the dismissal.
|
||||
Notices []notice.Notice
|
||||
// ReadyNotice lists the verified domains that wait for their site; set
|
||||
// by SetReadyNotice.
|
||||
ReadyNotice notice.Notice
|
||||
Error notice.Notice
|
||||
}
|
||||
|
||||
// AllowanceNotice is the allowance's notice: a Problem when the lookup
|
||||
// failed, a Warning when no access is granted, and nothing otherwise.
|
||||
func (d SitesData) AllowanceNotice() notice.Notice {
|
||||
switch {
|
||||
case d.EntitlementCheckFailed:
|
||||
return notice.Problem("We couldn't check your site allowance; your sites are shown below. Refresh in a moment to try again.")
|
||||
case !d.HasEntitlement:
|
||||
return notice.Warning("No site access is currently granted; your existing sites are shown below.")
|
||||
}
|
||||
return notice.Notice{}
|
||||
}
|
||||
|
||||
// ReadOnlyNotice is the Warning that says why some sites are read-only, and
|
||||
// nothing while none is.
|
||||
func (d SitesData) ReadOnlyNotice() notice.Notice {
|
||||
if !d.HasReadonly {
|
||||
return notice.Notice{}
|
||||
}
|
||||
return notice.Warning("Some of your sites are ", notice.Strong("read-only"), " because you're over your plan's active-site limit. They stay readable and your content is kept; upgrade your plan to make them editable again.")
|
||||
}
|
||||
|
||||
// SetReadyNotice sets ReadyNotice from CustomDomainClaims: an Information
|
||||
// notice listing each verified domain with its one-click create, or nothing
|
||||
// when no claim waits.
|
||||
func (d *SitesData) SetReadyNotice(t *server.SafeTemplates) {
|
||||
d.ReadyNotice = notice.Notice{}
|
||||
if len(d.CustomDomainClaims) > 0 {
|
||||
d.ReadyNotice = notice.Information("").WithBody(t.Fragment("fedwikiReadyWords", d.CustomDomainClaims))
|
||||
}
|
||||
}
|
||||
|
||||
// CustomDomainClaimViewModel is one verified external domain claim without a
|
||||
@@ -390,9 +414,11 @@ func (h *FedWikiPartialsHandler) GetSites(w http.ResponseWriter, r *http.Request
|
||||
CustomDomainClaims: h.bannerRows(r.Context(), workspaceID, requests),
|
||||
DomainsSurface: h.domainsSurface(r),
|
||||
Polling: requests.anyOpen(),
|
||||
Notices: requests.notices(siteStatus),
|
||||
Notices: requests.notices(siteStatus, h.Logger),
|
||||
}
|
||||
|
||||
data.SetReadyNotice(h.Templates)
|
||||
|
||||
h.Templates.Render(w, "fedwiki_sites.html", data)
|
||||
}
|
||||
|
||||
@@ -423,7 +449,7 @@ func (h *FedWikiPartialsHandler) anyPublishedProductConfersResourceKey(ctx conte
|
||||
}
|
||||
|
||||
// domainsSurface composes core's member domains surface into the card on
|
||||
// the server; a failure renders an inline notice, never a blank region.
|
||||
// the server; a failure renders a Problem notice, never a blank region.
|
||||
func (h *FedWikiPartialsHandler) domainsSurface(r *http.Request) template.HTML {
|
||||
if h.Include == nil {
|
||||
return ""
|
||||
@@ -431,7 +457,7 @@ func (h *FedWikiPartialsHandler) domainsSurface(r *http.Request) template.HTML {
|
||||
out, err := h.Include(r, "/partials/domains/claims")
|
||||
if err != nil {
|
||||
h.Logger.Error("domains surface failed to compose", slog.Any("error", err))
|
||||
return template.HTML(`<div class="alert alert-danger" role="alert">Could not load domains.</div>`)
|
||||
return h.Templates.Fragment("notice", notice.Problem("Could not load domains."))
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -504,6 +530,15 @@ type CreateFormData struct {
|
||||
Form forms.FormView
|
||||
}
|
||||
|
||||
// NoDomainsNotice is the Warning the form shows in place of its fields when
|
||||
// the deployment has no site domain configured.
|
||||
func (d CreateFormData) NoDomainsNotice() notice.Notice {
|
||||
if len(d.AllowedDomains) > 0 {
|
||||
return notice.Notice{}
|
||||
}
|
||||
return notice.Warning("No site domains are configured for this deployment yet. An operator must configure at least one domain before sites can be created; contact your operator.")
|
||||
}
|
||||
|
||||
// resolveCreateFormAffordances computes the create form's runtime state,
|
||||
// which both an unbound render (GetCreateForm) and a refused resubmission
|
||||
// (renderCreateFormRefusal) need alike: whether the "use a domain I own"
|
||||
@@ -643,7 +678,7 @@ func (h *FedWikiPartialsHandler) buildSiteURL(domain string) string {
|
||||
}
|
||||
|
||||
func (h *FedWikiPartialsHandler) renderError(w http.ResponseWriter, tmplName string, message string) {
|
||||
data := SitesData{Error: message}
|
||||
data := SitesData{Error: notice.Problem(message)}
|
||||
h.Templates.Render(w, tmplName, data)
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
siteusage "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/usage"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/workflows"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/authtest"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/htmltest"
|
||||
)
|
||||
|
||||
// sessionFor returns a request context carrying an authenticated session for
|
||||
@@ -230,7 +231,7 @@ func TestQuotaSurfacesOnAFailedRead(t *testing.T) {
|
||||
|
||||
t.Run("the card says the allowance could not be checked and lists the sites", func(t *testing.T) {
|
||||
body := e.sitesList()
|
||||
if !strings.Contains(body, "We couldn't check your site allowance; your sites are shown below. Refresh in a moment to try again.") {
|
||||
if !strings.Contains(htmltest.Parse(t, body).Text(), "We couldn't check your site allowance; your sites are shown below. Refresh in a moment to try again.") {
|
||||
t.Errorf("card has no notice for the failed read: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, "one"+e.uniq) {
|
||||
|
||||
@@ -232,11 +232,11 @@ func checkMissingNotice(t *testing.T, row noticeIdentityCase, replacement bool)
|
||||
env.site("park", "active")
|
||||
}
|
||||
}
|
||||
want := fmt.Sprintf(row.want, domain, parkDomain)
|
||||
want := "Warning: " + fmt.Sprintf(row.want, domain, parkDomain)
|
||||
list := env.sitesList()
|
||||
var got []string
|
||||
for _, notice := range htmltest.Parse(t, list).All(".alert:has(button[aria-label=Dismiss])") {
|
||||
got = append(got, notice.One(t, "span").Text())
|
||||
for _, notice := range htmltest.Parse(t, list).All(".app-notice:has(button[aria-label=Dismiss])") {
|
||||
got = append(got, notice.One(t, ".app-notice-words").Text())
|
||||
}
|
||||
if len(got) > 1 {
|
||||
t.Errorf("%s: missing swap showed more than one notice: %v", row.name, got)
|
||||
|
||||
@@ -16,7 +16,6 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
@@ -800,7 +799,7 @@ func (s *listStates) declinedCreate() {
|
||||
dismissButton := notice.One(t, "button[aria-label=Dismiss]")
|
||||
for attr, want := range map[string]string{
|
||||
"hx-post": "/partials/fedwiki/requests/" + s.instance + "/" + strconv.FormatInt(s.gen, 10) + "/dismiss",
|
||||
"hx-target": "closest .alert",
|
||||
"hx-target": "closest .app-notice",
|
||||
"hx-swap": "outerHTML",
|
||||
} {
|
||||
if got, _ := dismissButton.Attr(attr); got != want {
|
||||
@@ -897,12 +896,12 @@ func tableRow(t *testing.T, list *htmltest.Node, domain string) *htmltest.Node {
|
||||
return rows[0]
|
||||
}
|
||||
|
||||
// dismissibleNotice returns the one alert that names domain and carries a
|
||||
// dismissibleNotice returns the one notice that names domain and carries a
|
||||
// control to dismiss it.
|
||||
func dismissibleNotice(t *testing.T, list *htmltest.Node, domain string) *htmltest.Node {
|
||||
t.Helper()
|
||||
var found []*htmltest.Node
|
||||
for _, alert := range list.All(".alert[role=alert]") {
|
||||
for _, alert := range list.All(".app-notice:has(button[aria-label=Dismiss])") {
|
||||
if alert.Count("button[aria-label=Dismiss]") > 0 && strings.Contains(alert.Text(), domain+" wasn") {
|
||||
found = append(found, alert)
|
||||
}
|
||||
@@ -966,33 +965,27 @@ func controlAddresses(t *testing.T, row *htmltest.Node) []controlAddress {
|
||||
// noticeFor returns the dismissible notice that names domain.
|
||||
func noticeFor(t *testing.T, list, domain string) string {
|
||||
t.Helper()
|
||||
for _, part := range strings.Split(list, `<div class="alert `)[1:] {
|
||||
end := strings.Index(part, "</div>")
|
||||
if end < 0 {
|
||||
continue
|
||||
}
|
||||
if n := part[:end]; strings.Contains(n, `aria-label="Dismiss"`) && strings.Contains(n, domain+" wasn") {
|
||||
return `<div class="alert ` + n
|
||||
for _, n := range htmltest.Parse(t, list).All(".app-notice:has(button[aria-label=Dismiss])") {
|
||||
if strings.Contains(n.Text(), domain+" wasn") {
|
||||
return n.HTML()
|
||||
}
|
||||
}
|
||||
t.Fatalf("no notice for %s:\n%s", domain, list)
|
||||
return ""
|
||||
}
|
||||
|
||||
// notices returns the sentences of the list's notices, in render order.
|
||||
func notices(list string) []string {
|
||||
// notices returns the sentences of the list's dismissible notices, in render
|
||||
// order, without the part's hidden "Warning: " and "Error: " words.
|
||||
func notices(t *testing.T, list string) []string {
|
||||
t.Helper()
|
||||
var out []string
|
||||
for _, part := range strings.Split(list, `<div class="alert `)[1:] {
|
||||
end := strings.Index(part, "</div>")
|
||||
if end < 0 || !strings.Contains(part[:end], `aria-label="Dismiss"`) {
|
||||
continue
|
||||
for _, n := range htmltest.Parse(t, list).All(".app-notice:has(button[aria-label=Dismiss])") {
|
||||
words := n.One(t, ".app-notice-words")
|
||||
text := words.Text()
|
||||
for _, hidden := range words.All(".visually-hidden") {
|
||||
text = strings.Replace(text, hidden.Text(), "", 1)
|
||||
}
|
||||
open := strings.Index(part, "<span>")
|
||||
close := strings.Index(part, "</span>")
|
||||
if open < 0 || close < open {
|
||||
continue
|
||||
}
|
||||
out = append(out, html.UnescapeString(strings.TrimSpace(part[open+len("<span>"):close])))
|
||||
out = append(out, strings.TrimSpace(text))
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -1182,7 +1175,7 @@ func TestNoticesPerAction(t *testing.T) {
|
||||
restoreDomain + " wasn't restored. You have reached your active site limit.",
|
||||
archiveDomain + " wasn't archived. Try again later.",
|
||||
}
|
||||
if got := notices(list); fmt.Sprint(got) != fmt.Sprint(want) {
|
||||
if got := notices(t, list); fmt.Sprint(got) != fmt.Sprint(want) {
|
||||
t.Errorf("notices =\n%q\nwant\n%q", got, want)
|
||||
}
|
||||
for _, d := range []string{archiveDomain, restoreDomain, keepDomain, deleteDomain} {
|
||||
@@ -1207,7 +1200,7 @@ func TestSwapNoticeOnce(t *testing.T) {
|
||||
e.finish(in.ParkInstanceID, in.ParkGeneration, integration.LifecycleFailed, workflows.ReasonRetriesExhausted)
|
||||
|
||||
list := e.sitesList()
|
||||
if got, want := notices(list), []string{chosenDomain + " wasn't kept active. Try again later."}; fmt.Sprint(got) != fmt.Sprint(want) {
|
||||
if got, want := notices(t, list), []string{chosenDomain + " wasn't kept active. Try again later."}; fmt.Sprint(got) != fmt.Sprint(want) {
|
||||
t.Errorf("notices = %q, want %q", got, want)
|
||||
}
|
||||
if strings.Contains(list, incumbentDomain+" wasn") {
|
||||
@@ -1223,7 +1216,7 @@ func TestSwapNoticeOnce(t *testing.T) {
|
||||
t.Errorf("swap row %s/%d not acknowledged: %+v", a.Instance, a.Generation, req)
|
||||
}
|
||||
}
|
||||
if n := notices(e.sitesList()); len(n) != 0 {
|
||||
if n := notices(t, e.sitesList()); len(n) != 0 {
|
||||
t.Errorf("notices after dismissal = %q", n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"html/template"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sort"
|
||||
@@ -22,6 +21,8 @@ import (
|
||||
fwmod "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/store"
|
||||
siteusage "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/usage"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/workflows"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
coreweb "git.coopcloud.tech/wiki-cafe/member-console/internal/web"
|
||||
)
|
||||
|
||||
// The member's site actions (integration-delivery-core design D25 to D27,
|
||||
@@ -764,12 +765,11 @@ func (h *FedWikiPartialsHandler) acknowledgeRequest(ctx context.Context, workspa
|
||||
}
|
||||
|
||||
// siteActionResult writes the outcome of a row action: on success an
|
||||
// HX-Trigger refreshes the list; on failure an inline alert is returned to
|
||||
// HX-Trigger refreshes the list; on failure a Problem notice is returned to
|
||||
// the action's target.
|
||||
func (h *FedWikiPartialsHandler) siteActionResult(w http.ResponseWriter, errMsg string) {
|
||||
if errMsg != "" {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`<div class="alert alert-danger py-2 small mb-2" role="alert">` + template.HTMLEscapeString(errMsg) + `</div>`)) // the status line is already sent; a failed write has no other answer
|
||||
h.Templates.Render(w, "notice", notice.Problem(errMsg))
|
||||
return
|
||||
}
|
||||
w.Header().Set("HX-Trigger", `{"refreshSites": true}`)
|
||||
@@ -778,12 +778,11 @@ func (h *FedWikiPartialsHandler) siteActionResult(w http.ResponseWriter, errMsg
|
||||
|
||||
// siteActionConflict answers a row action whose address another request
|
||||
// holds, or whose site changed since the list rendered: the sentence, and a
|
||||
// list refresh so the rows carry current addresses (design D31). The alert
|
||||
// list refresh so the rows carry current addresses (design D31). The notice
|
||||
// target keeps its text across the refresh (hx-preserve).
|
||||
func (h *FedWikiPartialsHandler) siteActionConflict(w http.ResponseWriter) {
|
||||
w.Header().Set("HX-Trigger", `{"refreshSites": true}`)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`<div class="alert alert-danger py-2 small mb-2" role="alert">` + template.HTMLEscapeString(msgSiteChanged) + `</div>`)) // the status line is already sent; a failed write has no other answer
|
||||
h.Templates.Render(w, "notice", notice.Problem(msgSiteChanged))
|
||||
}
|
||||
|
||||
// withWorkspaceTx runs fn inside a transaction that holds a per-workspace
|
||||
@@ -875,7 +874,7 @@ func (v requestsView) createRows(siteIDs []string) []SiteViewModel {
|
||||
// one per request the member made. A swap's parked site is left out: the
|
||||
// swap is the member's Keep active on the other site, whose notice tells
|
||||
// it. siteStatus is each site's current status, by id.
|
||||
func (v requestsView) notices(siteStatus map[string]string) []RequestNotice {
|
||||
func (v requestsView) notices(siteStatus map[string]string, logger *slog.Logger) []notice.Notice {
|
||||
rows := make([]integration.LifecycleRequest, 0, len(v.outcomes))
|
||||
for _, row := range v.outcomes {
|
||||
if _, open := v.open[row.InstanceID]; open {
|
||||
@@ -887,13 +886,9 @@ func (v requestsView) notices(siteStatus map[string]string) []RequestNotice {
|
||||
rows = append(rows, row)
|
||||
}
|
||||
sort.SliceStable(rows, func(i, j int) bool { return finishedAt(rows[i]).After(finishedAt(rows[j])) })
|
||||
out := make([]RequestNotice, 0, len(rows))
|
||||
out := make([]notice.Notice, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
p := decodeParams(row.Parameters)
|
||||
tone := "warning"
|
||||
if row.Status == integration.LifecycleFailed {
|
||||
tone = "danger"
|
||||
}
|
||||
sentence := noticeSentence(p.Domain, requestAction(row.Operation, p, siteStatus[row.InstanceID]), row.ReasonCode.String)
|
||||
if row.ReasonCode.String == workflows.ReasonSiteMissing {
|
||||
sentence = p.Domain + " was deleted."
|
||||
@@ -906,12 +901,17 @@ func (v requestsView) notices(siteStatus map[string]string) []RequestNotice {
|
||||
}
|
||||
}
|
||||
}
|
||||
out = append(out, RequestNotice{
|
||||
Sentence: sentence,
|
||||
Tone: tone,
|
||||
Instance: row.InstanceID,
|
||||
Generation: row.Generation,
|
||||
})
|
||||
n := notice.Warning(sentence)
|
||||
if row.Status == integration.LifecycleFailed {
|
||||
n = notice.Problem(sentence)
|
||||
}
|
||||
route, err := coreweb.RouteURL("/partials/fedwiki/requests/{instance}/{generation}/dismiss", row.InstanceID, row.Generation)
|
||||
if err != nil {
|
||||
logger.Error("failed to build the dismiss route of a request notice",
|
||||
slog.String("instance", row.InstanceID), slog.Int64("generation", row.Generation), slog.Any("error", err))
|
||||
continue
|
||||
}
|
||||
out = append(out, n.Dismissible(route, "Dismiss"))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package web
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integration"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/workflows"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/htmltest"
|
||||
)
|
||||
|
||||
// siteNoticeRow is one notice of the sites card: its tone's class, its words
|
||||
// and the runs and controls it carries.
|
||||
type siteNoticeRow struct {
|
||||
name string
|
||||
data func(t *testing.T, h *FedWikiPartialsHandler) SitesData
|
||||
want string
|
||||
role string
|
||||
words []string
|
||||
strong string
|
||||
rows int
|
||||
close string
|
||||
}
|
||||
|
||||
func sitesWith(set func(d *SitesData)) func(t *testing.T, h *FedWikiPartialsHandler) SitesData {
|
||||
return func(t *testing.T, h *FedWikiPartialsHandler) SitesData {
|
||||
d := SitesData{HasEntitlement: true, CanCreate: true, Quota: 5}
|
||||
set(&d)
|
||||
d.SetReadyNotice(h.Templates)
|
||||
return d
|
||||
}
|
||||
}
|
||||
|
||||
// requestRow is the declined or failed create the card's notices read.
|
||||
func requestRow(status, reason string) integration.LifecycleRequest {
|
||||
return integration.LifecycleRequest{
|
||||
InstanceID: "inst-1", Generation: 7, Operation: integration.LifecycleCreate, Status: status,
|
||||
Parameters: requestParams{Domain: "new.example.test"}.raw(),
|
||||
ReasonCode: sql.NullString{String: reason, Valid: true},
|
||||
}
|
||||
}
|
||||
|
||||
func TestSitesCardNotices(t *testing.T) {
|
||||
h := newRenderHandler(t)
|
||||
declined := requestRow(integration.LifecycleDeclined, workflows.ReasonSiteLimitReached)
|
||||
failed := requestRow(integration.LifecycleFailed, workflows.ReasonRetriesExhausted)
|
||||
rows := []siteNoticeRow{
|
||||
{name: "allowance failed", want: "alert-danger", role: "alert", words: []string{"We couldn't check your site allowance;"},
|
||||
data: sitesWith(func(d *SitesData) { d.EntitlementCheckFailed = true })},
|
||||
{name: "no access", want: "alert-warning", role: "status", words: []string{"No site access is currently granted;"},
|
||||
data: sitesWith(func(d *SitesData) {
|
||||
d.HasEntitlement = false
|
||||
d.Sites = []SiteViewModel{{ID: "site-1", Domain: "kept.example.test", Status: "active"}}
|
||||
})},
|
||||
{name: "read only", want: "alert-warning", role: "status", words: []string{"Some of your sites are read-only"}, strong: "read-only",
|
||||
data: sitesWith(func(d *SitesData) { d.HasReadonly = true })},
|
||||
{name: "ready to use", want: "alert-info", role: "status", words: []string{"Ready to use:", "one.example.org", "two.example.org"}, rows: 2,
|
||||
data: sitesWith(func(d *SitesData) {
|
||||
d.CustomDomainClaims = []CustomDomainClaimViewModel{
|
||||
{ClaimID: "c1", Domain: "one.example.org", Instance: "i1", Generation: 1},
|
||||
{ClaimID: "c2", Domain: "two.example.org", Instance: "i2", Generation: 2},
|
||||
}
|
||||
})},
|
||||
{name: "declined request", want: "alert-warning", role: "status", words: []string{"new.example.test wasn't created."},
|
||||
close: "/partials/fedwiki/requests/inst-1/7/dismiss",
|
||||
data: sitesWith(func(d *SitesData) {
|
||||
d.Notices = requestsView{outcomes: []integration.LifecycleRequest{declined}}.notices(nil, discardLogger())
|
||||
})},
|
||||
{name: "failed request", want: "alert-danger", role: "alert", words: []string{"new.example.test wasn't created."},
|
||||
close: "/partials/fedwiki/requests/inst-1/7/dismiss",
|
||||
data: sitesWith(func(d *SitesData) {
|
||||
d.Notices = requestsView{outcomes: []integration.LifecycleRequest{failed}}.notices(nil, discardLogger())
|
||||
})},
|
||||
}
|
||||
for _, row := range rows {
|
||||
t.Run(row.name, func(t *testing.T) { checkSiteNotice(t, h, row) })
|
||||
}
|
||||
}
|
||||
|
||||
// checkSiteNotice renders the card for the row and checks its one notice: the
|
||||
// tone's class and role, the words and runs, the rows and the close button.
|
||||
func checkSiteNotice(t *testing.T, h *FedWikiPartialsHandler, row siteNoticeRow) {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
h.Templates.Render(rec, "fedwiki_sites.html", row.data(t, h))
|
||||
out := rec.Body.String()
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: the card answered %d:\n%s", row.name, rec.Code, out)
|
||||
}
|
||||
notices := htmltest.Parse(t, out).All(".app-notice")
|
||||
if len(notices) != 1 {
|
||||
t.Fatalf("%s: no notice renders:\n%s", row.name, out)
|
||||
}
|
||||
n := notices[0]
|
||||
if !n.HasClass(row.want) {
|
||||
t.Errorf("%s: the notice is %s, want %s", row.name, toneClass(n), row.want)
|
||||
}
|
||||
if role, _ := n.Attr("role"); role != row.role {
|
||||
t.Errorf("%s: role = %q, want %q", row.name, role, row.role)
|
||||
}
|
||||
for _, w := range row.words {
|
||||
if !strings.Contains(n.Text(), w) {
|
||||
t.Errorf("%s: the words lack %q:\n%s", row.name, w, out)
|
||||
}
|
||||
}
|
||||
if row.strong != "" && (n.Count("strong") != 1 || n.One(t, "strong").Text() != row.strong) {
|
||||
t.Errorf("%s: the words lack a strong run reading %s:\n%s", row.name, row.strong, out)
|
||||
}
|
||||
if got := n.Count(".app-notice-words > div"); row.rows != 0 && got != row.rows {
|
||||
t.Errorf("%s: %d rows, want %d:\n%s", row.name, got, row.rows, out)
|
||||
}
|
||||
closes := n.Count(`button[aria-label="Dismiss"][hx-post="` + row.close + `"][hx-target="closest .app-notice"]`)
|
||||
switch {
|
||||
case row.close != "" && closes != 1:
|
||||
t.Errorf("%s: no close button posts %s:\n%s", row.name, row.close, out)
|
||||
case row.close == "" && n.Count(".btn-close") != 0:
|
||||
t.Errorf("%s: a close button renders:\n%s", row.name, out)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateFormWithoutDomains: a deployment with no site domain shows the
|
||||
// Warning notice in place of the form.
|
||||
func TestCreateFormWithoutDomains(t *testing.T) {
|
||||
h := newRenderHandler(t)
|
||||
out := render(t, h, "fedwiki_create_form.html", CreateFormData{})
|
||||
n := htmltest.Parse(t, out).All(".app-notice")
|
||||
if len(n) != 1 || !n[0].HasClass("alert-warning") {
|
||||
t.Fatalf("no domains: no notice renders:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(n[0].Text(), "No site domains are configured for this deployment yet.") {
|
||||
t.Errorf("no domains: the words lack the sentence:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// toneClass names the Bootstrap alert class a notice carries.
|
||||
func toneClass(n *htmltest.Node) string {
|
||||
for _, c := range []string{"alert-danger", "alert-warning", "alert-success", "alert-info"} {
|
||||
if n.HasClass(c) {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return "no tone"
|
||||
}
|
||||
@@ -41,6 +41,8 @@ const (
|
||||
partForm = "ui_form.html"
|
||||
partFormField = "ui_form_field.html"
|
||||
partDisabledControl = "ui_disabled_control.html"
|
||||
partNotice = "ui_notice.html"
|
||||
shellToasts = "shell_toasts.html"
|
||||
listScaffold = "operator_list_controls.html"
|
||||
// confirmModal is the shell's dialog title, chrome like the parts: the
|
||||
// one <h2> outside ui_section_header.html the anatomy allows.
|
||||
@@ -716,6 +718,91 @@ func ruleHTMX4Scripts(staticDir string) []Violation {
|
||||
return v
|
||||
}
|
||||
|
||||
// ruleScriptCopy extends filler-copy to the string literals of the first-party
|
||||
// scripts the htmx 4 rule reads, because the toasts' messages live there. It
|
||||
// walks each script once: a comment is skipped, and a quoted literal is read
|
||||
// to its closing quote, a backslash escaping the next character. A regular
|
||||
// expression literal is read as code; no first-party script holds a quote
|
||||
// inside one.
|
||||
func ruleScriptCopy(staticDir string) []Violation {
|
||||
entries, err := os.ReadDir(staticDir)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return []Violation{unreadableFile(staticDir, err)}
|
||||
}
|
||||
var v []Violation
|
||||
for _, e := range entries {
|
||||
name := e.Name()
|
||||
if e.IsDir() || !strings.HasSuffix(name, ".js") ||
|
||||
strings.HasSuffix(name, ".min.js") || name == "bootstrap.bundle.js" {
|
||||
continue
|
||||
}
|
||||
path := filepath.Join(staticDir, name)
|
||||
src, err := os.ReadFile(path)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
v = append(v, unreadableFile(path, err))
|
||||
continue
|
||||
}
|
||||
v = append(v, scriptLiteralCopy(path, string(src))...)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// scriptLiteralCopy reports filler-copy for each string literal of src that
|
||||
// holds a filler phrase, at the line the literal starts on.
|
||||
func scriptLiteralCopy(path, src string) []Violation {
|
||||
var v []Violation
|
||||
line := 1
|
||||
for i := 0; i < len(src); {
|
||||
c := src[i]
|
||||
if c == '\n' {
|
||||
line++
|
||||
i++
|
||||
} else if strings.HasPrefix(src[i:], "//") {
|
||||
for i < len(src) && src[i] != '\n' {
|
||||
i++
|
||||
}
|
||||
} else if strings.HasPrefix(src[i:], "/*") {
|
||||
end := len(src)
|
||||
if k := strings.Index(src[i+2:], "*/"); k >= 0 {
|
||||
end = i + 2 + k + 2
|
||||
}
|
||||
line += strings.Count(src[i:end], "\n")
|
||||
i = end
|
||||
} else if c == '\'' || c == '"' || c == '`' {
|
||||
end := literalEnd(src, i)
|
||||
if phrase := fillerCopy(src[i+1 : max(i+1, end-1)]); phrase != "" {
|
||||
v = append(v, Violation{File: path, Line: line, Rule: "filler-copy", Message: fillerCopyMsg("UI", phrase)})
|
||||
}
|
||||
line += strings.Count(src[i:end], "\n")
|
||||
i = end
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// literalEnd returns the index just past the string literal that opens at
|
||||
// src[start], a backslash escaping the next character.
|
||||
func literalEnd(src string, start int) int {
|
||||
quote := src[start]
|
||||
for i := start + 1; i < len(src); i++ {
|
||||
switch src[i] {
|
||||
case '\\':
|
||||
i++
|
||||
case quote:
|
||||
return i + 1
|
||||
}
|
||||
}
|
||||
return len(src)
|
||||
}
|
||||
|
||||
// --- screen coverage --------------------------------------------------------
|
||||
|
||||
// ruleScreenCoverage fails when a registered GET page route is missing from
|
||||
|
||||
@@ -298,6 +298,33 @@ document.body.addEventListener("htmx:response:error", function () {});
|
||||
}
|
||||
}
|
||||
|
||||
// TestFillerCopyReadsScripts pins filler-copy over the string literals of
|
||||
// the first-party scripts: a literal reports at its line, and a comment or a
|
||||
// vendored bundle reports nothing.
|
||||
func TestFillerCopyReadsScripts(t *testing.T) {
|
||||
t.Run("literal", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "app.js"), "var a = 1;\nshowErrorToast('Please wait.');\n")
|
||||
vs := ruleScriptCopy(dir)
|
||||
if len(vs) != 1 || vs[0].Rule != "filler-copy" || vs[0].Line != 2 {
|
||||
t.Errorf("the script's filler was not reported: %v", vs)
|
||||
}
|
||||
})
|
||||
for _, r := range []struct{ name, file, src string }{
|
||||
{"line comment", "app.js", "// showErrorToast('Please wait.')\n"},
|
||||
{"block comment", "app.js", "/* showErrorToast('Please wait.') */\n"},
|
||||
{"vendored bundle", "x.min.js", "showErrorToast('Please wait.')\n"},
|
||||
} {
|
||||
t.Run(r.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, r.file), r.src)
|
||||
if vs := ruleScriptCopy(dir); len(vs) != 0 {
|
||||
t.Errorf("%s: filler-copy fired: %v", r.name, vs)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnatomyAllowlist pins the allowlist's behaviour: listed files are
|
||||
// counted, not failed; a stale entry (clean or missing) fails.
|
||||
func TestAnatomyAllowlist(t *testing.T) {
|
||||
|
||||
@@ -138,6 +138,7 @@ func Run(cfg Config) (*Result, error) {
|
||||
res.Violations = append(res.Violations, anatomy...)
|
||||
res.Allowlisted = allowlisted
|
||||
res.Violations = append(res.Violations, ruleGoCopy(goCopyDirs(cfg))...)
|
||||
res.Violations = append(res.Violations, ruleRawNotice(anatomyTemplateDirs(cfg), goCopyDirs(cfg), append(goCopyDirs(cfg), filepath.Join(filepath.Dir(cfg.ServerDir), "forms")))...)
|
||||
}
|
||||
if cfg.ManifestPath != "-" {
|
||||
res.Violations = append(res.Violations, ruleScreenCoverage(routes, cfg.ManifestPath)...)
|
||||
@@ -145,7 +146,9 @@ func Run(cfg Config) (*Result, error) {
|
||||
if cfg.SpecsDir != "-" {
|
||||
res.Violations = append(res.Violations, ruleSpecPurposePlaceholder(cfg.SpecsDir)...)
|
||||
}
|
||||
res.Violations = append(res.Violations, ruleHTMX4Scripts(filepath.Join(filepath.Dir(cfg.TemplateDir), "static"))...)
|
||||
staticDir := filepath.Join(filepath.Dir(cfg.TemplateDir), "static")
|
||||
res.Violations = append(res.Violations, ruleHTMX4Scripts(staticDir)...)
|
||||
res.Violations = append(res.Violations, ruleScriptCopy(staticDir)...)
|
||||
if cfg.LockRoot != "-" {
|
||||
res.Violations = append(res.Violations, ruleLockSites(cfg.LockRoot)...)
|
||||
res.Violations = append(res.Violations, ruleLockFamilies(cfg.LockRoot)...)
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package lint
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
// raw-notice (spec ui-quality-gate "Lint refuses a hand-written notice"; design decision 9): every notice renders through
|
||||
// templates/partials/ui_notice.html from a notice.Notice built in Go, so
|
||||
// Bootstrap's alert classes, role="alert" and Bootstrap's own
|
||||
// data-bs-dismiss="alert" are findings anywhere else, and so is a notice
|
||||
// body set from anything but a template fragment.
|
||||
|
||||
// noticeClassExempt are the templates that may write an alert class: the
|
||||
// part itself. The form part's preview box and tray are exempt by
|
||||
// formPreviewClass, which reads the tag's own class instead of the file.
|
||||
var noticeClassExempt = []string{partNotice}
|
||||
|
||||
// noticeRoleExempt are the templates that may write role="alert": the part,
|
||||
// which sets the role from the tone, and the toasts, which are their own
|
||||
// primitive and announce an error assertively.
|
||||
var noticeRoleExempt = []string{partNotice, shellToasts}
|
||||
|
||||
var (
|
||||
// templateCommentRe matches a Go template comment, blanked before the
|
||||
// tags are read so a comment that names an alert is not markup.
|
||||
templateCommentRe = regexp.MustCompile(`(?s)\{\{-?\s*/\*.*?\*/\s*-?\}\}`)
|
||||
goRoleAlertRe = regexp.MustCompile(`\brole=["']alert["']`)
|
||||
goBSDismissRe = regexp.MustCompile(`\bdata-bs-dismiss=["']alert["']`)
|
||||
// goClassListRe matches a literal that is nothing but a class list, so
|
||||
// a view field such as Class: "alert alert-warning" is read as one.
|
||||
goClassListRe = regexp.MustCompile(`^\s*[a-z0-9-]+(\s+[a-z0-9-]+)*\s*$`)
|
||||
)
|
||||
|
||||
const (
|
||||
noticeClassMsg = `composes an .alert outside the notice part; build a notice.Notice in Go and render it with {{ template "notice" ... }} (page-anatomy "Every notice renders through one part", design-system.md §6)`
|
||||
noticeRoleMsg = `sets role="alert" outside the notice part; the part sets the role from the notice's tone (page-anatomy "A notice signals its tone besides colour and announces by tone")`
|
||||
noticeDismissMsg = `closes a notice with data-bs-dismiss, which records nothing; a closable notice names the route that records its closing (notice.Notice.Dismissible; page-anatomy "A notice is closable only when its owner records the closing")`
|
||||
noticeBodyMsg = `sets a notice's Body from something other than SafeTemplates.Fragment; a Body is markup from the console's own templates (page-anatomy "What a notice may contain")`
|
||||
)
|
||||
|
||||
// alertToken reports whether a class value carries the token alert or one
|
||||
// that starts alert-. A template action is replaced by a space first, so a
|
||||
// token it completes counts by its literal part (alert-{{ .Tone }} is
|
||||
// alert-) and a class that merely contains the letters does not fire.
|
||||
func alertToken(value string) bool {
|
||||
for _, tok := range strings.Fields(templateActRe.ReplaceAllString(value, " ")) {
|
||||
if tok == "alert" || strings.HasPrefix(tok, "alert-") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// formPreviewClass reports a class value the form part may write: it carries
|
||||
// app-notice-preview and no token that starts alert-.
|
||||
func formPreviewClass(value string) bool {
|
||||
preview := false
|
||||
for _, tok := range strings.Fields(templateActRe.ReplaceAllString(value, " ")) {
|
||||
if tok != "alert" && alertToken(tok) {
|
||||
return false
|
||||
}
|
||||
if tok == "app-notice-preview" {
|
||||
preview = true
|
||||
}
|
||||
}
|
||||
return preview
|
||||
}
|
||||
|
||||
// keepNewlines returns as many line breaks as s holds, so a blanked comment
|
||||
// leaves every later line where it was.
|
||||
func keepNewlines(s string) string { return strings.Repeat("\n", strings.Count(s, "\n")) }
|
||||
|
||||
// noticeTemplateViolations reports, at the line each tag starts on, an alert
|
||||
// class, a role="alert" and a data-bs-dismiss="alert" in one template.
|
||||
func noticeTemplateViolations(path, src string) []Violation {
|
||||
base := filepath.Base(path)
|
||||
src = templateCommentRe.ReplaceAllStringFunc(src, keepNewlines)
|
||||
// A template action becomes a space, so an attribute written straight after one is read under its own name.
|
||||
src = templateActRe.ReplaceAllStringFunc(src, func(m string) string { return " " + keepNewlines(m) })
|
||||
var out []Violation
|
||||
add := func(line int, msg string) {
|
||||
out = append(out, Violation{File: path, Line: line, Rule: "raw-notice", Message: msg})
|
||||
}
|
||||
tz := html.NewTokenizer(strings.NewReader(src))
|
||||
line := 1
|
||||
for {
|
||||
tt := tz.Next()
|
||||
raw := string(tz.Raw())
|
||||
tokenLine := line
|
||||
line += strings.Count(raw, "\n")
|
||||
switch tt {
|
||||
case html.ErrorToken:
|
||||
return out
|
||||
case html.StartTagToken, html.SelfClosingTagToken:
|
||||
_, hasAttr := tz.TagName()
|
||||
for hasAttr {
|
||||
key, val, more := tz.TagAttr()
|
||||
hasAttr = more
|
||||
value := string(val)
|
||||
switch string(key) {
|
||||
case "class":
|
||||
formPreviewBox := base == partForm && formPreviewClass(value)
|
||||
if alertToken(value) && !slices.Contains(noticeClassExempt, base) && !formPreviewBox {
|
||||
add(tokenLine, noticeClassMsg)
|
||||
}
|
||||
case "role":
|
||||
if slices.Contains(strings.Fields(value), "alert") && !slices.Contains(noticeRoleExempt, base) {
|
||||
add(tokenLine, noticeRoleMsg)
|
||||
}
|
||||
case "data-bs-dismiss":
|
||||
if strings.TrimSpace(value) == "alert" {
|
||||
add(tokenLine, noticeDismissMsg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// noticeGoViolations reports, in the Go packages dirs, an alert class,
|
||||
// role="alert" or data-bs-dismiss="alert" in a string literal, at the line
|
||||
// the literal starts on, and, in bodyDirs, a call WithBody(x) whose argument
|
||||
// is not a call to a method named Fragment. Test files are skipped.
|
||||
func noticeGoViolations(dirs, bodyDirs []string) []Violation {
|
||||
var out []Violation
|
||||
out = append(out, eachGoString(dirs, func(path string, line int, _, text string) {
|
||||
for _, m := range classAttrRe.FindAllStringSubmatch(text, -1) {
|
||||
if alertToken(m[1]) {
|
||||
out = append(out, Violation{File: path, Line: line, Rule: "raw-notice", Message: noticeClassMsg})
|
||||
}
|
||||
}
|
||||
if goClassListRe.MatchString(text) && slices.ContainsFunc(strings.Fields(text), func(tok string) bool { return strings.HasPrefix(tok, "alert-") }) {
|
||||
out = append(out, Violation{File: path, Line: line, Rule: "raw-notice", Message: noticeClassMsg})
|
||||
}
|
||||
if goRoleAlertRe.MatchString(text) {
|
||||
out = append(out, Violation{File: path, Line: line, Rule: "raw-notice", Message: noticeRoleMsg})
|
||||
}
|
||||
if goBSDismissRe.MatchString(text) {
|
||||
out = append(out, Violation{File: path, Line: line, Rule: "raw-notice", Message: noticeDismissMsg})
|
||||
}
|
||||
})...)
|
||||
for _, dir := range bodyDirs {
|
||||
files, _ := readTree(dir, goSource) // eachGoString reported an unreadable file
|
||||
for _, f := range files {
|
||||
out = append(out, noticeBodyViolations(f.path, f.src)...)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// noticeBodyViolations reports each WithBody call in one Go file whose
|
||||
// argument is not a Fragment call.
|
||||
func noticeBodyViolations(path string, src []byte) []Violation {
|
||||
fset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fset, path, src, 0)
|
||||
if err != nil {
|
||||
return nil // an unparseable file fails the build, not this rule
|
||||
}
|
||||
var out []Violation
|
||||
ast.Inspect(file, func(n ast.Node) bool {
|
||||
call, ok := n.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
if isWithBody(call) && !isFragmentCall(call.Args[len(call.Args)-1]) {
|
||||
out = append(out, Violation{File: path, Line: fset.Position(call.Pos()).Line, Rule: "raw-notice", Message: noticeBodyMsg})
|
||||
}
|
||||
return true
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// isWithBody reports a call of a method named WithBody with one argument, or
|
||||
// with two when the method is called through its type (a method expression,
|
||||
// whose first argument is the notice).
|
||||
func isWithBody(call *ast.CallExpr) bool {
|
||||
sel, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok || sel.Sel.Name != "WithBody" {
|
||||
return false
|
||||
}
|
||||
if _, expr := sel.X.(*ast.SelectorExpr); expr {
|
||||
return len(call.Args) == 1 || len(call.Args) == 2
|
||||
}
|
||||
return len(call.Args) == 1
|
||||
}
|
||||
|
||||
// isFragmentCall reports an expression that is a call of a method named
|
||||
// Fragment, the one source of a notice's body.
|
||||
func isFragmentCall(e ast.Expr) bool {
|
||||
call, ok := e.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
sel, ok := call.Fun.(*ast.SelectorExpr)
|
||||
return ok && sel.Sel.Name == "Fragment"
|
||||
}
|
||||
|
||||
// ruleRawNotice applies both passes to the template dirs and the Go dirs, and
|
||||
// the Body check to bodyDirs besides, and reports every finding.
|
||||
func ruleRawNotice(templateDirs, goDirs, bodyDirs []string) (violations []Violation) {
|
||||
for _, dir := range templateDirs {
|
||||
files, bad := readTree(dir, func(path string) bool { return strings.HasSuffix(path, ".html") })
|
||||
violations = append(violations, bad...)
|
||||
for _, f := range files {
|
||||
violations = append(violations, noticeTemplateViolations(f.path, string(f.src))...)
|
||||
}
|
||||
}
|
||||
byFile := map[string][]Violation{}
|
||||
for _, v := range noticeGoViolations(goDirs, bodyDirs) {
|
||||
byFile[v.File] = append(byFile[v.File], v)
|
||||
}
|
||||
for _, dir := range goDirs {
|
||||
files, _ := readTree(dir, goSource) // noticeGoViolations reported an unreadable file
|
||||
for _, f := range files {
|
||||
violations = append(violations, byFile[f.path]...)
|
||||
delete(byFile, f.path)
|
||||
}
|
||||
}
|
||||
for _, rest := range byFile { // findings of a file that could not be read
|
||||
violations = append(violations, rest...)
|
||||
}
|
||||
return violations
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package lint
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// noticeLines returns the lines the raw-notice findings of the violations
|
||||
// are reported at.
|
||||
func noticeLines(vs []Violation) []int {
|
||||
var out []int
|
||||
for _, v := range vs {
|
||||
if v.Rule == "raw-notice" {
|
||||
out = append(out, v.Line)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestRawNoticeFiresInTemplates(t *testing.T) {
|
||||
rows := []struct {
|
||||
name string
|
||||
file string
|
||||
src string
|
||||
line int
|
||||
}{
|
||||
{"hand-written alert", "operator_x.html", "<p>a</p>\n<div class=\"alert alert-warning py-2 small\">x</div>\n", 2},
|
||||
{"templated tone", "operator_x.html", "<div class=\"alert-{{ .Tone }} py-2\">x</div>\n", 1},
|
||||
{"alert link", "operator_x.html", "<p>a</p>\n<p>b</p>\n<a class=\"alert-link\" href=\"/x\">x</a>\n", 3},
|
||||
{"role line", "operator_x.html", "<p class=\"small text-danger\" role=\"alert\">x</p>\n", 1},
|
||||
{"bootstrap close", "operator_x.html", "<button type=\"button\" data-bs-dismiss=\"alert\">x</button>\n", 1},
|
||||
{"multi-line tag", "operator_x.html", "<p>a</p>\n<div\n id=\"a\"\n class=\"alert alert-info\">x</div>\n", 2},
|
||||
{"class after an action", "operator_x.html", "<div {{ if .Bad }}class=\"alert alert-danger\"{{ end }}>x</div>\n", 1},
|
||||
{"role after an action", "operator_x.html", "<p {{ if .Bad }}role=\"alert\"{{ end }}>x</p>\n", 1},
|
||||
{"role list", "operator_x.html", "<p role=\"alert status\">x</p>\n", 1},
|
||||
{"preview class outside the form part", "operator_x.html", "<div class=\"alert app-notice-preview\">x</div>\n", 1},
|
||||
{"form part's own alert", "ui_form.html", "<p>a</p>\n<div class=\"alert alert-danger mb-3\">x</div>\n", 2},
|
||||
}
|
||||
for _, r := range rows {
|
||||
t.Run(r.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "partials", r.file), r.src)
|
||||
vs := ruleRawNotice([]string{dir}, nil, nil)
|
||||
if got := noticeLines(vs); len(got) != 1 || got[0] != r.line {
|
||||
t.Errorf("%s: raw-notice at %v, want line %d", r.name, got, r.line)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRawNoticePasses(t *testing.T) {
|
||||
rows := []struct {
|
||||
name string
|
||||
file string
|
||||
src string
|
||||
}{
|
||||
{"the part", partNotice, "<div class=\"alert alert-danger app-notice\" role=\"alert\">x</div>\n"},
|
||||
{"the form part", partForm, "<div class=\"alert app-notice-preview app-form-box mb-3\">x</div>\n"},
|
||||
{"the toasts", shellToasts, "<div id=\"errorToast\" role=\"alert\">x</div>\n"},
|
||||
{"a colouring", "operator_x.html", "<td class=\"text-danger\">x</td>\n"},
|
||||
{"near words", "operator_x.html", "<p class=\"app-alerting\" role=\"alertdialog\">x</p>\n"},
|
||||
{"template comment", "operator_x.html", "{{/* {{ template \"notice\" . }} replaces <div class=\"alert\"> */}}\n<p>x</p>\n"},
|
||||
{"html comment", "operator_x.html", "<!-- <div class=\"alert\"> -->\n<p>x</p>\n"},
|
||||
}
|
||||
for _, r := range rows {
|
||||
t.Run(r.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "partials", r.file), r.src)
|
||||
vs := ruleRawNotice([]string{dir}, nil, nil)
|
||||
if got := noticeLines(vs); len(got) != 0 {
|
||||
t.Errorf("%s: raw-notice fired: %v", r.name, vs)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRawNoticeFiresInGoLiterals(t *testing.T) {
|
||||
rows := []struct {
|
||||
name string
|
||||
file string
|
||||
src string
|
||||
line int // 0: nothing is reported
|
||||
}{
|
||||
{"server class literal", "server/x.go", "package server\n\nvar _ = \"<div class=\\\"alert alert-danger\\\">x</div>\"\n", 3},
|
||||
{"server role literal", "server/r.go", "package server\n\nvar _ = \"<p class=\\\"small\\\" role=\\\"alert\\\">x</p>\"\n", 3},
|
||||
{"class list built in Go", "server/k.go", "package server\n\nvar Class = \"alert alert-warning\"\n", 3},
|
||||
{"body through a method expression", "server/m.go", "package server\n\nfunc f(n, s any) {\n\t_ = notice.Notice.WithBody(n, template.HTML(s))\n}\n", 4},
|
||||
{"integration literal", "integrations/x/web/y.go", "package web\n\nvar a = 1\nvar _ = \"data-bs-dismiss=\\\"alert\\\"\"\n", 4},
|
||||
{"test file", "server/x_test.go", "package server\n\nvar _ = \"<div class=\\\"alert\\\" role=\\\"alert\\\">x</div>\"\n", 0},
|
||||
{"comment", "server/z.go", "package server\n\n// <div class=\"alert\" role=\"alert\">\nvar a = 1\n", 0},
|
||||
{"body from a string", "server/b.go", "package server\n\nfunc f(n any) {\n\tn.WithBody(template.HTML(\"<b>x</b>\"))\n}\n", 4},
|
||||
{"body from a fragment", "server/c.go", "package server\n\nfunc f(n, h any) {\n\tn.WithBody(h.Templates.Fragment(\"x\", d))\n}\n", 0},
|
||||
}
|
||||
for _, r := range rows {
|
||||
t.Run(r.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, r.file), r.src)
|
||||
goDir := []string{filepath.Join(dir, filepath.Dir(r.file))}
|
||||
vs := ruleRawNotice(nil, goDir, goDir)
|
||||
got := noticeLines(vs)
|
||||
if r.line == 0 {
|
||||
if len(got) != 0 {
|
||||
t.Errorf("%s: raw-notice fired: %v", r.name, vs)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(got) == 0 {
|
||||
t.Errorf("%s: raw-notice at %v, want line %d", r.name, got, r.line)
|
||||
return
|
||||
}
|
||||
for _, l := range got {
|
||||
if l != r.line {
|
||||
t.Errorf("%s: raw-notice at %v, want line %d", r.name, got, r.line)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
// Package notice is the value the notice part renders
|
||||
// (templates/partials/ui_notice.html; page-anatomy "Every notice renders
|
||||
// through one part"). It imports no package of the console, so the forms
|
||||
// library, the server and the integrations' web packages can each build
|
||||
// one. The part decides the look, the glyph, the hidden word, the role and
|
||||
// the markup of emphasis and of an action from the value; a template never
|
||||
// writes them.
|
||||
package notice
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Tone says what happened. The zero value names no tone.
|
||||
type Tone int
|
||||
|
||||
const (
|
||||
// ProblemTone is a failure or a refusal; the part announces it.
|
||||
ProblemTone Tone = iota + 1
|
||||
// WarningTone is a standing condition that needs attention.
|
||||
WarningTone
|
||||
// DoneTone is a completed outcome.
|
||||
DoneTone
|
||||
// InformationTone is a neutral fact.
|
||||
InformationTone
|
||||
// PreviewTone is worn only by the form part's preview box and the Rows
|
||||
// tray; the notice part refuses it.
|
||||
PreviewTone
|
||||
)
|
||||
|
||||
var toneNames = map[Tone]string{ProblemTone: "problem", WarningTone: "warning", DoneTone: "done", InformationTone: "information", PreviewTone: "preview"}
|
||||
|
||||
// Name is the name the part keys a tone's look, glyph and hidden word by;
|
||||
// the empty string for no tone.
|
||||
func (t Tone) Name() string { return toneNames[t] }
|
||||
|
||||
// Role is the live role the part sets: only a Problem interrupts.
|
||||
func (t Tone) Role() string {
|
||||
if t == ProblemTone {
|
||||
return "alert"
|
||||
}
|
||||
return "status"
|
||||
}
|
||||
|
||||
// Style says how a run of words is set.
|
||||
type Style int
|
||||
|
||||
const (
|
||||
// PlainStyle sets a run as ordinary text.
|
||||
PlainStyle Style = iota
|
||||
// StrongStyle sets a run in bold.
|
||||
StrongStyle
|
||||
// CodeStyle sets a run as code.
|
||||
CodeStyle
|
||||
)
|
||||
|
||||
// Run is one stretch of a notice's words, set plain, strong or as code.
|
||||
type Run struct {
|
||||
Text string
|
||||
Style Style
|
||||
}
|
||||
|
||||
// Strong reports a run set in bold; Code reports a run set as code.
|
||||
func (r Run) Strong() bool { return r.Style == StrongStyle }
|
||||
func (r Run) Code() bool { return r.Style == CodeStyle }
|
||||
|
||||
// Strong and Code build the runs for a name in bold and a term in code.
|
||||
func Strong(s string) Run { return Run{Text: s, Style: StrongStyle} }
|
||||
func Code(s string) Run { return Run{Text: s, Style: CodeStyle} }
|
||||
|
||||
// Text is a notice's words: a closed sequence of runs. The part escapes
|
||||
// every run and renders <strong> and <code> itself, so no notice needs
|
||||
// template.HTML for emphasis.
|
||||
type Text []Run
|
||||
|
||||
// Words builds a Text from strings (plain runs, a named string type included) and Runs. Any other
|
||||
// argument becomes a run Check refuses, so a wrong argument fails the
|
||||
// render that shows it.
|
||||
func Words(parts ...any) Text {
|
||||
t := make(Text, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
switch v := p.(type) {
|
||||
case string:
|
||||
t = append(t, Run{Text: v})
|
||||
case Run:
|
||||
t = append(t, v)
|
||||
default:
|
||||
if rv := reflect.ValueOf(p); rv.IsValid() && rv.Kind() == reflect.String {
|
||||
t = append(t, Run{Text: rv.String()})
|
||||
} else {
|
||||
t = append(t, Run{Text: fmt.Sprintf("%T", p), Style: Style(-1)})
|
||||
}
|
||||
}
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// String is the words as plain text, for tests and for code that reads a
|
||||
// notice's sentence.
|
||||
func (t Text) String() string {
|
||||
var b strings.Builder
|
||||
for _, r := range t {
|
||||
b.WriteString(r.Text)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// Link is the link the part renders after the words, as alert-link.
|
||||
type Link struct{ Label, URL string }
|
||||
|
||||
// Action is one control that posts: the part renders a small outline
|
||||
// button and escapes each field. Navigation is the notice's Link.
|
||||
type Action struct{ Label, URL, Target, Swap string }
|
||||
|
||||
// Dismiss names the route that records a notice's closing, which the
|
||||
// notice's owner stores on its own record, and the close button's label.
|
||||
type Dismiss struct{ Route, Label string }
|
||||
|
||||
// Notice is one message about a page, a section or an outcome. A notice
|
||||
// with no words renders nothing.
|
||||
type Notice struct {
|
||||
Tone Tone
|
||||
// Text is the words, as runs the part escapes.
|
||||
Text Text
|
||||
Link *Link
|
||||
Action *Action
|
||||
// body is markup from the console's own templates, rendered through
|
||||
// SafeTemplates.Fragment, for a notice that carries rows (a second line counts as one), a list or
|
||||
// more than one control.
|
||||
body template.HTML
|
||||
Dismiss *Dismiss
|
||||
// Line renders the boxless shape.
|
||||
Line bool
|
||||
}
|
||||
|
||||
// Problem builds a notice that says something failed or was refused.
|
||||
func Problem(words ...any) Notice { return Notice{Tone: ProblemTone, Text: Words(words...)} }
|
||||
|
||||
// Warning builds a notice that names a standing condition.
|
||||
func Warning(words ...any) Notice { return Notice{Tone: WarningTone, Text: Words(words...)} }
|
||||
|
||||
// Done builds a notice that reports a completed outcome.
|
||||
func Done(words ...any) Notice { return Notice{Tone: DoneTone, Text: Words(words...)} }
|
||||
|
||||
// Information builds a notice that states a neutral fact.
|
||||
func Information(words ...any) Notice { return Notice{Tone: InformationTone, Text: Words(words...)} }
|
||||
|
||||
// WithLink returns the notice with the link the part renders after its words.
|
||||
func (n Notice) WithLink(label, url string) Notice { n.Link = &Link{Label: label, URL: url}; return n }
|
||||
|
||||
// WithAction returns the notice with one control that posts.
|
||||
func (n Notice) WithAction(a Action) Notice { n.Action = &a; return n }
|
||||
|
||||
// WithBody returns the notice with markup from SafeTemplates.Fragment.
|
||||
func (n Notice) WithBody(body template.HTML) Notice { n.body = body; return n }
|
||||
|
||||
// Dismissible returns the notice with a close button that posts to the route
|
||||
// recording the closing.
|
||||
func (n Notice) Dismissible(route, label string) Notice {
|
||||
n.Dismiss = &Dismiss{Route: route, Label: label}
|
||||
return n
|
||||
}
|
||||
|
||||
// AsLine returns the notice in the boxless shape.
|
||||
func (n Notice) AsLine() Notice { n.Line = true; return n }
|
||||
|
||||
// Body is the notice's markup from the console's own templates.
|
||||
func (n Notice) Body() template.HTML { return n.body }
|
||||
|
||||
// MarshalText is the notice's words as plain text, so a view that holds
|
||||
// a notice encodes it as its sentence (JSON goldens, structured logs).
|
||||
func (n Notice) MarshalText() ([]byte, error) { return []byte(n.Text.String()), nil }
|
||||
|
||||
// Empty reports a notice with no words.
|
||||
func (n Notice) Empty() bool { return n.Text.String() == "" && n.body == "" }
|
||||
|
||||
// Check is called by the part before it renders a notice with words, as
|
||||
// pageHeader calls its own; an error aborts the render.
|
||||
func (n Notice) Check() (string, error) {
|
||||
if n.Empty() {
|
||||
return "", nil
|
||||
}
|
||||
words := n.Text.String()
|
||||
if words == "" {
|
||||
words = "(body)"
|
||||
}
|
||||
switch {
|
||||
case n.Tone == 0:
|
||||
return "", fmt.Errorf("notice %q has no tone", words)
|
||||
case n.Tone == PreviewTone:
|
||||
return "", fmt.Errorf("notice %q: the preview tone renders only in the form part's preview box and tray", words)
|
||||
case n.Tone.Name() == "":
|
||||
return "", fmt.Errorf("notice %q: unknown tone %d", words, int(n.Tone))
|
||||
case n.hasBadRun():
|
||||
return "", fmt.Errorf("notice %q: a run is neither plain, strong nor code", words)
|
||||
case n.Line && n.body != "":
|
||||
return "", fmt.Errorf("notice %q: a line holds one sentence, not a body", words)
|
||||
case n.Line && n.Dismiss != nil:
|
||||
return "", fmt.Errorf("notice %q: a line is never closable", words)
|
||||
case n.Line && n.Link != nil && n.Action != nil:
|
||||
return "", fmt.Errorf("notice %q: a line carries one link or one control, not both", words)
|
||||
case n.Action != nil && (n.Action.Label == "" || n.Action.URL == "" || n.Action.Target == "" || n.Action.Swap == ""):
|
||||
return "", fmt.Errorf("notice %q: an action names its label, route, target and swap", words)
|
||||
case n.Dismiss != nil && (n.Dismiss.Route == "" || n.Dismiss.Label == ""):
|
||||
return "", fmt.Errorf("notice %q: a closable notice names the route that records its closing and its label", words)
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// hasBadRun reports a run whose style is none of plain, strong and code.
|
||||
func (n Notice) hasBadRun() bool {
|
||||
for _, r := range n.Text {
|
||||
if r.Style != PlainStyle && r.Style != StrongStyle && r.Style != CodeStyle {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package notice
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os/exec"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestConstructors(t *testing.T) {
|
||||
rows := []struct {
|
||||
name string
|
||||
got Notice
|
||||
tone Tone
|
||||
role string
|
||||
}{
|
||||
{"problem", Problem("x"), ProblemTone, "alert"},
|
||||
{"warning", Warning("x"), WarningTone, "status"},
|
||||
{"done", Done("x"), DoneTone, "status"},
|
||||
{"information", Information("x"), InformationTone, "status"},
|
||||
}
|
||||
for _, r := range rows {
|
||||
t.Run(r.name, func(t *testing.T) {
|
||||
if r.got.Tone != r.tone {
|
||||
t.Errorf("%s: tone = %v, want %v", r.name, r.got.Tone, r.tone)
|
||||
}
|
||||
if got := r.got.Tone.Name(); got != r.name {
|
||||
t.Errorf("%s: name = %q, want %q", r.name, got, r.name)
|
||||
}
|
||||
if got := r.got.Tone.Role(); got != r.role {
|
||||
t.Errorf("%s: role = %q, want %q", r.name, got, r.role)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWords(t *testing.T) {
|
||||
type sentence string
|
||||
got := Words("a ", Strong("b"), " c ", Code("d"))
|
||||
want := Text{{"a ", PlainStyle}, {"b", StrongStyle}, {" c ", PlainStyle}, {"d", CodeStyle}}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Words(...) = %#v, want %#v", got, want)
|
||||
}
|
||||
if s := got.String(); s != "a b c d" {
|
||||
t.Errorf("String() = %q, want %q", s, "a b c d")
|
||||
}
|
||||
for name, arg := range map[string]any{"int": 42, "error": errors.New("x")} {
|
||||
w := Words(arg)
|
||||
if len(w) != 1 || (Notice{Tone: ProblemTone, Text: w}).hasBadRun() == false {
|
||||
t.Errorf("Words(%s) = %#v, want one run Check refuses", name, w)
|
||||
}
|
||||
}
|
||||
if w, want := Words(sentence("x")), (Text{{"x", PlainStyle}}); !reflect.DeepEqual(w, want) {
|
||||
t.Errorf("Words(sentence) = %#v, want %#v", w, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckRefuses(t *testing.T) {
|
||||
ok := func() Notice { return Problem("x") }
|
||||
rows := []struct {
|
||||
name string
|
||||
n Notice
|
||||
want string
|
||||
}{
|
||||
{"no tone", Notice{Text: Words("x")}, "has no tone"},
|
||||
{"body with no tone", Notice{body: "<em>x</em>"}, "has no tone"},
|
||||
{"preview", Notice{Tone: PreviewTone, Text: Words("x")}, "preview tone"},
|
||||
{"unknown tone", Notice{Tone: Tone(9), Text: Words("x")}, "unknown tone 9"},
|
||||
{"line with body", ok().WithBody("<em>x</em>").AsLine(), "a line holds one sentence"},
|
||||
{"closable line", ok().Dismissible("/r", "Dismiss").AsLine(), "a line is never closable"},
|
||||
{"line with link and action", ok().WithLink("a", "/").WithAction(Action{"a", "/r", "#t", "outerHTML"}).AsLine(), "one link or one control"},
|
||||
{"close without route", ok().Dismissible("", "Dismiss"), "names the route that records its closing"},
|
||||
{"close without label", ok().Dismissible("/r", ""), "names the route that records its closing"},
|
||||
{"bad run", Notice{Tone: ProblemTone, Text: Words(42)}, "neither plain, strong nor code"},
|
||||
{"action without label", ok().WithAction(Action{"", "/r", "#t", "outerHTML"}), "an action names its label"},
|
||||
{"action without route", ok().WithAction(Action{"a", "", "#t", "outerHTML"}), "an action names its label"},
|
||||
{"action without target", ok().WithAction(Action{"a", "/r", "", "outerHTML"}), "an action names its label"},
|
||||
{"action without swap", ok().WithAction(Action{"a", "/r", "#t", ""}), "an action names its label"},
|
||||
}
|
||||
for _, r := range rows {
|
||||
t.Run(r.name, func(t *testing.T) {
|
||||
if _, err := r.n.Check(); err == nil || !strings.Contains(err.Error(), r.want) {
|
||||
t.Errorf("%s: Check() = %v, want an error containing %q", r.name, err, r.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckAccepts(t *testing.T) {
|
||||
rows := []struct {
|
||||
name string
|
||||
n Notice
|
||||
}{
|
||||
{"box with everything", Problem("x").WithLink("a", "/").WithAction(Action{"a", "/r", "#t", "outerHTML"}).WithBody("<em>y</em>").Dismissible("/d", "Dismiss")},
|
||||
{"line with action", Problem("x").WithAction(Action{"a", "/r", "#t", "outerHTML"}).AsLine()},
|
||||
{"line with link", Problem("x").WithLink("a", "/").AsLine()},
|
||||
{"empty with no tone", Notice{}},
|
||||
}
|
||||
for _, r := range rows {
|
||||
t.Run(r.name, func(t *testing.T) {
|
||||
if _, err := r.n.Check(); err != nil {
|
||||
t.Errorf("%s: Check() = %v, want nil", r.name, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarshalText(t *testing.T) {
|
||||
for _, r := range []struct {
|
||||
n Notice
|
||||
want string
|
||||
}{
|
||||
{Problem("a ", Strong("b")), `{"E":"a b"}`},
|
||||
{Notice{}, `{"E":""}`},
|
||||
} {
|
||||
got, err := json.Marshal(struct{ E Notice }{r.n})
|
||||
if err != nil || string(got) != r.want {
|
||||
t.Errorf("json.Marshal = %s, want %s", got, r.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoticeImportsNoConsolePackage(t *testing.T) {
|
||||
const module = "git.coopcloud.tech/wiki-cafe/member-console/"
|
||||
out, err := exec.Command("go", "list", "-deps", "-f", "{{.ImportPath}}", module+"internal/notice").Output()
|
||||
if err != nil {
|
||||
t.Fatalf("go list -deps: %v", err)
|
||||
}
|
||||
for _, dep := range strings.Fields(string(out)) {
|
||||
if strings.HasPrefix(dep, module) && dep != module+"internal/notice" {
|
||||
t.Errorf("internal/notice depends on %s; it imports no package of the console", dep)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/htmltest"
|
||||
)
|
||||
|
||||
// TestStatusBadgeMapIsComplete pins page-anatomy "Status badges come from
|
||||
@@ -154,7 +156,9 @@ func TestPartsRender(t *testing.T) {
|
||||
t.Errorf("emptyState not-blocked branch wrong:\n%s", out)
|
||||
}
|
||||
out = Render(t, OperatorSet(t), "emptyState", EmptyStateParams{Blocked: true, BlockerCopy: "Create a product first.", PrerequisiteURL: "/operator/products", PrerequisiteLabel: "Products"})
|
||||
if !strings.Contains(out, `alert alert-warning`) || !strings.Contains(out, `href="/operator/products"`) {
|
||||
blocked := htmltest.Parse(t, out)
|
||||
warn := blocked.All(`[role="status"].app-notice-warning`)
|
||||
if len(warn) != 1 || !strings.Contains(warn[0].Text(), "Create a product first.") || blocked.Count(`a.alert-link[href="/operator/products"]`) != 1 || blocked.Count(".btn") != 0 {
|
||||
t.Errorf("emptyState blocked branch wrong:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
+18
-12
@@ -16,6 +16,7 @@ import (
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/billing"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/entitlements"
|
||||
internalstripe "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/stripe/store"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/plans"
|
||||
"github.com/google/uuid"
|
||||
stripe "github.com/stripe/stripe-go/v81"
|
||||
@@ -37,6 +38,8 @@ type BillingCheckoutHandler struct {
|
||||
// (server.Config.StripeMode); see MemberProductsHandler.StripeMode for
|
||||
// what the mode gates.
|
||||
StripeMode string
|
||||
// Templates renders the refusal's notice line.
|
||||
Templates *SafeTemplates
|
||||
}
|
||||
|
||||
// HandleCheckout creates a Stripe Checkout Session and redirects the member.
|
||||
@@ -81,7 +84,7 @@ func (h *BillingCheckoutHandler) HandleCheckout(w http.ResponseWriter, r *http.R
|
||||
if !move.Allows(plans.Checkout) {
|
||||
h.Logger.Info("checkout refused: the offer decision does not offer it",
|
||||
slog.String("price_id", target.price.PriceID), slog.String("reason", string(move.Reason)))
|
||||
target.refuse(w)
|
||||
target.refuse(w, h.Templates)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -179,19 +182,22 @@ type checkoutTarget struct {
|
||||
}
|
||||
|
||||
// refuse answers a request for a price Checkout does not sell.
|
||||
func (t checkoutTarget) refuse(w http.ResponseWriter) {
|
||||
refuseCheckout(w, len(t.ladders) > 0)
|
||||
func (t checkoutTarget) refuse(w http.ResponseWriter, tmpl *SafeTemplates) {
|
||||
refuseCheckout(w, tmpl, len(t.ladders) > 0)
|
||||
}
|
||||
|
||||
// refuseCheckout answers 422 with the plan sentence when the product is a tier
|
||||
// of a ladder, and the product sentence otherwise. No Stripe call and no row
|
||||
// precedes it.
|
||||
func refuseCheckout(w http.ResponseWriter, onLadder bool) {
|
||||
// of a ladder, and the product sentence otherwise, as the notice part's
|
||||
// Problem line: the control's error target swaps it in. No Stripe call and no
|
||||
// row precedes it.
|
||||
func refuseCheckout(w http.ResponseWriter, tmpl *SafeTemplates, onLadder bool) {
|
||||
msg := checkoutProductRefusal
|
||||
if onLadder {
|
||||
msg = checkoutPlanRefusal
|
||||
}
|
||||
http.Error(w, msg, http.StatusUnprocessableEntity)
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||
writeBody(w, tmpl.logger, []byte(tmpl.Fragment("notice", notice.Problem(msg).AsLine())))
|
||||
}
|
||||
|
||||
// resolveCheckoutTarget reads the posted price, its product and the product's
|
||||
@@ -209,14 +215,14 @@ func (h *BillingCheckoutHandler) resolveCheckoutTarget(w http.ResponseWriter, r
|
||||
parsed, err := uuid.Parse(postedID)
|
||||
if err != nil {
|
||||
h.Logger.Info("checkout refused: price_id is not a UUID")
|
||||
refuseCheckout(w, true)
|
||||
refuseCheckout(w, h.Templates, true)
|
||||
return checkoutTarget{}, false
|
||||
}
|
||||
priceID := parsed.String()
|
||||
price, err := h.BillingQ.GetPrice(ctx, priceID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
h.Logger.Info("checkout refused: no such price", slog.String("price_id", priceID))
|
||||
refuseCheckout(w, true)
|
||||
refuseCheckout(w, h.Templates, true)
|
||||
return checkoutTarget{}, false
|
||||
}
|
||||
if err != nil {
|
||||
@@ -248,7 +254,7 @@ func (h *BillingCheckoutHandler) resolveCheckoutTarget(w http.ResponseWriter, r
|
||||
if !evaluateMemberGate(product).OK() {
|
||||
h.Logger.Info("checkout refused: product not published for members",
|
||||
slog.String("product_id", product.ProductID), slog.String("lifecycle_status", product.LifecycleStatus))
|
||||
target.refuse(w)
|
||||
target.refuse(w, h.Templates)
|
||||
return checkoutTarget{}, false
|
||||
}
|
||||
return target, true
|
||||
@@ -307,7 +313,7 @@ func (h *BillingCheckoutHandler) checkoutPriceMapping(w http.ResponseWriter, r *
|
||||
}
|
||||
if err != nil || !mapping.StripePriceID.Valid {
|
||||
h.Logger.Error("stripe price mapping not found", slog.String("price_id", priceID))
|
||||
target.refuse(w)
|
||||
target.refuse(w, h.Templates)
|
||||
return mapping, false
|
||||
}
|
||||
// A price id recorded in the environment this key is not in, or one the
|
||||
@@ -322,7 +328,7 @@ func (h *BillingCheckoutHandler) checkoutPriceMapping(w http.ResponseWriter, r *
|
||||
slog.String("stripe_price_id", mapping.StripePriceID.String),
|
||||
slog.String("recorded_mode", internalstripe.RecordedMode(mapping.Livemode, mapping.SyncStatus)),
|
||||
slog.String("key_mode", keyMode))
|
||||
target.refuse(w)
|
||||
target.refuse(w, h.Templates)
|
||||
return mapping, false
|
||||
}
|
||||
return mapping, true
|
||||
|
||||
@@ -117,6 +117,7 @@ func newCheckoutEnv(t *testing.T, keyPrefix string) *checkoutEnv {
|
||||
BillingQ: billing.New(database),
|
||||
AuthConfig: &auth.Config{SessionManager: sm},
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
Templates: server.NewSafeTemplates(server.MemberSet(t), slog.New(slog.NewTextHandler(io.Discard, nil))),
|
||||
BaseURL: "https://example.test",
|
||||
StripeMode: internalstripe.ModeForKey(keyPrefix + "checkoutenv"),
|
||||
},
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/auth"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/billing"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/htmltest"
|
||||
"github.com/alexedwards/scs/v2"
|
||||
)
|
||||
|
||||
@@ -85,6 +86,7 @@ func postCheckout(t *testing.T, q billing.Querier, priceID string) *httptest.Res
|
||||
BillingQ: q,
|
||||
AuthConfig: authCfg,
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
Templates: NewSafeTemplates(MemberSet(t), slog.New(slog.NewTextHandler(io.Discard, nil))),
|
||||
BaseURL: "https://example.test",
|
||||
StripeMode: "test",
|
||||
}
|
||||
@@ -96,14 +98,20 @@ func postCheckout(t *testing.T, q billing.Querier, priceID string) *httptest.Res
|
||||
return rec
|
||||
}
|
||||
|
||||
// checkoutRefusalText reads the text of the one Problem line a refusal answers.
|
||||
func checkoutRefusalText(t *testing.T, body string) string {
|
||||
t.Helper()
|
||||
return htmltest.Parse(t, body).One(t, `.app-notice-line[role="alert"]`).Text()
|
||||
}
|
||||
|
||||
// wantCheckoutRefusal fails unless rec is the 422 refusal with the sentence.
|
||||
func wantCheckoutRefusal(t *testing.T, rec *httptest.ResponseRecorder, sentence string) {
|
||||
t.Helper()
|
||||
if rec.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusUnprocessableEntity, rec.Body.String())
|
||||
}
|
||||
if got := strings.TrimSpace(rec.Body.String()); got != sentence {
|
||||
t.Errorf("body = %q, want %q", got, sentence)
|
||||
if got := checkoutRefusalText(t, rec.Body.String()); got != "Error: "+sentence {
|
||||
t.Errorf("body = %q, want %q", got, "Error: "+sentence)
|
||||
}
|
||||
if strings.Contains(sentence, "—") {
|
||||
t.Errorf("refusal sentence contains an em dash: %q", sentence)
|
||||
@@ -210,3 +218,23 @@ func TestCheckoutRefusesAnUnknownPrice(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckoutRefusalIsAProblemLine: the refused checkout answers the control's
|
||||
// error target with one Problem line holding the sentence, not a box.
|
||||
func TestCheckoutRefusalIsAProblemLine(t *testing.T) {
|
||||
q := fakeCheckoutQuerier{
|
||||
price: billing.Price{PriceID: checkoutPriceID, ProductID: "prod-draft", IsActive: true},
|
||||
product: billing.Product{ProductID: "prod-draft", LifecycleStatus: "draft", IsActive: true, IsPublic: true},
|
||||
ladders: []billing.ListLaddersByProductRow{{PlanLadderID: "ladder-1", ProductID: "prod-draft"}},
|
||||
}
|
||||
rec := postCheckout(t, q, checkoutPriceID)
|
||||
page := htmltest.Parse(t, rec.Body.String())
|
||||
lines := page.All(`.app-notice-line[role="alert"]`)
|
||||
if rec.Code != http.StatusUnprocessableEntity || len(lines) != 1 || page.Count(".alert") != 0 ||
|
||||
!strings.Contains(lines[0].Text(), checkoutPlanRefusal) {
|
||||
t.Errorf("the refusal answered %d:\n%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); ct != "text/html; charset=utf-8" {
|
||||
t.Errorf("the refusal's Content-Type = %q, want text/html; charset=utf-8", ct)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,6 +110,7 @@ func (w *checkoutOfferWorld) post(orgID, priceID string, billingQ billing.Querie
|
||||
EntitlementsQ: entsQ,
|
||||
AuthConfig: authCfg,
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
Templates: NewSafeTemplates(MemberSet(w.t), slog.New(slog.NewTextHandler(io.Discard, nil))),
|
||||
BaseURL: "https://example.test",
|
||||
StripeMode: "test",
|
||||
}
|
||||
@@ -141,8 +142,8 @@ func (w *checkoutOfferWorld) postReal(orgID, priceID string) (int, string) {
|
||||
// wantRefused fails unless the request was refused with the plan sentence.
|
||||
func wantRefused(t *testing.T, code int, body string) {
|
||||
t.Helper()
|
||||
if code != http.StatusUnprocessableEntity || strings.TrimSpace(body) != checkoutPlanRefusal {
|
||||
t.Errorf("status %d body %q, want 422 %q", code, strings.TrimSpace(body), checkoutPlanRefusal)
|
||||
if code != http.StatusUnprocessableEntity || checkoutRefusalText(t, body) != "Error: "+checkoutPlanRefusal {
|
||||
t.Errorf("status %d body %q, want 422 %q", code, body, "Error: "+checkoutPlanRefusal)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,8 +267,8 @@ func TestCheckoutRefusesAOneTimePrice(t *testing.T) {
|
||||
})
|
||||
t.Run("a product on no ladder", func(t *testing.T) {
|
||||
code, body := w.postReal(org, w.prices[addonOnce])
|
||||
if code != http.StatusUnprocessableEntity || strings.TrimSpace(body) != checkoutProductRefusal {
|
||||
t.Errorf("status %d body %q, want 422 %q", code, strings.TrimSpace(body), checkoutProductRefusal)
|
||||
if code != http.StatusUnprocessableEntity || checkoutRefusalText(t, body) != "Error: "+checkoutProductRefusal {
|
||||
t.Errorf("status %d body %q, want 422 %q", code, body, "Error: "+checkoutProductRefusal)
|
||||
}
|
||||
})
|
||||
t.Run("control: another product on no ladder", func(t *testing.T) {
|
||||
@@ -395,6 +396,7 @@ func TestCheckoutAnswersHTMXWithAClientRedirect(t *testing.T) {
|
||||
EntitlementsQ: entitlements.New(db),
|
||||
AuthConfig: &auth.Config{SessionManager: sm},
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
Templates: NewSafeTemplates(MemberSet(t), slog.New(slog.NewTextHandler(io.Discard, nil))),
|
||||
BaseURL: "https://example.test",
|
||||
StripeMode: "test",
|
||||
}
|
||||
@@ -498,6 +500,7 @@ func TestCheckoutRefusesALadderWhosePlanIsSuspended(t *testing.T) {
|
||||
Database: db, BillingQ: billing.New(db), EntitlementsQ: entitlements.New(db),
|
||||
AuthConfig: &auth.Config{SessionManager: sm},
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
Templates: NewSafeTemplates(MemberSet(t), slog.New(slog.NewTextHandler(io.Discard, nil))),
|
||||
BaseURL: "https://example.test", StripeMode: "test",
|
||||
},
|
||||
}
|
||||
@@ -521,7 +524,7 @@ func checkSuspendedCheckout(t *testing.T, env suspendedCheckout, row suspendedCh
|
||||
t.Errorf("Checkout called Stripe: %v", env.mock.Calls[before:])
|
||||
}
|
||||
switch {
|
||||
case row.refused && (rec.Code != http.StatusUnprocessableEntity || body != checkoutPlanRefusal):
|
||||
case row.refused && (rec.Code != http.StatusUnprocessableEntity || checkoutRefusalText(t, body) != "Error: "+checkoutPlanRefusal):
|
||||
t.Errorf("Checkout of a tier on a suspended plan's ladder was not refused: status %d body %q, want 422 %q", rec.Code, body, checkoutPlanRefusal)
|
||||
case !row.refused && (rec.Code != http.StatusServiceUnavailable || !strings.Contains(body, "billing setup in progress")):
|
||||
t.Errorf("Checkout of a tier of another ladder: status %d body %q, want 503 billing setup in progress", rec.Code, body)
|
||||
@@ -630,6 +633,7 @@ func newPaidUnderGrant(t *testing.T) paidUnderGrant {
|
||||
Database: db, BillingQ: billing.New(db), EntitlementsQ: entitlements.New(db),
|
||||
AuthConfig: &auth.Config{SessionManager: env.sm},
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
Templates: NewSafeTemplates(MemberSet(t), slog.New(slog.NewTextHandler(io.Discard, nil))),
|
||||
BaseURL: "https://example.test", StripeMode: "test",
|
||||
}
|
||||
return env
|
||||
@@ -668,7 +672,7 @@ func TestCheckoutRefusesALadderASubscriptionPaysFor(t *testing.T) {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
rec, calls := env.post(t, row.org, row.price)
|
||||
body := strings.TrimSpace(rec.Body.String())
|
||||
if rec.Code != http.StatusUnprocessableEntity || body != refusal || calls != 0 {
|
||||
if rec.Code != http.StatusUnprocessableEntity || checkoutRefusalText(t, body) != "Error: "+refusal || calls != 0 {
|
||||
t.Errorf("%s: checkout answered %d, want 422, with %d Stripe calls, body %q", row.name, rec.Code, calls, body)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -5,10 +5,12 @@ package server
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/forms"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/htmltest"
|
||||
)
|
||||
|
||||
// The billing line's placement (merchant-disclosure D5): once under each
|
||||
@@ -181,21 +183,27 @@ func TestPayInvoiceReferencesTheBillingLine(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSuccessReturnRepeatsTheFacts(t *testing.T) {
|
||||
body := Render(t, MemberSet(t), "index.html", IndexPageData{CheckoutStatus: "success", BillingFacts: BillingFacts{Sentences: shownFacts}})
|
||||
alert := body[strings.Index(body, "alert-success"):]
|
||||
alert = alert[:strings.Index(alert, "</div>\n")]
|
||||
if !strings.Contains(alert, "Billed by Acme Holdings LLC. Card statement: ACMEHOLDINGS.") {
|
||||
t.Errorf("the success alert does not repeat the facts: %s", alert)
|
||||
set := MemberSet(t)
|
||||
st := NewSafeTemplates(set, slog.Default())
|
||||
page := func(status string, facts BillingFacts) string {
|
||||
data := IndexPageData{CheckoutStatus: status, BillingFacts: facts}
|
||||
data.SetNotices(st)
|
||||
return Render(t, set, "index.html", data)
|
||||
}
|
||||
if strings.Contains(alert, "text-muted") {
|
||||
body := page("success", BillingFacts{Sentences: shownFacts})
|
||||
alert := htmltest.Parse(t, body).One(t, ".app-notice-done")
|
||||
if !strings.Contains(alert.Text(), "Billed by Acme Holdings LLC. Card statement: ACMEHOLDINGS.") {
|
||||
t.Errorf("the success alert does not repeat the facts: %s", alert.HTML())
|
||||
}
|
||||
if strings.Contains(alert.HTML(), "text-muted") {
|
||||
t.Error("the facts inside the alert use muted text, which falls under the contrast floor there")
|
||||
}
|
||||
|
||||
plain := Render(t, MemberSet(t), "index.html", IndexPageData{CheckoutStatus: "success"})
|
||||
plain := page("success", BillingFacts{})
|
||||
if strings.Contains(plain, "Billed by") {
|
||||
t.Error("a success return with recognised names still shows a billing line")
|
||||
}
|
||||
cancel := Render(t, MemberSet(t), "index.html", IndexPageData{CheckoutStatus: "cancel", BillingFacts: BillingFacts{Sentences: shownFacts}})
|
||||
cancel := page("cancel", BillingFacts{Sentences: shownFacts})
|
||||
if strings.Contains(cancel, "Billed by") {
|
||||
t.Error("a cancelled return shows the billing line")
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
)
|
||||
|
||||
// Server-side composition (spec page-anatomy "A page arrives complete";
|
||||
@@ -52,10 +54,11 @@ func NewInclude(router http.Handler) Include {
|
||||
}
|
||||
}
|
||||
|
||||
// IncludeOr renders the fragment, or an inline notice naming what could not
|
||||
// IncludeOr renders the fragment, or a Problem notice naming what could not
|
||||
// be loaded, so a failing region never fails the page and never renders
|
||||
// blank. A nil Include (a test set without a router) renders nothing.
|
||||
func IncludeOr(inc Include, logger *slog.Logger, r *http.Request, path, what string) template.HTML {
|
||||
// blank. A nil Include (a test set without a router) renders nothing, and
|
||||
// so does a nil t on a failure.
|
||||
func IncludeOr(inc Include, t *SafeTemplates, logger *slog.Logger, r *http.Request, path, what string) template.HTML {
|
||||
if inc == nil {
|
||||
return ""
|
||||
}
|
||||
@@ -64,7 +67,10 @@ func IncludeOr(inc Include, logger *slog.Logger, r *http.Request, path, what str
|
||||
if logger != nil {
|
||||
logger.Error("page region failed to compose", slog.String("path", path), slog.Any("error", err))
|
||||
}
|
||||
return template.HTML(`<div class="alert alert-danger" role="alert">Could not load ` + template.HTMLEscapeString(what) + `.</div>`)
|
||||
if t == nil {
|
||||
return ""
|
||||
}
|
||||
return t.Fragment("notice", notice.Problem("Could not load "+what+"."))
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -120,4 +126,25 @@ type IndexPageData struct {
|
||||
// the member and what their card statement says (merchant-disclosure
|
||||
// D5). Empty on every other load.
|
||||
BillingFacts BillingFacts
|
||||
// CheckoutNotice and PendingClaimsNotice are the dashboard's two
|
||||
// notices, set by SetNotices from the fields above.
|
||||
CheckoutNotice notice.Notice
|
||||
PendingClaimsNotice notice.Notice
|
||||
}
|
||||
|
||||
// SetNotices sets CheckoutNotice from CheckoutStatus and BillingFacts, and
|
||||
// PendingClaimsNotice from PendingDomainClaims. The handler and the tests
|
||||
// that render the page both call it.
|
||||
func (d *IndexPageData) SetNotices(t *SafeTemplates) {
|
||||
d.CheckoutNotice = notice.Notice{}
|
||||
switch d.CheckoutStatus {
|
||||
case "success":
|
||||
d.CheckoutNotice = notice.Done("").WithBody(t.Fragment("checkoutReturnWords", d.BillingFacts))
|
||||
case "cancel":
|
||||
d.CheckoutNotice = notice.Information("Checkout canceled. Your current plan is unchanged.")
|
||||
}
|
||||
d.PendingClaimsNotice = notice.Notice{}
|
||||
if len(d.PendingDomainClaims) > 0 {
|
||||
d.PendingClaimsNotice = notice.Information("").WithBody(t.Fragment("pendingClaimsWords", d.PendingDomainClaims))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,10 +4,13 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/htmltest"
|
||||
)
|
||||
|
||||
// TestIncludeComposesInProcess pins page-anatomy "A page arrives complete":
|
||||
@@ -42,11 +45,40 @@ func TestIncludeComposesInProcess(t *testing.T) {
|
||||
t.Error("an unregistered include must error")
|
||||
}
|
||||
|
||||
notice := IncludeOr(inc, nil, r, "/partials/bad", "your <plans>")
|
||||
if !strings.Contains(string(notice), `alert alert-danger`) || !strings.Contains(string(notice), "Could not load your <plans>.") {
|
||||
t.Errorf("IncludeOr must render an escaped inline notice, got %q", notice)
|
||||
st := NewSafeTemplates(OperatorSet(t), slog.New(slog.DiscardHandler))
|
||||
got := IncludeOr(inc, st, nil, r, "/partials/bad", "your <plans>")
|
||||
if !strings.Contains(string(got), "Could not load your <plans>.") {
|
||||
t.Errorf("IncludeOr must render an escaped Problem notice, got %q", got)
|
||||
}
|
||||
if IncludeOr(nil, nil, r, "/partials/ok", "x") != "" {
|
||||
if IncludeOr(nil, st, nil, r, "/partials/ok", "x") != "" {
|
||||
t.Error("a nil Include renders nothing")
|
||||
}
|
||||
if IncludeOr(inc, nil, nil, r, "/partials/bad", "x") != "" {
|
||||
t.Error("a failed include renders nothing without templates")
|
||||
}
|
||||
}
|
||||
|
||||
// TestIncludeOrRendersAProblemNotice pins that a failed include is a Problem
|
||||
// notice and a successful one is its HTML unchanged.
|
||||
func TestIncludeOrRendersAProblemNotice(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /partials/ok", func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte("<p>ok</p>"))
|
||||
})
|
||||
mux.HandleFunc("GET /partials/bad", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "boom", http.StatusInternalServerError)
|
||||
})
|
||||
inc := NewInclude(mux)
|
||||
st := NewSafeTemplates(OperatorSet(t), slog.New(slog.DiscardHandler))
|
||||
r := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
|
||||
out := string(IncludeOr(inc, st, nil, r, "/partials/bad", "workspaces"))
|
||||
page := htmltest.Parse(t, out)
|
||||
notices := page.All(`[role="alert"]`)
|
||||
if len(notices) != 1 || !strings.Contains(notices[0].Text(), "Could not load workspaces.") {
|
||||
t.Errorf("a failed include rendered:\n%s", out)
|
||||
}
|
||||
if got := IncludeOr(inc, st, nil, r, "/partials/ok", "workspaces"); got != "<p>ok</p>" {
|
||||
t.Errorf("a successful include rendered:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package server
|
||||
|
||||
// RenderPlansAfterMove is the answer a plan move gives once it has run, for
|
||||
// the external tests that read its HX-Trigger.
|
||||
var RenderPlansAfterMove = (*MemberProductsHandler).renderPlansAfterMove
|
||||
@@ -40,6 +40,7 @@ import (
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/identity"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/organization"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/htmltest"
|
||||
wf "git.coopcloud.tech/wiki-cafe/member-console/internal/workflows/entitlements"
|
||||
)
|
||||
|
||||
@@ -1524,14 +1525,17 @@ func TestGrantResumptionManage_ARefusalWithoutItsRowIsNeverSilent(t *testing.T)
|
||||
if !strings.Contains(row, "Choose a time in the future.") || !strings.Contains(row, `value="stale page"`) {
|
||||
t.Errorf("the refusal is not bound to the head's row:\n%s", body)
|
||||
}
|
||||
if strings.Contains(body, "<strong>Error:</strong>") {
|
||||
t.Errorf("a refusal bound to a row also reads as the banner")
|
||||
for _, banner := range htmltest.Parse(t, body).All(".app-notice-problem") {
|
||||
if strings.Contains(banner.Text(), "Valid until") {
|
||||
t.Errorf("a refusal bound to a row also reads as the banner")
|
||||
}
|
||||
}
|
||||
|
||||
// A search that renders no row: the refusal is the banner.
|
||||
target := "/partials/operator/organizations/" + org + "/grants/" + g + "/manage?q=no-such-product"
|
||||
code, body, _ = w.h.postOrgGrantAt(w.h.handler.ManageGrant, target, org, g, manageRow(g, past))
|
||||
if code != http.StatusUnprocessableEntity || !strings.Contains(body, "<strong>Error:</strong> Valid until: Choose a time in the future.") {
|
||||
banners := htmltest.Parse(t, body).All(`[role="alert"].app-notice-problem`)
|
||||
if code != http.StatusUnprocessableEntity || len(banners) != 1 || banners[0].Text() != "Error: Valid until: Choose a time in the future." {
|
||||
t.Errorf("a refusal no row shows: status=%d, want the banner:\n%s", code, body)
|
||||
}
|
||||
if strings.Contains(body, `name="rows.`) {
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/entitlements"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/forms"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/htmltest"
|
||||
)
|
||||
|
||||
func TestJoinWithAnd(t *testing.T) {
|
||||
@@ -505,8 +506,16 @@ func TestOrgEnrollmentGrantsTable_RefusalStaysInTheRow(t *testing.T) {
|
||||
t.Errorf("the refused row lacks %q:\n%s", want, row)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(out, `<div class="alert alert-danger mb-3">This grant collides with a rung already held by another delivery.</div>`) {
|
||||
t.Errorf("a refusal on a field the row does not carry is not in the form's slot")
|
||||
inSlot := false
|
||||
for _, slot := range htmltest.Parse(t, out).All(".app-form-error") {
|
||||
for _, n := range slot.All(`[role="alert"]`) {
|
||||
if strings.Contains(n.Text(), "This grant collides with a rung already held by another delivery.") {
|
||||
inSlot = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !inSlot {
|
||||
t.Errorf("a refusal on a field the row does not carry is not a Problem notice in the form's slot")
|
||||
}
|
||||
if strings.Contains(row, "collides") {
|
||||
t.Errorf("a refusal on a field the row does not carry landed in the row")
|
||||
|
||||
@@ -446,7 +446,7 @@ func projectGrant(g GrantViewModel) grantProjection {
|
||||
|
||||
func projectGrantsPage(body any) (template.HTML, error) {
|
||||
d := body.(GrantsData)
|
||||
p := grantsPageProjection{Error: d.Error, Q: d.Nav.Q, Facet: d.Nav.Facet, Page: d.Nav.Page, Total: d.Nav.Total}
|
||||
p := grantsPageProjection{Error: d.Error.Text.String(), Q: d.Nav.Q, Facet: d.Nav.Facet, Page: d.Nav.Page, Total: d.Nav.Total}
|
||||
for _, g := range d.Grants {
|
||||
row := projectGrant(g)
|
||||
row.OrgID, row.OrgName, row.TargetBadge, row.CreatedAt = g.OrgID, g.OrgName, g.TargetBadge().Label, g.CreatedAt
|
||||
@@ -457,7 +457,7 @@ func projectGrantsPage(body any) (template.HTML, error) {
|
||||
|
||||
func projectLedger(d OrgEnrollmentData) (template.HTML, error) {
|
||||
p := ledgerProjection{
|
||||
GrantsError: d.GrantsError, GrantsTotal: d.GrantsTotal, GrantsListQuery: d.GrantsListQuery,
|
||||
GrantsError: d.GrantsError.Text.String(), GrantsTotal: d.GrantsTotal, GrantsListQuery: d.GrantsListQuery,
|
||||
Q: d.GrantsNav.Q, Facet: d.GrantsNav.Facet, Page: d.GrantsNav.Page, PerPage: d.GrantsNav.PerPage,
|
||||
Total: d.GrantsNav.Total, Extra: d.GrantsNav.Extra,
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/plans"
|
||||
)
|
||||
|
||||
@@ -42,7 +43,7 @@ type AddonsData struct {
|
||||
// "Products" when no plans exist and this section IS the catalog — a
|
||||
// plan-less deployment must not read its whole catalog as extras.
|
||||
HasPlans bool
|
||||
Error string
|
||||
Error notice.Notice
|
||||
// BillingFacts is the add-ons section's own paragraph, under the same
|
||||
// rule as the Plans one; every listed add-on leads to Stripe, so the
|
||||
// section's presence is the whole condition (merchant-disclosure D5).
|
||||
@@ -73,7 +74,7 @@ func (h *MemberProductsHandler) buildAddonsData(ctx context.Context) AddonsData
|
||||
products, err := h.BillingQ.ListPublicProducts(ctx)
|
||||
if err != nil {
|
||||
h.Logger.Error("failed to list public products", slog.Any("error", err))
|
||||
data.Error = "Failed to load extras"
|
||||
data.Error = notice.Problem("Failed to load extras")
|
||||
return data
|
||||
}
|
||||
|
||||
@@ -88,7 +89,7 @@ func (h *MemberProductsHandler) buildAddonsData(ctx context.Context) AddonsData
|
||||
planProducts, err := h.BillingQ.ListPublicPlanProducts(ctx)
|
||||
if err != nil {
|
||||
h.Logger.Error("failed to list plan products for tier exclusion", slog.Any("error", err))
|
||||
return AddonsData{Error: "Failed to load extras"}
|
||||
return AddonsData{Error: notice.Problem("Failed to load extras")}
|
||||
}
|
||||
for _, p := range planProducts {
|
||||
tierIDs[p.ProductID] = true
|
||||
@@ -105,7 +106,7 @@ func (h *MemberProductsHandler) buildAddonsData(ctx context.Context) AddonsData
|
||||
price, err := loader.defaultPrice(ctx, p.ProductID)
|
||||
if err != nil {
|
||||
h.Logger.Error("failed to read the price facts of a product", slog.String("product_id", p.ProductID), slog.Any("error", err))
|
||||
return AddonsData{Error: "Failed to load extras"}
|
||||
return AddonsData{Error: notice.Problem("Failed to load extras")}
|
||||
}
|
||||
if !plans.OffLadder(plans.Target{ProductID: p.ProductID, Listed: true, Price: price.Price}).Allows(plans.Checkout) {
|
||||
// A catalog offers what can be bought (maintainer, 2026-09-19;
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package server_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/billing"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/entitlements"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/server"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/htmltest"
|
||||
)
|
||||
|
||||
// TestMemberAnswersToast: a completed plan move and a released domain answer
|
||||
// with a success toast in HX-Trigger, and their regions hold no Done notice.
|
||||
func TestMemberAnswersToast(t *testing.T) {
|
||||
planMove := func(action string) func(t *testing.T) *httptest.ResponseRecorder {
|
||||
return func(t *testing.T) *httptest.ResponseRecorder {
|
||||
db := dbtest.Open(t)
|
||||
h, err := server.NewMemberProductsHandler(server.MemberProductsConfig{
|
||||
BillingQ: billing.New(db), EntitlementsQ: entitlements.New(db),
|
||||
Database: db, Logger: discardLogger(), StripeMode: "test",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("member handler: %v", err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
server.RenderPlansAfterMove(h, rec, context.Background(), "00000000-0000-0000-0000-000000000000", nil, action)
|
||||
return rec
|
||||
}
|
||||
}
|
||||
release := func(t *testing.T) *httptest.ResponseRecorder {
|
||||
env := newDomainsTestEnv(t, "connect.example.test", true)
|
||||
workspace := newDomainsWorkspace(t, env.database, "toast")
|
||||
claim, err := env.registry.ClaimExternal(context.Background(), workspace, "toast"+time.Now().Format("150405.000000000")+".example")
|
||||
if err != nil {
|
||||
t.Fatalf("claim: %v", err)
|
||||
}
|
||||
activateClaim(t, env.database, claim.ClaimID)
|
||||
req := postForm(env.sessionFor(t, workspace), "/partials/domains/claims/"+claim.ClaimID+"/release")
|
||||
req.SetPathValue("claimID", claim.ClaimID)
|
||||
rec := httptest.NewRecorder()
|
||||
env.handler.ReleaseClaim(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("release = %d, want 200", rec.Code)
|
||||
}
|
||||
return rec
|
||||
}
|
||||
for _, row := range []struct {
|
||||
name string
|
||||
answer func(t *testing.T) *httptest.ResponseRecorder
|
||||
sentence string
|
||||
changed bool
|
||||
}{
|
||||
{"switch", planMove("switch"), "Your plan change has been submitted.", true},
|
||||
{"cancel", planMove("cancel"), "Your cancellation is scheduled.", true},
|
||||
{"release", release, "Domain released. It's free to claim again.", false},
|
||||
} {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
rec := row.answer(t)
|
||||
var trigger map[string]any
|
||||
raw := rec.Header().Get("HX-Trigger")
|
||||
if err := json.Unmarshal([]byte(raw), &trigger); err != nil || trigger["showSuccessToast"] != row.sentence {
|
||||
t.Errorf("%s: HX-Trigger = %q, want showSuccessToast %q", row.name, raw, row.sentence)
|
||||
}
|
||||
if _, has := trigger["entitlements-changed"]; has != row.changed {
|
||||
t.Errorf("%s: HX-Trigger = %q, entitlements-changed present = %v, want %v", row.name, raw, has, row.changed)
|
||||
}
|
||||
if n := htmltest.Parse(t, rec.Body.String()).Count(".app-notice-done, .alert-success"); n != 0 {
|
||||
t.Errorf("%s: the region still holds a done notice:\n%s", row.name, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -99,8 +99,8 @@ func TestMemberCatalogGateFollowsTheMappingEnvironment(t *testing.T) {
|
||||
stale := seed("EnvGate Stale", "stale", live)
|
||||
|
||||
data := h.buildAddonsData(ctx)
|
||||
if data.Error != "" {
|
||||
t.Fatalf("buildAddonsData: %s", data.Error)
|
||||
if !data.Error.Empty() {
|
||||
t.Fatalf("buildAddonsData: %s", data.Error.Text.String())
|
||||
}
|
||||
listed := make(map[string]bool, len(data.Addons))
|
||||
for _, a := range data.Addons {
|
||||
@@ -156,8 +156,8 @@ func checkCatalogWithoutAKey(t *testing.T, ctx context.Context, h *MemberProduct
|
||||
t.Helper()
|
||||
keyless := &MemberProductsHandler{BillingQ: h.BillingQ, Logger: h.Logger, Database: database}
|
||||
data := keyless.buildAddonsData(ctx)
|
||||
if data.Error != "" {
|
||||
t.Fatalf("buildAddonsData with no Stripe key: %s", data.Error)
|
||||
if !data.Error.Empty() {
|
||||
t.Fatalf("buildAddonsData with no Stripe key: %s", data.Error.Text.String())
|
||||
}
|
||||
listed := make(map[string]bool, len(data.Addons))
|
||||
for _, a := range data.Addons {
|
||||
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/auth"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/domains"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/entitlements"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/web"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/workflows/clientholder"
|
||||
wfdomains "git.coopcloud.tech/wiki-cafe/member-console/internal/workflows/domains"
|
||||
@@ -137,8 +138,7 @@ type MemberDomainsData struct {
|
||||
// gate must hold (entitlement granted AND connect target configured);
|
||||
// every POST re-enforces it, so this is presentation only.
|
||||
CanAddExternal bool
|
||||
Error string
|
||||
Notice string
|
||||
Error notice.Notice
|
||||
}
|
||||
|
||||
// MemberDomainRecordView is one row of the DNS instructions table: a record
|
||||
@@ -177,7 +177,27 @@ type MemberDomainClaimData struct {
|
||||
// Hosted marks a claim that is not an external one: it carries no
|
||||
// challenge and has no records to publish.
|
||||
Hosted bool
|
||||
Error string
|
||||
Error notice.Notice
|
||||
}
|
||||
|
||||
// Outcome is the notice a settled claim shows in place of its DNS records,
|
||||
// and the empty notice while the claim is pending.
|
||||
func (d MemberDomainClaimData) Outcome() notice.Notice {
|
||||
switch {
|
||||
case d.Hosted:
|
||||
return notice.Information(notice.Strong(d.Domain), " is part of our hosting; there's nothing for you to publish in DNS. Any name inside it is yours to use.")
|
||||
case d.Canceled:
|
||||
return notice.Information("Verification for ", notice.Strong(d.Domain), " was canceled. The domain is free again; start over when you're ready.")
|
||||
case d.Released:
|
||||
return notice.Information(notice.Strong(d.Domain), " was released. The domain is free again; claim it back at any time.")
|
||||
case d.Expired:
|
||||
return notice.Warning("Verification for ", notice.Strong(d.Domain), " expired before the DNS record was found. The domain is free again; restart verification at any time.")
|
||||
case d.Verified && d.Placed:
|
||||
return notice.Done(notice.Strong(d.Domain), " is verified ✓ and in use. Any name inside it is yours too: creating a site there needs no further DNS verification.")
|
||||
case d.Verified:
|
||||
return notice.Done(notice.Strong(d.Domain), " is verified ✓. Create a site with it from the service card on your dashboard; creation is instant now, with no further DNS verification.")
|
||||
}
|
||||
return notice.Notice{}
|
||||
}
|
||||
|
||||
// --- Presentation helpers ---
|
||||
@@ -281,14 +301,14 @@ func (h *MemberDomainsHandler) surfaceData(ctx context.Context, workspaceID stri
|
||||
data.CanAddExternal = enabled
|
||||
|
||||
if h.Registry == nil {
|
||||
data.Error = "Domains aren't available right now."
|
||||
data.Error = notice.Problem("Domains aren't available right now.")
|
||||
return data
|
||||
}
|
||||
rows, err := h.Registry.ListLiveClaims(ctx, workspaceID)
|
||||
if err != nil {
|
||||
h.Logger.Error("failed to list domain claims",
|
||||
slog.String("workspace_id", workspaceID), slog.Any("error", err))
|
||||
data.Error = "Failed to load your domains."
|
||||
data.Error = notice.Problem("Failed to load your domains.")
|
||||
return data
|
||||
}
|
||||
for _, row := range rows {
|
||||
@@ -588,16 +608,16 @@ func (h *MemberDomainsHandler) ReleaseClaim(w http.ResponseWriter, r *http.Reque
|
||||
data := h.surfaceData(ctx, session.WorkspaceID)
|
||||
switch {
|
||||
case err == nil:
|
||||
data.Notice = "Domain released. It's free to claim again."
|
||||
fireSuccessToast(w, "Domain released. It's free to claim again.")
|
||||
case errors.Is(err, domains.ErrClaimHasPlacements):
|
||||
data.Error = h.placementGuardMessage(ctx, claimID)
|
||||
data.Error = notice.Problem(h.placementGuardMessage(ctx, claimID))
|
||||
case errors.Is(err, domains.ErrClaimNotReleasable):
|
||||
data.Error = "That domain is part of our hosting and can't be released."
|
||||
data.Error = notice.Problem("That domain is part of our hosting and can't be released.")
|
||||
case errors.Is(err, domains.ErrClaimNotActive):
|
||||
data.Error = "That domain isn't active; cancel its verification instead."
|
||||
data.Error = notice.Problem("That domain isn't active; cancel its verification instead.")
|
||||
default:
|
||||
h.Logger.Error("failed to release claim", slog.Any("error", err))
|
||||
data.Error = "We couldn't release that domain. Try again."
|
||||
data.Error = notice.Problem("We couldn't release that domain. Try again.")
|
||||
}
|
||||
h.Templates.Render(w, "member_domains.html", data)
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user