@micha.bigler/ui-core-micha 3.3.1 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,15 @@
2
2
 
3
3
  Only notable, user-facing changes. Not every version — see `WORK_ORDERS.md` for the full history.
4
4
 
5
+ ## 3.4.0 — AUTH-6
6
+
7
+ `QrSignupManager` gains two optional props, both backward-compatible (existing callers keep
8
+ today's behaviour unchanged): `registrationContext` (merged into the generated QR's
9
+ `registration_context`, letting a consumer scope the signup to e.g. a specific department) and
10
+ `defaultMaxRedemptions` (overrides the component's own low default, for a poster-scale code meant
11
+ to be scanned by many people). Fixed in the same change: a context change combined with a
12
+ previously-customized redemption count could fire a redundant `createSignupQr` call.
13
+
5
14
  ## 3.3.1 — UCM-CHART-18
6
15
 
7
16
  **Exported PNGs no longer contain interactive controls — buttons, drill-down links, and the like
package/WORK_ORDERS.md CHANGED
@@ -27,6 +27,7 @@ prefixed ID; never reuse a bare flat number across workstreams.
27
27
 
28
28
  | ID | Titel | Beschreibung | Datum | Status | Commit(s) | Notiz |
29
29
  |---|---|---|---|---|---|---|
30
+ | AUTH-6 | `QrSignupManager` additive `registrationContext`/`defaultMaxRedemptions` props | jg-ferien's `JG-MEM-1` (department QR-join) needs a per-department signup context and a high, poster-scale redemption default — `QrSignupManager` only exposed `enabled`/`expiryDays`. Two new optional props added, both defaulting to today's exact behaviour: `registrationContext` (merged into the generated token's `registration_context`) and `defaultMaxRedemptions` (overrides the low internal default). | 2026-08-28 | done | 1749c09 | No WO file — operator-requested, fixed directly, same convention as AUTH-3. Tier 3 (shared-core). Implemented by `codex exec` (jg-ferien's JG-MEM-1 dispatch touched this repo additively per that WO's own allowance), left uncommitted for the Orchestrator's own review before landing here. **review: claude/sonnet · 2 raised · 2 accepted · worst accepted: defect** — (R1: the new context-change effect also calls `setMaxRedemptions`, and with `maxRedemptions` in that same effect's dependency array, a context change after the admin had typed a custom redemption count fired a second, redundant `createSignupQr` call — fixed by reading the current value through a ref instead of a reactive dependency, so `setMaxRedemptions` no longer re-triggers the effect that just set it; R2: the one new test only covered the happy path on a fresh mount, with no test proving the existing `AccountPage` call (`enabled`/`expiryDays` only) stays byte-for-byte unaffected, and no test that would have caught R1 — two regression tests added: a bare old-prop-shape call asserting the exact legacy payload + single call, and a context-change-after-custom-redemptions call asserting exactly one `createSignupQr` invocation). Confirmed backward compatible against the one existing consumer, `AccountPage.jsx:369-372` (unaffected — it never passes the new props). Tests: `QrSignupManager.registrationContext.test.jsx` (3/3, incl. the two new regression cases) + `AccountPage.test.jsx` (4/4) + `SignUpPage.test.jsx` (10/10) all green — 17/17 total across the three files touching this component. No `ui_reviewer`/`sec_reviewer` (pure prop/effect-timing change, no visual surface, no auth-enforcement logic — the actual token validation stays entirely server-side in `django-core-micha`, already reviewed under `JG-MEM-1`). **Rebased onto a concurrent session's `UCM-CHART-17`/`-18` pushes (3.3.0/3.3.1 already published) — republished as 3.4.0 instead of the originally-committed 3.3.0** (minor — new capability, not a fix), via the repo's `publish.yml` (push-to-`main` + version bump). jg-ferien bumps its pin separately once this lands on npm. |
30
31
  | UCM-CHART-18 | The PNG export shows what the chart says, not what the user can click | Two defects, one file, a few lines apart -- both raised by `HRAM-CHT-7`'s independent `ui_reviewer` (2026-08-25) and confirmed, partly by reading and partly live. **(1) Interactive controls are in the image.** Since 3.3.0 the PNG rasterises `ChartFrame`'s whole `chartRef` box, and `chartRef` wraps `children` only -- not `toolbar`, `controls` or `meta` -- so anything a panel renders as children is now in the file: hram's `StructuralReachabilityPanel:468` footer `IconButton` (always visible, so **every** PNG of that panel carries a button), `AllocationPerformancePanel:536,548` and `OptimizationResultsPanel:1120,1141`. **(2) `transform` is not inlined** -- neither property list (`:32-36`, `:44-52`) has it, so `OptimizationResultsPanel:1107`'s rotated legend swatch exports as a **square instead of a diamond**. **Fixed here rather than in the app for two reasons:** it is a property of the element kind, not of each panel -- an exported image should show what the chart communicates, not what can be clicked -- and the alternative (moving controls into `ChartFrame`'s `controls`/`toolbar` slots) would **undo a deliberate design decision**, since `HRAM-RES-30` put that info affordance in the footer beside the caveat line. After this, hram needs **only a pin bump**. Full order [`work-orders/UCM-CHART-18.md`](work-orders/UCM-CHART-18.md) | 2026-08-25 | done | `5f34a2b` | **Tier 3** -- shared-core. `ui_reviewer` (what belongs in an exported image, and the MUI-legend counter-check) + `reviewer` (the ordering trap, the `transform` double-apply question); no `sec_reviewer`. **THE single most likely way to get this wrong:** `inlineComputedStyles` walks source and clone **in lockstep by index** (`:70-77`), so removing controls from the clone **before** it shifts every subsequent index and elements silently receive their neighbours' styles -- an export that looks plausible and is wrong everywhere after the first removal. Removal happens **after** the style walk, and the code comment must say so. **Counter-check that is not optional:** what disappears must be operation, not content -- a consumer whose legend items are `<button>`s (MUI's own legend can be interactive) would lose its legend, and the affected hram panels all pass `hideLegend` so they are **not** the test case; verify against a chart that keeps MUI's own legend, and if it vanishes that changes the approach. Also: `transform` may **double-apply** on SVG nodes that carry it as a presentation attribute the clone already keeps -- check `xLabels="angled"` before assuming it is inert. **Release: patch -> 3.3.1** -- this repairs behaviour 3.3.0 itself introduced rather than adding capability, the same reasoning `UCM-CHART-16` went out on, while `-15`/`-17` were minors because they changed what a consumer gets on purpose. Gate is **opening the files**, as for `UCM-CHART-17`: both defects were invisible to every test and visible immediately in an exported image. **Implementation:** `.claude/models.local.json` has no local override (defaults apply) -- `implementation.runtime` is `claude`/`sonnet`, implemented directly, no Codex dispatch. The lockstep-index ordering was respected from the start (`inlineComputedStyles` before `stripInteractiveControls`), `transform`/`transform-origin` added to the shared property list. **Verification (real Chrome, via the dev harness's module graph, no probe entry ever committed):** all four WO cases confirmed with hard evidence, not visual impression -- (1) a control in `children` (`IconButton` beside static text): captured the PNG path's actual intermediate SVG, confirmed no `<button` tag/text while the sibling and chart survive. (2) MUI's own legend (non-interactive, two series): fully intact, both labels present. (3) a rotated swatch: pixel-sampled the real rasterised PNG on a real `<canvas>` -- bounding-box corner reads background white, centre reads the swatch's own colour, i.e. a genuine diamond. (4) `xLabels="angled"`: the exported tick carries both the original `transform` XML attribute (kept by `cloneNode`) and the newly-inlined computed matrix; the matrix values mathematically match a SINGLE -45° rotation (`cos(-45°)=0.707107`), not a doubled one -- confirmed the inline `style` declaration wins over the presentation attribute rather than composing with it. 89 affected chart tests green (14 in `exportChart.test.js`), `tsc` clean. **Review: codex/gpt-5.6-luna (`reviewer` + `ui_reviewer`, concurrent) · 5 raised · 3 accepted · worst accepted: high (interactive-legend content loss)** (id not divisible by 5, no rotation configured). **Both reviewers independently converged on the SAME defect**, exactly the risk the WO's own Envelope named and required a live counter-check for: the initial fix REMOVED (not unwrapped) MUI's own interactive legend items (`onItemClick`/`toggleVisibilityOnClick` renders each item as `<button role="button" class="...MuiChartsLegend-series...">`), deleting the swatch+label along with the click handler -- the WO's own words, "if it vanishes, that is a finding that changes the approach, not a detail to paper over." FIXED: `MuiChartsLegend-series` matches are now UNWRAPPED (replaced with a plain `<span>` carrying the same class/style/children) instead of removed; re-verified live against an ACTUAL interactive legend (`slotProps={{legend:{toggleVisibilityOnClick:true}}}`, confirmed the live items render as real `<BUTTON>` tags) -- export contains zero `<button` tags, `MuiChartsLegend-series` and both series labels survive intact. `reviewer` additionally found: the interactive-control selector missed `a[href]`/`[role="link"]` (accepted, added -- also corrects the CHANGELOG's own "drill-down links" claim, which wasn't true until this fix); and the original ordering test's button was the LAST descendant, so a wrong call order wouldn't have shifted any node the test actually asserted on -- content-presence checks can't observe a style misattribution, only a wrong STYLE VALUE can (accepted, rewrote with a distinctively-styled trailing sibling, confirmed by temporarily reverting the call order that the new assertion genuinely fails). Two findings rejected as decoration/informational only (transform double-apply already reasoned through correctly by both reviewers; a jsdom-literal vs. browser-matrix distinction in the unit test, already covered by the separate real-browser verification track). |
31
32
  | UCM-CHART-17 | The two export buttons make two different promises; make them keep them | **Export SVG** yields the chart as scalable, correctly styled vector art; **Export PNG** yields what the user is looking at -- legend, size key and footnotes included. **Defect, from source:** `exportChart.js:7-11` clones the first `<svg>` and serialises it raw, with **no styles carried**. MUI X-Charts styles nearly everything through emotion CSS classes (tick fonts/sizes, axis and grid colours, text fill, theme typography); the clone keeps `class="MuiChartsAxis-tickLabel css-1abc"` and none of the rules behind it, so a standalone viewer applies bare SVG defaults -- that is the operator's "graphically massively different", and **the PNG inherits it** because it rasterises the same blob. **Second cause, and it is ours:** `findSvg` takes the *first* `<svg>`, i.e. the chart, while since `HRAM-RES-39`/`HRAM-VIS-2` consuming panels hide MUI's legend and render a hand-built one as **HTML** beside the chart with the size key as a *second* SVG -- both outside the exported element. **Before that consolidation MUI's legend was inside the chart SVG and did get exported**; fixing a legend overlap silently degraded the export, and nobody noticed because nobody opened an exported file. Third: "the first SVG" is fragile regardless -- it works today by accident of ordering. **Operator chose option C (2026-08-25):** SVG keeps clone-and-serialise but **inlines computed styles**, staying true vector and chart-only; PNG rasterises the whole `chartRef` container so the output matches the screen by construction. Full order [`work-orders/UCM-CHART-17.md`](work-orders/UCM-CHART-17.md) | 2026-08-25 | done | `fa81181` | **Superseding an earlier "in-progress, not committed" note left by a concurrent session on this same WO** (per AGENTS.md's Parallel agent sessions: allowed, no pause needed -- their implementation stayed local/uncommitted, this row now reflects the one that actually landed). **Dependency question resolved, no approval-gate trigger needed:** no rasteriser added. Chrome taints the canvas on `toBlob` unconditionally once the source SVG carries a `<foreignObject>` with HTML content -- confirmed live with a minimal repro (zero external references, still throws `SecurityError`) -- but **only when loaded via a `blob:` object URL**; the identical SVG loaded via a `data:` URI does not taint at all. That swap (`rasterize()` in `exportChart.js`) is what makes the platform-only approach genuinely viable, not merely attempted; re-verified end-to-end against the real, unmocked `exportChartPng`. Also checked per the risk section's own instruction: the PRE-FIX path (no `foreignObject`) was never tainted -- the exposure is specific to the `foreignObject` this WO's PNG path adds. **Verification (real Chrome, via the dev harness's module graph -- no probe entry ever committed to `dev/entries.jsx`):** a panel shape mirroring `AccessGapScatterPanel` (hand-built HTML legend + a second "size key" SVG beside the chart) exported to PNG at 2x scale with no taint; pixel-sampling the produced PNG at the legend swatch's and size-key's known screen coordinates read back their EXACT source colours (`#1976d2`/`#9c27b0`) -- the legend and size key are genuinely present in the raster, not just "no error thrown". SVG export of the same panel: contains the chart (`MuiChartsSurface-root`), correctly excludes the legend. A plain no-legend panel shape also verified clean on both paths. 192 affected chart tests green, `tsc` clean. **Review: codex/gpt-5.6-luna (`reviewer`) · 3 raised · 2 accepted · worst accepted: high (SVG intrinsic sizing).** (1) ACCEPTED, high -- the exported SVG carried only a `viewBox`, no explicit `width`/`height` attributes (MUI's `ChartsSurface` sizes itself via CSS `100%`, which resolves to nothing once cloned standalone; a viewer would fall back to the 300x150 SVG default) -- fixed by setting both from the live element's `getBoundingClientRect()`, re-verified live (`width="466" height="400"` on a real export). (2) REJECTED, factually incorrect -- claimed jsdom lacks `URL.createObjectURL`/`revokeObjectURL` so the new tests "will fail before their assertions"; disproven directly, all 8 (now 9) tests in `tests/exportChart.test.js` pass, and jsdom 29.1.1 implements both natively (verified). (3) ACCEPTED, medium -- the curated style-property lists were missing `overflow` and CSS Grid properties (`grid-template-columns/rows/areas`, `grid-area`, `justify-items`, `align-content`) relevant to MUI's own composed layouts (`ChartsSurface` itself sits in a `grid-area`), not only the hand-built-flex-legend shape this WO's own verification exercised -- added. **`ui_reviewer`: codex/gpt-5.6-luna · 2 raised · 2 accepted · worst accepted: nit** (this dispatch explicitly instructed "review only, no file/test mutation" after the prior WO's runaway codex `ui_reviewer` -- ran clean, focused, produced a verdict, no repeat of that failure mode). `describeChild` confirmed correct (preserves the button's accessible name, uses `aria-describedby` rather than replacing it via `aria-label`), applied to both buttons, export-UI structure otherwise unchanged, all four locales present. Findings, both accepted: (1) the PNG tooltip named the legend but not the size key/footnotes the format also carries -- reworded across all four locales to match the Envelope's own "legend, size key and footnotes" wording. (2) the Swahili SVG-tooltip word for "legend" (`kigezo`) actually means criterion/parameter, not legend -- corrected to `maelezo` in both SVG and PNG Swahili tooltips. Publishes automatically via `publish.yml` on this push (version-increase gate, `3.3.0 > 3.2.1`). Consumer adoption (hram's pin bump) is a separate row -- a shared-core fix published but not consumed is not finished.
32
33
  | UCM-CHART-16 | The x-axis band starves MUI's tick-fit check, and two consumers have patched around it | A chart with an axis title **and** horizontal tick labels must render its tick labels without a consumer hand-setting `xAxis[].height`. **Defect:** on the horizontal path `resolveXAxisGeometry` reserves one combined band from `TICK_BAND_BASE_PX` + `AXIS_TITLE_BAND_PX`; once a title is also taken from that budget, MUI's own fit check (`shortenLabels` against `tickLabelsMaxHeight`) is left **just under one line of 12 px text** and blanks **every** label regardless of content. Distinctive and easy to misread: correctly positioned tick marks, zero non-empty label texts -- looks like a data or formatter problem and is neither. **Evidence: two consumers, same workaround, same magic number**, independently, in two different WOs -- hram `StructuralReachabilityPanel.jsx:386` (`HRAM-RES-32`) and `AccessGapScatterPanel.jsx:212` (`HRAM-RES-39`), both `height: 56`. RES-32's own comment already diagnosed it and called it *"a pre-existing, latent shared-core near-miss"*, then patched locally because a shared-core fix was outside that WO; RES-39 read the MUI source, reached the same cause and the same 56, and patched locally again. **The third titled-horizontal-axis chart will hit it too**, and the package is meanwhile violating its own stated Rule 1 (*"nothing outside the resolver does chart arithmetic"*) in two places. Fix: correct the reservation, and **derive** it from the known tick font size and title band rather than adding a second magic number that will be wrong at a different font size. Full order [`work-orders/UCM-CHART-16.md`](work-orders/UCM-CHART-16.md) | 2026-08-25 | done | `9830266` | **Tier 3** -- shared-core. `reviewer` + `ui_reviewer` (the plot-area change across consumers); no `sec_reviewer`. **The risk that decides this WO: a mocked prop-assertion test cannot catch it.** The file already records the same trap for a neighbouring bug (*"a mocked prop-assertion test cannot catch this, it only reproduces on an actual MUI scale computation"*) -- a test asserting the computed band's number passes whatever the number is. **Test 1 must observe rendered label text**, or it is decoration. Also: raising the band changes every titled-horizontal-axis chart's plot area, on top of `UCM-CHART-15`'s 80 px shift -- and fixing it too generously wastes vertical space everywhere, so the near-miss margin is the budget, not a number rounded up to be safe. Release patch unless the plot-area change warrants minor; say which and why in the CHANGELOG. Consumer cleanup (removing hram's two workarounds) is `HRAM-CHT-6`, after this ships. **Third occurrence, 2026-08-25, and it changes the fix:** hram's `AccessibilityPanel` in `Urban/Peri-urban/Rural x Division` mode -- five band categories, five rendered bar groups, **no tick labels at all**, same signature. But that chart has **no `xAxisLabel`**, so the title is not competing for the band; what it has is `tickLabelStyle: { fontSize: 13 }`, one pixel above the 12 px the base band was sized against. **So the trigger is not "a title takes the room" -- it is that the band is a near-miss at all**, and anything consuming a little more pushes it over. A fixed `height: 56` patched into a third consumer would work at 13 px and fail at 14. That is exactly why scope item 2 requires the resolver to **derive** the requirement from the tick font size it already knows, instead of adopting the constant two consumers measured empirically at 12 px. Signature-matched, not yet instrumented -- confirm the mechanism on this third case, since it is the one that distinguishes a derived fix from a bigger constant. **Implementation:** `.claude/models.local.json` has no local override (defaults apply) -- `implementation.runtime` is `claude`/`sonnet`, implemented directly by the Orchestrator, no Codex dispatch. **The defect could not be confirmed from source reading alone** (jsdom does not implement real SVG text measurement, `getBBox`, so a rendered test would trivially pass regardless of correctness): reproduced and calibrated against the real, unmocked `BarChart` in this repo's own dev harness (Chrome, DM Sans, via `dev/entries.jsx`, reverted before commit) -- confirmed the defect reproduces exactly as described, confirmed it does NOT reproduce under MUI's default Roboto stack (explains why it was font-dependent and missed until a consumer used a taller font), then binary-searched the real minimal `xAxis[].height` at ten font-size/title combinations (11-18px) to derive `TICK_TEXT_HEIGHT_FACTOR=1.3`, `TICK_BAND_MUI_OVERHEAD_PX=9`, `TICK_BAND_TITLE_EXTRA_PX=2` -- matched every measured threshold within 1px, never under. Third occurrence (no title, `tickLabelStyle.fontSize:13`) confirmed via the same harness. 180 affected chart tests green (78 `chartDefaults.test.js` + 2 new rendered tests in `chartAxisTickBand.test.jsx`, which install a calibrated `SVGElement.prototype.getBBox` mock since jsdom's real implementation always measures 0x0 + 100 across `BarChart`/`LineChart`/`ScatterChart`/`TimeSeriesChart`/`ChartFrame`), `tsc -p tsconfig.build.json` clean. Both new resolver tests and both new rendered tests independently confirmed to fail against the pre-fix resolver (temporarily reverted, reran, restored) -- test 1 must observe rendered label text, not a computed number, per the WO's own risk section; both requirements met. Version bumped `3.2.0` -> `3.2.1` (patch, per the WO's own classification -- repairs existing behaviour, `UCM-CHART-15`'s heights untouched). **Review: codex/gpt-5.6-luna (`reviewer`) · 3 raised · 1 accepted · worst accepted: defect · chosen** (id not divisible by 5, no rotation configured). `reviewer` findings: (1) ACCEPTED -- the Rule-2 guardrail test only asserted `xTitleBand === 0`, which passes whether or not the title margin leaked into `xAxisBand` instead; fixed to assert the actual band/height values too. (2) REJECTED, out of scope -- a caller-supplied `xAxis[].tickSize` override isn't a documented/supported customization point of this package (grep confirms zero call sites, in this repo or its own tests/docs, ever set it); adding speculative handling for an unused knob is the "second magic number" pattern this WO exists to avoid. (3) REJECTED, out of scope -- a custom/multiline title font size overflowing the fixed `AXIS_TITLE_BAND_PX=20` reservation is a pre-existing `UCM-CHART-12`-era limitation, unchanged and unworsened by this WO. **`ui_reviewer`: codex/gpt-5.6-luna dispatch produced NO USABLE VERDICT** -- ran for an extended period repeatedly re-executing `vitest`/`git` against the live working tree (including applying then reverting a debug `console.log` in the new test file -- confirmed harmless via `git diff`/content check, but a review process should never write to the shared tree) and terminated with exit 0 but no findings/verdict text. Treated as unusable per "a review never lapses because a provider is down" -- fell back to `review_fallback` (`claude`/`sonnet`), spawned read-only, explicitly instructed not to run tests or mutate anything: **no findings**, confirmed the fix is byte-identical to the pre-fix band at the package's own default tick font (zero growth for unaffected charts), the CHANGELOG communicates the visual consequence plainly, and patch is the right classification. **Flagged for awareness, not fixed here:** the codex `ui_reviewer` runaway-without-verdict pattern is worth watching for future Tier-3 dispatches -- consider adding an explicit "review only, do not modify files or run mutating commands" line to review prompts. |
@@ -29,7 +29,7 @@ function escapeHtml(value) {
29
29
  .replace(/"/g, '&quot;')
30
30
  .replace(/'/g, '&#39;');
31
31
  }
32
- export function QrSignupManager({ enabled = false, expiryDays = DEFAULT_EXPIRY_DAYS, }) {
32
+ export function QrSignupManager({ enabled = false, expiryDays = DEFAULT_EXPIRY_DAYS, registrationContext = null, defaultMaxRedemptions = DEFAULT_MAX_REDEMPTIONS, }) {
33
33
  const { t } = useTranslation();
34
34
  const qrWrapperRef = useRef(null);
35
35
  const [busy, setBusy] = useState(false);
@@ -37,8 +37,17 @@ export function QrSignupManager({ enabled = false, expiryDays = DEFAULT_EXPIRY_D
37
37
  const [success, setSuccess] = useState('');
38
38
  const [result, setResult] = useState(null);
39
39
  const [copyState, setCopyState] = useState('idle');
40
- const [maxRedemptions, setMaxRedemptions] = useState(DEFAULT_MAX_REDEMPTIONS);
40
+ const [maxRedemptions, setMaxRedemptions] = useState(() => (clampMaxRedemptions(defaultMaxRedemptions)));
41
+ // Read via ref inside the auto-generate effect below, not as a reactive dependency --
42
+ // that effect itself calls setMaxRedemptions (on context change / disable), and depending
43
+ // on the state it just set re-triggers the effect a second time before the first fetch
44
+ // settles, firing a redundant createSignupQr call (and burning an extra token/redemption).
45
+ const maxRedemptionsRef = useRef(maxRedemptions);
46
+ maxRedemptionsRef.current = maxRedemptions;
41
47
  const hasGeneratedRef = useRef(false);
48
+ const registrationContextKey = useMemo(() => JSON.stringify(registrationContext || null), [registrationContext]);
49
+ const previousRegistrationContextKey = useRef(registrationContextKey);
50
+ const createPayload = (expiresMinutes, redemptions) => (Object.assign({ expires_minutes: expiresMinutes, max_redemptions: redemptions }, (registrationContext ? { registration_context: registrationContext } : {})));
42
51
  const formattedExpiry = useMemo(() => {
43
52
  if (!(result === null || result === void 0 ? void 0 : result.expires_at)) {
44
53
  return '';
@@ -67,10 +76,7 @@ export function QrSignupManager({ enabled = false, expiryDays = DEFAULT_EXPIRY_D
67
76
  setSuccess('');
68
77
  setCopyState('idle');
69
78
  try {
70
- const data = await createSignupQr({
71
- expires_minutes: nextDays * 24 * 60,
72
- max_redemptions: nextRedemptions,
73
- });
79
+ const data = await createSignupQr(Object.assign({}, createPayload(nextDays * 24 * 60, nextRedemptions)));
74
80
  setResult(data);
75
81
  hasGeneratedRef.current = true;
76
82
  setSuccess(t('Auth.SIGNUP_QR_CREATE_SUCCESS', 'New QR signup link created.'));
@@ -83,12 +89,19 @@ export function QrSignupManager({ enabled = false, expiryDays = DEFAULT_EXPIRY_D
83
89
  }
84
90
  };
85
91
  useEffect(() => {
92
+ const contextChanged = previousRegistrationContextKey.current !== registrationContextKey;
93
+ if (contextChanged) {
94
+ previousRegistrationContextKey.current = registrationContextKey;
95
+ hasGeneratedRef.current = false;
96
+ setResult(null);
97
+ setMaxRedemptions(clampMaxRedemptions(defaultMaxRedemptions));
98
+ }
86
99
  if (!enabled) {
87
100
  setResult(null);
88
101
  setError('');
89
102
  setSuccess('');
90
103
  setCopyState('idle');
91
- setMaxRedemptions(DEFAULT_MAX_REDEMPTIONS);
104
+ setMaxRedemptions(clampMaxRedemptions(defaultMaxRedemptions));
92
105
  hasGeneratedRef.current = false;
93
106
  return;
94
107
  }
@@ -103,10 +116,7 @@ export function QrSignupManager({ enabled = false, expiryDays = DEFAULT_EXPIRY_D
103
116
  setCopyState('idle');
104
117
  try {
105
118
  const days = clampExpiryDays(expiryDays);
106
- const data = await createSignupQr({
107
- expires_minutes: days * 24 * 60,
108
- max_redemptions: clampMaxRedemptions(maxRedemptions),
109
- });
119
+ const data = await createSignupQr(Object.assign({}, createPayload(days * 24 * 60, clampMaxRedemptions(contextChanged ? defaultMaxRedemptions : maxRedemptionsRef.current))));
110
120
  if (!active)
111
121
  return;
112
122
  setResult(data);
@@ -128,7 +138,13 @@ export function QrSignupManager({ enabled = false, expiryDays = DEFAULT_EXPIRY_D
128
138
  return () => {
129
139
  active = false;
130
140
  };
131
- }, [enabled, expiryDays, t]);
141
+ }, [
142
+ defaultMaxRedemptions,
143
+ enabled,
144
+ expiryDays,
145
+ registrationContextKey,
146
+ t,
147
+ ]);
132
148
  const handleCopyLink = async () => {
133
149
  var _a;
134
150
  const signupUrl = result === null || result === void 0 ? void 0 : result.signup_url;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@micha.bigler/ui-core-micha",
3
- "version": "3.3.1",
3
+ "version": "3.4.0",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.js",
6
6
  "sideEffects": [
@@ -44,6 +44,8 @@ function escapeHtml(value) {
44
44
  export function QrSignupManager({
45
45
  enabled = false,
46
46
  expiryDays = DEFAULT_EXPIRY_DAYS,
47
+ registrationContext = null,
48
+ defaultMaxRedemptions = DEFAULT_MAX_REDEMPTIONS,
47
49
  }) {
48
50
  const { t } = useTranslation();
49
51
  const qrWrapperRef = useRef(null);
@@ -52,8 +54,27 @@ export function QrSignupManager({
52
54
  const [success, setSuccess] = useState('');
53
55
  const [result, setResult] = useState(null);
54
56
  const [copyState, setCopyState] = useState('idle');
55
- const [maxRedemptions, setMaxRedemptions] = useState(DEFAULT_MAX_REDEMPTIONS);
57
+ const [maxRedemptions, setMaxRedemptions] = useState(() => (
58
+ clampMaxRedemptions(defaultMaxRedemptions)
59
+ ));
60
+ // Read via ref inside the auto-generate effect below, not as a reactive dependency --
61
+ // that effect itself calls setMaxRedemptions (on context change / disable), and depending
62
+ // on the state it just set re-triggers the effect a second time before the first fetch
63
+ // settles, firing a redundant createSignupQr call (and burning an extra token/redemption).
64
+ const maxRedemptionsRef = useRef(maxRedemptions);
65
+ maxRedemptionsRef.current = maxRedemptions;
56
66
  const hasGeneratedRef = useRef(false);
67
+ const registrationContextKey = useMemo(
68
+ () => JSON.stringify(registrationContext || null),
69
+ [registrationContext],
70
+ );
71
+ const previousRegistrationContextKey = useRef(registrationContextKey);
72
+
73
+ const createPayload = (expiresMinutes, redemptions) => ({
74
+ expires_minutes: expiresMinutes,
75
+ max_redemptions: redemptions,
76
+ ...(registrationContext ? { registration_context: registrationContext } : {}),
77
+ });
57
78
 
58
79
  const formattedExpiry = useMemo(() => {
59
80
  if (!result?.expires_at) {
@@ -85,8 +106,7 @@ export function QrSignupManager({
85
106
  setCopyState('idle');
86
107
  try {
87
108
  const data = await createSignupQr({
88
- expires_minutes: nextDays * 24 * 60,
89
- max_redemptions: nextRedemptions,
109
+ ...createPayload(nextDays * 24 * 60, nextRedemptions),
90
110
  });
91
111
  setResult(data);
92
112
  hasGeneratedRef.current = true;
@@ -99,12 +119,19 @@ export function QrSignupManager({
99
119
  };
100
120
 
101
121
  useEffect(() => {
122
+ const contextChanged = previousRegistrationContextKey.current !== registrationContextKey;
123
+ if (contextChanged) {
124
+ previousRegistrationContextKey.current = registrationContextKey;
125
+ hasGeneratedRef.current = false;
126
+ setResult(null);
127
+ setMaxRedemptions(clampMaxRedemptions(defaultMaxRedemptions));
128
+ }
102
129
  if (!enabled) {
103
130
  setResult(null);
104
131
  setError('');
105
132
  setSuccess('');
106
133
  setCopyState('idle');
107
- setMaxRedemptions(DEFAULT_MAX_REDEMPTIONS);
134
+ setMaxRedemptions(clampMaxRedemptions(defaultMaxRedemptions));
108
135
  hasGeneratedRef.current = false;
109
136
  return;
110
137
  }
@@ -120,8 +147,10 @@ export function QrSignupManager({
120
147
  try {
121
148
  const days = clampExpiryDays(expiryDays);
122
149
  const data = await createSignupQr({
123
- expires_minutes: days * 24 * 60,
124
- max_redemptions: clampMaxRedemptions(maxRedemptions),
150
+ ...createPayload(
151
+ days * 24 * 60,
152
+ clampMaxRedemptions(contextChanged ? defaultMaxRedemptions : maxRedemptionsRef.current),
153
+ ),
125
154
  });
126
155
  if (!active) return;
127
156
  setResult(data);
@@ -140,7 +169,13 @@ export function QrSignupManager({
140
169
  return () => {
141
170
  active = false;
142
171
  };
143
- }, [enabled, expiryDays, t]);
172
+ }, [
173
+ defaultMaxRedemptions,
174
+ enabled,
175
+ expiryDays,
176
+ registrationContextKey,
177
+ t,
178
+ ]);
144
179
 
145
180
  const handleCopyLink = async () => {
146
181
  const signupUrl = result?.signup_url;
@@ -0,0 +1,102 @@
1
+ // @vitest-environment jsdom
2
+
3
+ import React from 'react';
4
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
5
+ import { afterEach, describe, expect, it, vi } from 'vitest';
6
+
7
+ const mockState = vi.hoisted(() => ({
8
+ createSignupQr: vi.fn().mockResolvedValue({
9
+ signup_url: 'https://example.test/signup?rt=token',
10
+ expires_at: '2026-09-01T12:00:00Z',
11
+ }),
12
+ }));
13
+
14
+ vi.mock('../src/auth/authApi', () => ({
15
+ createSignupQr: mockState.createSignupQr,
16
+ }));
17
+
18
+ vi.mock('qrcode.react', () => ({
19
+ QRCodeSVG: () => null,
20
+ }));
21
+
22
+ // A stable `t` reference matters here: it's an effect dependency in QrSignupManager, and
23
+ // the real react-i18next memoizes it across renders. A fresh function per render (a common
24
+ // shorthand mock elsewhere in this repo) would make that effect re-fire on every unrelated
25
+ // re-render (e.g. the setBusy(true) inside it), which is a mock artifact this test file must
26
+ // not reintroduce given it asserts exact createSignupQr call counts.
27
+ const stableT = (_key, fallback) => fallback;
28
+ vi.mock('react-i18next', () => ({
29
+ useTranslation: () => ({ t: stableT }),
30
+ }));
31
+
32
+ import { QrSignupManager } from '../src/components/QrSignupManager';
33
+
34
+ describe('QrSignupManager registration context', () => {
35
+ afterEach(() => {
36
+ cleanup();
37
+ });
38
+
39
+ it('passes the department context and practical redemption default to the API', async () => {
40
+ mockState.createSignupQr.mockClear();
41
+
42
+ render(
43
+ <QrSignupManager
44
+ enabled
45
+ expiryDays={365}
46
+ registrationContext={{ group_ref: '42' }}
47
+ defaultMaxRedemptions={5000}
48
+ />,
49
+ );
50
+
51
+ await waitFor(() => expect(mockState.createSignupQr).toHaveBeenCalledWith({
52
+ expires_minutes: 365 * 24 * 60,
53
+ max_redemptions: 5000,
54
+ registration_context: { group_ref: '42' },
55
+ }));
56
+ });
57
+
58
+ it('behaves exactly as before when the new props are omitted (existing AccountPage-style call)', async () => {
59
+ mockState.createSignupQr.mockClear();
60
+
61
+ render(<QrSignupManager enabled expiryDays={90} />);
62
+
63
+ await waitFor(() => expect(mockState.createSignupQr).toHaveBeenCalledWith({
64
+ expires_minutes: 90 * 24 * 60,
65
+ max_redemptions: 1,
66
+ }));
67
+ expect(mockState.createSignupQr).toHaveBeenCalledTimes(1);
68
+ });
69
+
70
+ it('fires exactly one create call when the context changes after a custom redemption count was set', async () => {
71
+ mockState.createSignupQr.mockClear();
72
+
73
+ const { rerender } = render(
74
+ <QrSignupManager
75
+ enabled
76
+ expiryDays={90}
77
+ registrationContext={{ group_ref: '1' }}
78
+ defaultMaxRedemptions={5000}
79
+ />,
80
+ );
81
+ await waitFor(() => expect(mockState.createSignupQr).toHaveBeenCalledTimes(1));
82
+
83
+ fireEvent.change(screen.getByLabelText('Max redemptions'), { target: { value: '250' } });
84
+
85
+ mockState.createSignupQr.mockClear();
86
+ rerender(
87
+ <QrSignupManager
88
+ enabled
89
+ expiryDays={90}
90
+ registrationContext={{ group_ref: '2' }}
91
+ defaultMaxRedemptions={5000}
92
+ />,
93
+ );
94
+
95
+ await waitFor(() => expect(mockState.createSignupQr).toHaveBeenCalledWith({
96
+ expires_minutes: 90 * 24 * 60,
97
+ max_redemptions: 5000,
98
+ registration_context: { group_ref: '2' },
99
+ }));
100
+ expect(mockState.createSignupQr).toHaveBeenCalledTimes(1);
101
+ });
102
+ });