Author SHA1 Message Date
renovate Bot d152035f04 chore(deps): update angular-cli monorepo to v22.2.7
renovate/stability-days Updates have met minimum release age requirement
CI / policy (pull_request) Successful in 22s
CI / validate (pull_request) Successful in 41s
CI / build (pull_request) Successful in 37s
CI / benchmark (pull_request) Successful in 1m6s
CI / security (pull_request) Successful in 1m0s
CI / test (pull_request) Successful in 2m52s
CI / images (pull_request) Successful in 55s
CI / required (pull_request) Successful in 2s
CI / policy (push) Successful in 13s
CI / validate (push) Successful in 32s
CI / build (push) Successful in 22s
CI / benchmark (push) Successful in 57s
CI / security (push) Successful in 55s
CI / test (push) Successful in 4m1s
CI / images (push) Successful in 1m16s
CI / required (push) Successful in 5s
2026-11-16 06:03:22 +00:00
nessarandClaude Opus 5.5 995866fe5e docs(adr): share rule sets through the URL fragment
CI / policy (pull_request) Successful in 8s
CI / validate (pull_request) Successful in 30s
CI / build (pull_request) Successful in 21s
CI / benchmark (pull_request) Successful in 1m31s
CI / security (pull_request) Successful in 1m1s
CI / test (pull_request) Successful in 2m48s
CI / images (pull_request) Successful in 52s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 14s
CI / validate (push) Successful in 31s
CI / build (push) Successful in 22s
CI / security (push) Successful in 58s
CI / benchmark (push) Successful in 1m29s
CI / test (push) Successful in 2m39s
CI / images (push) Successful in 1m17s
CI / required (push) Successful in 1s
Record ADR 0014 and the Rule set glossary term for issue #363: a link
carries the whole ordered rule set in its own versioned envelope,
validated all or nothing, and replaces the recipient's rules after
confirmation without touching balances, declared days or the horizon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He39ydEEMnJJQHagHvB2
2026-11-15 21:21:27 +01:00
nessarandClaude Opus 5.5 a809c3bff5 fix(rules): apply the review of rule-set sharing
CI / policy (pull_request) Successful in 22s
CI / validate (pull_request) Successful in 28s
CI / build (pull_request) Successful in 24s
CI / security (pull_request) Successful in 1m4s
CI / benchmark (pull_request) Successful in 1m33s
CI / test (pull_request) Successful in 2m42s
CI / images (pull_request) Successful in 1m18s
CI / required (pull_request) Successful in 2s
CI / policy (push) Successful in 18s
CI / validate (push) Successful in 34s
CI / build (push) Successful in 23s
CI / benchmark (push) Successful in 1m30s
CI / security (push) Successful in 1m16s
CI / test (push) Successful in 2m59s
CI / images (push) Successful in 52s
CI / required (push) Successful in 1s
- Keep the planner core unchanged apart from exporting its rule checks:
  the link module checks a disabled rule by passing it as enabled.
- Require an earned leave type on every shared IF_THEN rule, as the rule
  type does, so an imported rule never lacks one.
- Cancel a link still being decoded when the address changes to one
  without a link.
- Restart the two seconds of the copy label on a second copy, and clear
  the timer when the panel goes away.
- Name the import statement's days as the rest of the UI now does:
  already booked days.

Refs #364, #365, #368.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He39ydEEMnJJQHagHvB2
2026-11-15 20:29:21 +01:00
nessarandClaude Fable 5.2 753c8fc234 feat(rules): share my rules from the rules panel
The rules panel offers "Share my rules" next to the add-rule buttons. The
share link is recomputed whenever the rule set changes and the button stays
disabled until it is ready, so the share sheet and the clipboard are reached
inside the click, without awaiting the compression.

With a share sheet the link is shared with the share title; dismissing the
sheet does nothing and any other share error copies the link. Without one
the link is copied and the button reads "Link copied" or "Copy failed" for
about two seconds. A rule that cannot travel in a link is named in an alert
under the button, which leaves once the rule set can be shared again.

Refs #368

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He39ydEEMnJJQHagHvB2
2026-11-15 20:23:32 +01:00
nessarandClaude Fable 5.2 ac587aa5d0 feat(rules): import a shared rule set after confirmation
A rules fragment on the planner page, at startup or on a later
hashchange, is decoded with the link module and offered in a dialog
that lists the incoming rules in order as plain text and states how
many current rules they replace. Replace my rules replaces the whole
rule set through RuleService and saves it, also when the saved rules
were unreadable at startup, so that later edits are saved too. An
invalid link is reported in the same dialog with Close. The fragment
is then removed from the address with history.replaceState, so a
reload does not ask again. The benchmark route ignores the fragment.

Refs #365

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He39ydEEMnJJQHagHvB2
2026-11-15 20:23:32 +01:00
nessarandClaude Fable 5.2 c20f0eaad3 feat(rules): encode and validate shared rule sets in a versioned link
Add the link module of rule-set sharing (#364, parent #363, ADR 0014), with
no UI yet. encodeRuleSetLink turns the rules RuleService exposes into the app
root plus a rules fragment parameter, or names the first rule that cannot be
shared. decodeRuleSetLink turns the fragment value back into a rule set ready
for RuleService, with TIME_WINDOW boundaries as local-midnight dates, or
returns null.

The link carries its own { version: 1, rules } envelope, compressed with raw
deflate and encoded in base64url. Validation is all or nothing on the wire
form: canonical values, known fields only, at most 100 rules and 64 KB
inflated, then the planner core's rule checks for every rule, disabled ones
included. Inflation is fed in small slices so it stops soon after the limit.

The core exports normalizeRules with its skip of disabled rules made
optional; the default behavior and the invalid-input reasons are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He39ydEEMnJJQHagHvB2
2026-11-15 20:23:19 +01:00
nessarandClaude Fable 5.2 97e25aa8b7 fix(i18n): reword unclear labels and rename the supplied rules
CI / policy (pull_request) Successful in 17s
CI / validate (pull_request) Successful in 34s
CI / build (pull_request) Successful in 21s
CI / benchmark (pull_request) Successful in 1m32s
CI / security (pull_request) Successful in 1m1s
CI / test (pull_request) Successful in 2m37s
CI / images (pull_request) Successful in 1m17s
CI / required (pull_request) Successful in 2s
CI / policy (push) Successful in 22s
CI / validate (push) Successful in 36s
CI / build (push) Successful in 27s
CI / benchmark (push) Successful in 1m37s
CI / security (push) Successful in 1m3s
CI / test (push) Successful in 3m4s
CI / images (push) Successful in 1m17s
CI / required (push) Successful in 2s
Review of every French label: sentences that said nothing or repeated a
heading are rewritten or removed, one word is kept per idea (période de
repos, période de travail, planning, le calcul, poser), the optimization
rule editor loses its jargon, and counted labels agree in number.
English, German and Spanish follow the French.

The six supplied optimization rules get names that say what they do. A
saved preset still under its first name takes the new one; a name the
person chose is kept.

Eight unused or redundant keys are removed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3AJHe4Ey5nTxHMdPcd
2026-11-15 16:35:09 +01:00
renovate Bot c73dac1dab chore(deps): update oven/bun docker tag to v1.4.4
renovate/stability-days Updates have met minimum release age requirement
CI / policy (pull_request) Successful in 14s
CI / validate (pull_request) Successful in 27s
CI / build (pull_request) Successful in 25s
CI / benchmark (pull_request) Successful in 1m8s
CI / security (pull_request) Successful in 1m5s
CI / test (pull_request) Successful in 3m47s
CI / images (pull_request) Successful in 55s
CI / required (pull_request) Successful in 4s
CI / policy (push) Successful in 11s
CI / validate (push) Successful in 28s
CI / build (push) Successful in 25s
CI / benchmark (push) Successful in 1m1s
CI / security (push) Successful in 54s
CI / test (push) Successful in 3m47s
CI / images (push) Successful in 1m17s
CI / required (push) Successful in 2s
2026-11-15 06:04:00 +00:00
nessarandClaude Fable 5.2 f63dfbd9a6 feat(stats): show the figures that inform a decision, with honest labels (#362)
CI / policy (pull_request) Successful in 15s
CI / validate (pull_request) Successful in 34s
CI / build (pull_request) Successful in 24s
CI / benchmark (pull_request) Successful in 1m10s
CI / security (pull_request) Successful in 56s
CI / test (pull_request) Successful in 3m50s
CI / images (pull_request) Successful in 1m19s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 16s
CI / validate (push) Successful in 38s
CI / build (push) Successful in 25s
CI / benchmark (push) Successful in 1m32s
CI / security (push) Successful in 58s
CI / test (push) Successful in 2m58s
CI / images (push) Successful in 1m21s
CI / required (push) Successful in 2s
The summary tiles and the statistics dialog now show leave days placed out
of those the plan could use, unplaced and lost days, total days off with
the weekends and public holidays as a detail, the number of time-off
periods and the longest, the longest stretch without leave, and bridged
public holidays out of the weekday holidays. Units sit next to the number
instead of in the label, and a tile and the dialog share one label.

The two averages are no longer displayed. Earned leave appears only when a
rule earns some, and names a single rule once. Weeks with one workday,
delivered by #69 on main only, are brought back as a dated warning.

Figures are derived in one tested helper; the planning engine is unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 16:40:07 +01:00
nessarandClaude Opus 5.5 57521cc28b test(date-comparison): wait for the dialog's initial focus before the retry focus check
CI / policy (pull_request) Successful in 20s
CI / validate (pull_request) Successful in 34s
CI / build (pull_request) Successful in 23s
CI / benchmark (pull_request) Successful in 1m30s
CI / security (pull_request) Successful in 1m0s
CI / test (pull_request) Successful in 2m53s
CI / images (pull_request) Successful in 1m14s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 8s
CI / build (push) Successful in 35s
CI / validate (push) Successful in 42s
CI / benchmark (push) Successful in 1m42s
CI / security (push) Successful in 1m38s
CI / test (push) Successful in 3m25s
CI / images (push) Successful in 1m15s
CI / required (push) Successful in 1s
The retry test recorded document.activeElement right after clicking Retry
and expected the arriving result not to move focus. MatDialog defaults to
delayFocusTrap, so autoFocus 'first-heading' moves focus to the title only
after the 150 ms opening animation timer and the next render. The test
usually finished just before that timer fired, so it compared body with
body. Under load the timer fired while job(2) was being polled, and the
final detectChanges ran the pending afterNextRender. Focus then moved from
body to #counterfactual-title and the assertion failed, even though the
result had not moved focus.

Wait for the title to receive focus, as the first test does, before taking
the snapshot. The assertion now checks that the result leaves the dialog's
settled focus on the title.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 16:07:24 +01:00
nessarandClaude Fable 5.2 556fa3fe37 docs(adr): renumber the empty leave balances decision to ADR 0013 (#356)
CI / policy (pull_request) Successful in 8s
CI / validate (pull_request) Successful in 38s
CI / build (pull_request) Successful in 38s
CI / benchmark (pull_request) Successful in 1m31s
CI / security (pull_request) Successful in 2m5s
CI / test (pull_request) Successful in 4m26s
CI / images (pull_request) Successful in 1m13s
CI / required (pull_request) Successful in 2s
develop already records ADR 0012 for obligation solutions.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 15:44:35 +01:00
nessarandClaude Fable 5.2 1e30812bb4 fix(rules): reword the default rule summaries as what the planner does (#357)
The maintainer could not understand several default rule summaries. Each
default optimization rule now states the action and its benefit, in the
four languages, and the automatic placement of an if-then rule reads
"au meilleur moment autour de ce jour".

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 15:44:21 +01:00
nessarandClaude Opus 5.5 aa3ef00341 feat(ui): switch between configuration and plan from a bottom bar on narrow viewports (#359)
Below 75rem only the chosen view is displayed, and a bar fixed to the
bottom of the viewport offers the configuration / plan switch and
Calculate. The page opens on the plan unless there is nothing to plan.
Calculate in the bar shows the plan and focuses its heading. Declared
non-working days are entered on the plan's calendar with the type and
erase choices in the bar. The skip link now shows the plan, and the
"go to your plan" link in the configuration is removed.

Calculate and the declaration controls become shared components, so
that the panel and the bar use the same markup and rules. The bar's
measured height reserves space at the end of the page and as scroll
padding, so that it never covers content or a focused element. The
two-column layout is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:44:21 +01:00
nessarandClaude Opus 5.5 bde65fc90e feat(rules): word the supplied optimization rules by their intent (#357)
The six supplied optimization compositions now say what the planner does
for the person ("Raccourcir la plus longue période travaillée d'affilée")
instead of naming the measure it moves. A rule matches when its elements,
measure, aggregation, direction and conditions equal a supplied rule; the
deficit threshold stays a placeholder, so a custom threshold keeps the
intent. Other compositions keep their generic sentence, and the
public-holiday-week phrases now explain their points per holiday.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:44:21 +01:00
nessarandClaude Sonnet 5.5 5148274d4d refactor(rules): edit planning rules in a dialog with one shared form (#360)
Adding or editing a planning rule now opens a Material dialog instead of
swapping the list item for an in-place form. One RuleDialog component serves
both, for every rule kind, so the duplicated add/edit template and the state
that only existed for in-place editing (editing class, cdkDragDisabled, the
hidden add buttons) are gone. The list only displays, enables, reorders and
deletes rules, and no longer changes layout while a rule is edited.

The form markup, validation and saved rule shape are moved unchanged; the
dialog returns the rule and the panel hands it to the rule service. The rule
editor tests now drive the real dialog.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 15:44:21 +01:00
nessarandClaude Sonnet 5.5 b165245aa0 feat(plan): list the time-off periods of the plan (#358)
Add a third disclosure above the calendar, closed by default, listing every
time-off period that contains a leave placement or a declared non-working day:
its date range in the active locale, the leave days per leave type, the declared
days and its duration in days off. Choosing a period scrolls its first leave or
declared day into view (honouring prefers-reduced-motion) and focuses it.

The three disclosures share one row on a wide screen; their summaries drop the
decorative icon when narrow so that the calendar stays above the fold.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 15:44:21 +01:00
nessarandClaude Opus 5.5 897bdefd25 feat(rules): describe planning rules in plain language (#357)
Optimization rules now read as a goal ("Réduire la plus longue séquence
de travail") built from per-measure phrases, element nouns and condition
qualifiers, so every valid composition gets a sentence. The technical
composition stays in the calculation details and the audit data.

The placement impact table drops the generic help repeated on every
optimization row. If-then and imposed-period summaries use real plurals,
leave-type phrases and the earned-leave wording of CONTEXT.md; the German
templates, which never filled their placeholders, are rewritten.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:44:21 +01:00
nessarandClaude Fable 5.2 0561a2f9d1 feat(ui): keep the configuration panel in view on wide screens (#355)
At the two-column breakpoint the panel is sticky and scrolls internally, and
the indicative wait with the Calculate button stays pinned at its bottom. The
panel is registered as a CDK scrollable so that dragging a rule still
auto-scrolls it. Single-column layouts are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 15:44:21 +01:00
nessarandClaude Fable 5.2 9ffd0953d4 feat(ui): show the calendar directly under the plan summary (#354)
Move the time-window, if-then and declared time-off period blocks into one
closed "applied rules detail" disclosure next to the placement explanation,
so the legend and the first row of months sit under the summary figures.
Put the status and the calculation date on the heading line.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 15:44:16 +01:00
nessarandClaude Fable 5.2 a4d7fa326f feat(ui): polish product name, statistics and calculation date (#353)
Show the product name VacOptimizer in the header, round plan statistics to one
decimal in the active locale, lay the statistics tiles out in two columns when
the dialog is wide enough, and attach the calculation date to the results
heading and status instead of a free paragraph.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 15:44:16 +01:00
nessarandClaude Opus 5.5 679a494fae feat(balances): start from an empty leave-balance list instead of random defaults (#356)
An absent or unreadable saved list now starts empty; no quantity is
generated. With no leave balance and no declared non-working day there
is nothing to plan: no calculation starts on load, Calculate is disabled
with the reason exposed through aria-describedby, and the results panel
shows the planning horizon's calendar with an invitation. Declared days
alone still calculate, so earned-leave chains keep working.

ADR 0012 records the decision and supersedes the random defaults of
ADR 0005. Tests now state their balances explicitly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:44:15 +01:00
nessarandClaude Fable 5.2 a130a4773a docs(benchmark): correct counts and wording after review, and record a costly obligation search left open
CI / policy (pull_request) Successful in 9s
CI / validate (pull_request) Successful in 43s
CI / test (pull_request) Successful in 3m34s
CI / benchmark (pull_request) Successful in 1m35s
CI / build (pull_request) Successful in 37s
CI / security (pull_request) Successful in 1m46s
CI / images (pull_request) Successful in 1m15s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 7s
CI / validate (push) Successful in 32s
CI / test (push) Successful in 3m40s
CI / benchmark (push) Successful in 1m34s
CI / build (push) Successful in 38s
CI / security (push) Successful in 1m55s
CI / images (push) Successful in 1m13s
CI / required (push) Successful in 1s
The benchmark has eight scenarios since the default-rules one. The #349 record
no longer says the stage ran for hours, which nothing measured, and separates
its rule-order survey from the named requests. The #350 record mentions the
seventh fixed request added later.

Comparing random long requests before the pull request found a request where
a Samedi Malin occurrence can fund an obligation: the obligations stage then
takes 10 of 11.8 seconds and 3.2 GB. It joins the runner's named requests and
the open points of the #347 record.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3Dca4aadeFoaGp2jB7
2026-11-12 18:25:14 +01:00
nessarandClaude Fable 5.2 642acc68ba docs(benchmark): point the records at the request runner and tabulate the frozen engine's rebuilds
Four rebuilds in a row had turned the origin of the frozen engine into one
long sentence; it is now a table, latest first. The #347, #348 and #349
records name the runner that holds their requests, and the README shows how
to use it. The #347 record no longer attributes to #349 the question of
whether loss prevention should leave room for a Samedi Malin pattern.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 11:40:01 +01:00
nessarandClaude Fable 5.2 75db74e10b test(planning): add a runner for the named requests of the #347 to #350 records
The records time and compare requests by name (347-3y, 348x-2027-1y-default,
349-samedi-first...), but the script that held those requests was not in the
repository. repro-requests.ts is an opt-in runner beside compare-engines.ts,
outside the functional suite and CI: it plans one named request on the current
or the frozen engine with a planning-work budget and prints the outcome, the
time per planning stage, the preference verdicts and the peak resident memory.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 11:40:01 +01:00
nessarandClaude Opus 5.5 13b81abd4d docs(benchmark): record the stages behind an IF_THEN rule and their exact speedup
Record what the Christmas and holiday-week stages did behind Samedi Malin,
with per-stage passes, candidates and kept improvements for the 2027 year
and the issue's request, the four exact changes and why they keep every
plan, the times before and after, the comparison made before rebuilding the
frozen engine, the new benchmark scenario, and the search changes tried and
not committed. Update the benchmark README for the frozen engine's origin,
the seventh fixed request, the check's run time and the default-rules
scenario; point the #321 finding at the record; describe the reuse and the
new prunes in the planning objectives contract; and note in the planning
duration model that the IF_THEN weight needs a refit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 11:15:25 +01:00
nessarandClaude Opus 5.5 9d64f43a68 test(benchmark): measure the default rules
No benchmark scenario enabled Samedi Malin or the Christmas window, so the
cost of the stages after an IF_THEN rule was invisible to the protocol and
its budget. The new scenario plans 2027, which has three Saturday public
holidays, with 25 CP and 12 RTT and the default rules. On the development
laptop it took 9.9 seconds before the exact search changes of #348 (2.8
times the calibration) and 2.9 seconds after (0.82 times); its multiplier
of 1.25 keeps the usual headroom, so the former cost would fail the gate.
The protocol takes about 9 seconds longer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 11:09:33 +01:00
nessarandClaude Opus 5.5 23b5ff1fc4 test(planning): rebuild the frozen engine from the exact IF_THEN search changes
Rebuild the frozen engine from 5aa3f39, which reaches the same plans with
less search behind an IF_THEN rule. Compared with the previous bundle
(built from 52059dc) before the rebuild, the 5,000 seeded requests and the
seven multi-year requests planned identically, as did the runner requests
of #347, #348, #349 and #350, but the change removes steps: 20 of the 500
cancelled runs of the differential check differed, ten only in their step
count and ten cancelled at another point. The type declaration still
matches the exports the check imports.

Built with: bun build src/app/services/leave-planner.core.ts --target=node
--external date-holidays, from a clean checkout of 5aa3f39.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:58:39 +01:00
nessarandClaude Opus 5.5 5aa3f39363 perf(planning): reach the same plans with less search behind an IF_THEN rule
With Samedi Malin among the default rules, the stages after it searched far
more than they needed to. Four exact changes keep every completed plan,
explanation and final state:

- The generic scan reads no answer from a move, swap, reassignment or
  removal: only a candidate that beats the best one so far counts. Such a
  candidate is now compared on the objectives that finalizing cannot change
  before it is finalized, and dropped when it provably cannot beat the best.
- The holiday-week and time-off-period bundles stop filling a bundle when no
  completion can be accepted: each later step only fills the remaining
  target dates, so every protected objective has an optimistic value, and a
  first difference that is worse rejects every completion. In 2027 the
  week of 1 November tried 14,000 to 21,000 allocations in each of four
  passes before one was accepted, starting with all those that broke the
  complete week of 14 July.
- A later stage reuses a completed generic scan of the same state even with
  an IF_THEN rule: once every balance is spent, the scan only accepts
  candidates that improve the whole vector, whatever the stage.
- The time-off period holding an earned leave entitlement's pattern is found
  by a binary search over the period ranges instead of a scan that built
  every period.

The frozen-engine check gains the one-year 2027 request with the default
rules. The changes remove steps, so a cancelled calculation can stop at
another point.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:57:55 +01:00
nessarandClaude Fable 5.2 72e290e8c3 docs(benchmark): record the obligation producer rule and its comparison
Record issue #347 in docs/benchmark/issue-347.md: the cause, the rule, the
times of the runner's requests before and after 52059dc, and the comparison
before the frozen-engine rebuild. The 5,000 seeded requests and the cancelled
comparisons are identical; the multi-year request with a TIME_WINDOW
obligation and three longer runner requests are worse on Samedi Malin, with
every later objective equal or better.

Name 52059dc as the frozen engine's origin and update the check's run time in
the benchmark README, point the #321 finding to the record, and state the
multi-year result and the measuring machines in ADR 0012.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 23:05:55 +01:00
nessarandClaude Fable 5.2 d2a20bde7b test(planning): rebuild the frozen engine from the obligation producer rule
Rebuilt from 52059dc with the documented command:

  bun build src/app/services/leave-planner.core.ts --target=node --external date-holidays --outfile src/app/services/frozen-engine/leave-planner.core.frozen.mjs

The search change lets a preference producer join the obligation search only
when it funds an obligation (issue #347, ADR 0012). Before the rebuild, the
5,000 seeded requests and the cancelled comparisons matched, and the
multi-year request of two years of 5 CP with a TIME_WINDOW obligation
differed; the comparison is recorded in docs/benchmark/issue-347.md.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 23:03:16 +01:00
nessarandClaude Fable 5.2 6c8ebbf1d7 docs(planning): record that an obligation solution holds only the preference patterns that fund an obligation
Record the maintainer's decision on issue #347 as ADR 0012 and state, in the
"Obligation solution" entry of CONTEXT.md, the one exception to "before any
preference rule applies": the pattern of an IF_THEN preference occurrence
whose earned leave can fund a later obligation date.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 22:58:52 +01:00
nessarandClaude Fable 5.2 52059dc8e0 perf(planning): let a preference producer join the obligation search only when it funds an obligation
An occurrence of an enabled preference IF_THEN rule that earns leave was an
optional requirement of the obligation search whenever an obligation needed
a placement, and it lifted the obligation solution limit. The search then
enumerated and ranked every obligation solution times every way to place or
skip each pattern: seconds to minutes for one obligation with Samedi Malin,
and minutes before reporting a planning conflict.

Such an occurrence now joins only when its earned leave can fund a compatible
obligation date after the occurrence, directly or through the pattern of
another joining occurrence. Without one, the obligation search is the one of
the request without that preference rule, including its solution limit.

This is a search change under ADR 0010: a pattern that funds no obligation is
no longer pre-placed ahead of higher-priority preferences, which changes plans
(issue #347).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 22:58:48 +01:00
nessarandClaude Fable 5.2 12c0b417be docs(benchmark): name the machine the #350 record was measured on
The record gave the desktop of the earlier records; its comparison and timings
ran on the development laptop, like those of the #349 record.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 22:58:14 +01:00
nessarandClaude Opus 5.5 b37785bbd9 docs(benchmark): record the loss prevention stall and its fix
Record why loss prevention behind another preference searched relocation
chains without end, the exact skip that replaces them, the before and after
times and memory of the requests of #349, and the comparison made before
rebuilding the frozen engine. Update the benchmark README, which said that
one year of 25 CP and 12 RTT with Samedi Malin ahead of loss prevention does
not finish and named ea2feaf as the frozen engine's origin, and note that a
change removing steps needs a rebuild for the cancelled comparisons. Point
the #321 finding at the record and describe the skip in the planning
objectives contract.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:50:14 +01:00
nessarandClaude Opus 5.5 b0bd729297 test(planning): rebuild the frozen engine from the loss prevention fix
Rebuild the frozen engine from c86829d, which lets loss prevention skip
relocation chains that cannot improve the protected prefix. Compared with
the previous bundle (built from ea2feaf) before the rebuild, the 5,000
seeded requests and the six multi-year requests planned identically, but
the change removes steps, so five of the 500 cancelled runs of the
differential check differed: two only in their step count, three cancelled
at a later point of the calculation. The bundle also takes up the changes
merged since ea2feaf; that comparison already included them. The type
declaration still matches the exports the check imports.

Built with: bun build src/app/services/leave-planner.core.ts --target=node
--external date-holidays, from a clean checkout of c86829d.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:43:45 +01:00
nessarandClaude Opus 5.5 c86829d295 fix(planning): let loss prevention finish behind another preference
Once every at-risk day is placed, the loss prevention stage still searched
relocation chains for each balance with days left, such as an earned leave
entitlement or a deferred balance. A chain only serves an addition that
strictly improves the protected prefix, and when loss prevention is not the
first preference nothing bounded that prefix, so the stage enumerated every
simple chain through the occupied dates. Its failure memo is keyed on the
visited dates and the whole plan, so it rarely matched and grew without
bound: Samedi Malin ahead of loss prevention over one year of 25 CP and
12 RTT ran past 100 seconds and several gigabytes.

The stage now skips the chains when no chain candidate can improve the
prefix. A chain keeps every occupied date and adds one free date, so an
objective already at its best value cannot improve, and an objective that
depends only on occupied dates can improve only if adding one free date
would improve it, which is probed directly. For calculations that run to
the end, this removes only candidates the stage would have rejected:
outcomes, explanations and final states stay identical. It removes steps,
so a calculation cancelled after a fixed number of steps can stop at
another point.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:42:13 +01:00
nessarandClaude Fable 5.2 2d912e8556 docs(benchmark): record the frozen-engine rebuild and the multi-year requests
Add the record of issue #350: the cause of the difference, the comparison over
the 5,000 seeded requests before the rebuild, the four placements that differed
on the request of the issue, the failure of the new test against the previous
bundle and the added run time. Update the benchmark README with the new origin
of the frozen engine and the fixed multi-year requests, and point the issue
#321 findings to the record.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 22:07:04 +01:00
nessarandClaude Fable 5.2 cca4c0ba2a test(planning): compare multi-year default-rule requests against the frozen engine
The seeded requests last at most ten weeks, so the differential check could
not see a plan that differs only on a long horizon, as the frozen engine did
on three years of 5 CP (#350). Add six fixed requests with the default rules,
with explicit calculation dates and Christmas window dates, compared like the
seeded ones: outcome, stable explanation, explanation error and final-state
snapshot strictly deep-equal, with the request printed as JSON on failure.

They cover the request of #350, a TIME_WINDOW obligation with Samedi Malin,
Samedi Malin ahead of loss prevention, a full year of 25 CP and 12 RTT, three
years from 2026 and a horizon starting on 1 September.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 22:03:41 +01:00
nessarandClaude Fable 5.2 eb316a76ae test(planning): rebuild the frozen engine from the weekday-holiday pattern fix
Rebuild the frozen engine from ea2feaf, which stops IF_THEN patterns at a
weekday public holiday and deliberately changed the plans of such patterns.
The bundle was last built for #302 from 8168137, so the differential check
compared the engine with one that predates that change. The comparison over
the 5,000 seeded requests found no difference before the rebuild. The
type declaration still matches the exports the check imports.

Built with: bun build src/app/services/leave-planner.core.ts --target=node
--external date-holidays, from a checkout of ea2feaf.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 22:02:23 +01:00
87 changed files with 9160 additions and 2954 deletions

No files matched your search

+5 -1
View File
@@ -109,7 +109,7 @@ An optimization rule that minimizes unplaced at-risk leave.
A planning rule that every valid plan must satisfy. Obligation rules are resolved jointly; their order only breaks ties between valid plans.
**Obligation solution**:
One way to satisfy every obligation rule jointly, before any preference rule applies. When there are several, the planner ranks them on their obligation-only plans by the planning objective order and its final tie-breaks, and completes the planning objective order from the best-ranked one only.
One way to satisfy every obligation rule jointly, before any preference rule applies. The one exception is the pattern of an IF_THEN preference occurrence whose earned leave can fund a later obligation date, directly or through another such pattern: the solution may hold it. A pattern that funds no obligation waits for its preference rule's turn in the rule priority. When there are several solutions, the planner ranks them on their obligation-only plans by the planning objective order and its final tie-breaks, and completes the planning objective order from the best-ranked one only.
**Preference rule**:
A planning rule that guides placement but may remain unsatisfied to preserve validity or satisfy higher-priority preferences.
@@ -129,6 +129,10 @@ A planning rule counting compatible leave placements and declared non-working da
**Rule priority**:
The user-defined lexicographic order shared by all active preference rules, including optimization rules. Each earlier preference is satisfied as far as possible before a later preference is considered.
**Rule set**:
The complete ordered list of one person's planning rules, including disabled and optimization rules; its order sets the rule priority. A shared rule set replaces the recipient's whole rule set and never carries leave balances, declared non-working days, or a planning horizon.
_Avoid_: configuration, settings, profile, template
**Rule satisfaction**:
The relationship in which a plan fulfils a planning rule. One compatible leave placement or declared non-working day may contribute to the satisfaction of multiple rules.
+2 -2
View File
@@ -1,5 +1,5 @@
# Stage 1: Build the Angular application and the Bun static server
FROM oven/bun:1.4.3-alpine@sha256:629e17411f1f129dbec3af78d5af9c9f2a937435c80349437206c6b0b7422373 AS builder
FROM oven/bun:1.4.4-alpine@sha256:4cf82f5686b196504fe119db3fcd9185b191f82ece82c40680e597228ec6070a AS builder
WORKDIR /app
@@ -12,7 +12,7 @@ COPY . .
RUN bun run build
# Stage 2: Production image
FROM oven/bun:1.4.3-alpine@sha256:629e17411f1f129dbec3af78d5af9c9f2a937435c80349437206c6b0b7422373 AS production
FROM oven/bun:1.4.4-alpine@sha256:4cf82f5686b196504fe119db3fcd9185b191f82ece82c40680e597228ec6070a AS production
WORKDIR /app
+6 -5
View File
@@ -186,13 +186,13 @@ The `/benchmark` route and planner core are lazy-loaded, so the normal applicati
The header opens one Settings dialog for planning dates, System / Light / Dark theme selection, English / French / German / Spanish language selection, and ISO week numbers. Changes apply and save on selection; closing the dialog retains them. System follows device appearance changes.
Saved balances, including an empty list, are restored before the initial calculation. When no readable saved list exists, CP, RTT, and Other start with random quantities from 10 through 20. These defaults remain unsaved until the first balance edit; subsequent edits save the entire list with identities, order, quantities, types, and calendar dates. Invalid saved balance data is cleared without removing unrelated settings or rules.
Saved balances, including an empty list, are restored before the initial calculation. When no readable saved list exists, the list starts empty and stays unsaved until the first balance edit; every balance edit saves the entire list with identities, order, quantities, types, and calendar dates. Invalid saved balance data is cleared without removing unrelated settings or rules. An empty list shows an invitation to add a balance. With no leave balance and no declared non-working day, nothing is calculated and Calculate is disabled; the results panel shows the planning horizon's calendar with its weekends and public holidays.
## Repository layout
```text
src/app/
├── benchmark/ # Lazy seven-scenario performance harness
├── benchmark/ # Lazy eight-scenario performance harness
├── components/ # Calendar, inputs, rules, and settings UI
├── services/
│ ├── leave-planner.service.ts # Canonical async planning boundary
@@ -249,7 +249,7 @@ Angular compiles with TypeScript 6. `bun check` is Bun's TypeScript 7 checker fo
Build or start the application, then open `/benchmark`. The isolated harness covers a representative year, typed obligations, chained earned entitlements, a deliberate conflict, a loaded year, and two- and three-year horizons with dated annual balances. It reports preparation time, planning latency, planning-work time, total wall time through explanation delivery, UI timer delay, available main-thread heap measurements, outcome, last completed stage, placement count, and determinism.
The release protocol, recorded desktop measurements, and hardware limitations are documented in [docs/benchmark/README.md](docs/benchmark/README.md). No reference-phone run or individual multi-year duration ceiling is established. CI runs the complete seven-scenario protocol with `bun test` and requires each scenario to stay within its budget relative to a frozen-engine calibration, with a 240-second hang guard. Bun measurements do not establish browser or reference-phone speedups.
The release protocol, recorded desktop measurements, and hardware limitations are documented in [docs/benchmark/README.md](docs/benchmark/README.md). No reference-phone run or individual multi-year duration ceiling is established. CI runs the complete eight-scenario protocol with `bun test` and requires each scenario to stay within its budget relative to a frozen-engine calibration, with a 240-second hang guard. Bun measurements do not establish browser or reference-phone speedups.
## Docker
@@ -276,7 +276,7 @@ The workflow runs on pushes to `develop` and `main`, `v*` tag pushes, PR opening
Jobs that run project commands install Bun 1.4.3 with `scripts/install-bun.sh` (a checksum-verified download, no npm) and run their steps with a `PATH` that holds Bun but no Node. The job containers keep Node only for Gitea's checkout and artifact actions, which are JavaScript actions the runner executes itself; see the [activation guide](docs/gitea-actions.md#runners-and-permissions).
Functional tests run with `bun test --isolate`; coverage is line-level only (Bun reports no branch or function data). The separate required benchmark job runs without coverage in a container limited to 3 GiB (JavaScriptCore has no heap-size flag, so this replaces the former 2 GiB Node heap cap) and keeps its 240-second hang guard, one warm-up and two measured repetitions of all seven scenarios. [#78](https://gitea.nessar.fr/nessar/vac-optimizer/issues/78) restored this gate after a complete local pass in 298.6 seconds; see [the measurements and hardware limits](docs/benchmark/issue-78.md). After [#302](docs/benchmark/issue-302.md) the local protocol takes about 41 seconds. Benchmark success is required for image publication and the aggregate `required` job. The lowered hang guard and tightened multipliers still need confirmation on the CI runners.
Functional tests run with `bun test --isolate`; coverage is line-level only (Bun reports no branch or function data). The separate required benchmark job runs without coverage in a container limited to 3 GiB (JavaScriptCore has no heap-size flag, so this replaces the former 2 GiB Node heap cap) and keeps its 240-second hang guard, one warm-up and two measured repetitions of all eight scenarios. [#78](https://gitea.nessar.fr/nessar/vac-optimizer/issues/78) restored this gate after a complete local pass in 298.6 seconds; see [the measurements and hardware limits](docs/benchmark/issue-78.md). After [#302](docs/benchmark/issue-302.md) the local protocol takes about 41 seconds. Benchmark success is required for image publication and the aggregate `required` job. The lowered hang guard and tightened multipliers still need confirmation on the CI runners.
The `required` job aggregates successful validation and expected image publication, accepting the image job's intentional skip for fork PRs and manual runs. Image jobs require successful validation and are limited to pushes to `develop`, `main` and release tags, and same-repository PRs. Registry credentials are confined to the publishing step.
@@ -322,6 +322,7 @@ Run `bun scripts/ci-policy.test.mjs` and `bun scripts/ci-image.test.mjs` locally
- [ADR 0002](docs/adr/0002-personal-client-side-planner-for-now.md) records the original client-side scope, superseded by ADR 0011.
- [ADR 0003](docs/adr/0003-constraint-first-lexicographic-planning.md) records the constraint-first planner architecture.
- [ADR 0004](docs/adr/0004-stable-explanation-original-trace-counterfactual.md) separates the outcome, stable explanation and displayed-placement hypothetical analysis.
- [ADR 0005](docs/adr/0005-saved-planning-inputs-before-random-defaults.md) records saved-input restoration and random fallback behavior.
- [ADR 0005](docs/adr/0005-saved-planning-inputs-before-random-defaults.md) records saved-input restoration; its random fallback is superseded by ADR 0013.
- [ADR 0006](docs/adr/0006-user-selected-horizons-and-cancellable-calculations.md) records fixed saved horizons, cancellation, duration estimation, and the removal of the automatic deadline.
- [ADR 0011](docs/adr/0011-server-side-planning-for-every-device.md) records server-side planning for every device with a local fallback.
- [ADR 0013](docs/adr/0013-empty-leave-balances-on-first-visit.md) starts from an empty leave-balance list instead of random balances.
+91 -101
View File
@@ -21,8 +21,8 @@
},
"devDependencies": {
"@analogjs/vite-plugin-angular": "^2.7.5",
"@angular/build": "22.2.3",
"@angular/cli": "22.2.3",
"@angular/build": "22.2.7",
"@angular/cli": "22.2.7",
"@angular/compiler-cli": "22.2.3",
"@eslint/js": "^10.0.1",
"@types/bun": "1.4.3",
@@ -47,17 +47,17 @@
"@analogjs/vite-plugin-angular": ["@analogjs/vite-plugin-angular@2.8.0", "", { "dependencies": { "magic-string": "^0.30.21", "obug": "^2.1.1", "oxc-parser": "^0.121.0", "tinyglobby": "^0.2.14" }, "peerDependencies": { "@angular-devkit/build-angular": "^17.0.0 || ^18.0.0 || ^19.0.0 || ^20.0.0 || ^21.0.0 || ^22.0.0", "@angular/build": "^18.0.0 || ^19.0.0 || ^20.0.0 || ^21.0.0 || ^22.0.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["@angular-devkit/build-angular", "@angular/build", "vite"] }, "sha512-4tDpjPERxmEBgIUxFwBVjbQOB0++1b1LoturpcXIvFuhcpBSVTJEKr+QYMAYMyeljEAUk07eo3zrIkzoyqlz8w=="],
"@angular-devkit/architect": ["@angular-devkit/architect@0.2202.3", "", { "dependencies": { "@angular-devkit/core": "22.2.3", "rxjs": "7.8.2" }, "bin": { "architect": "bin/cli.js" } }, "sha512-/605FxTg8Kt5fqNuIBVZMfuiNwIf+CTNsiYnHY85/7OTqCNkEwdkXKc3DiFM2KlR/AV2g64GkvHgHqxHzYh34g=="],
"@angular-devkit/architect": ["@angular-devkit/architect@0.2202.7", "", { "dependencies": { "@angular-devkit/core": "22.2.7", "rxjs": "7.8.2" }, "bin": { "architect": "bin/cli.js" } }, "sha512-l8apKEojW8WB5pqhK+BkO7+DZSCLNpvP+JBdBzDYagrtkKbtr1AKPuAE/2sVvlBE8SXyNCp3CX9gTtkk2q40mw=="],
"@angular-devkit/core": ["@angular-devkit/core@22.2.3", "", { "dependencies": { "ajv": "8.20.0", "ajv-formats": "3.0.1", "jsonc-parser": "3.3.1", "picomatch": "4.0.7", "rxjs": "7.8.2", "source-map": "0.8.0" }, "peerDependencies": { "chokidar": "^5.0.0" }, "optionalPeers": ["chokidar"] }, "sha512-bi1oBjJeg1XCgRrBYSuJikaJV4sO/mcnyFE/0a1H646yHhQpVYoU/M2Vh69Qv8h+YoMfC7RuSxT4LZHaubhhLw=="],
"@angular-devkit/core": ["@angular-devkit/core@22.2.7", "", { "dependencies": { "ajv": "8.20.0", "ajv-formats": "3.0.1", "jsonc-parser": "3.3.1", "picomatch": "4.0.7", "rxjs": "7.8.2", "source-map": "0.8.0" }, "peerDependencies": { "chokidar": "^5.0.0" }, "optionalPeers": ["chokidar"] }, "sha512-cchZAMsV4d76RDZBlWzPhYxM/Hb6bmq71oUngdrwehMbBbdQu3W9C2tGlvxuPxbRKru9ZlUa14YVXQ0+QnhFtw=="],
"@angular-devkit/schematics": ["@angular-devkit/schematics@22.2.3", "", { "dependencies": { "@angular-devkit/core": "22.2.3", "jsonc-parser": "3.3.1", "magic-string": "1.4.1", "ora": "9.4.1", "rxjs": "7.8.2" } }, "sha512-+XfBViIGqiFQK8KJXA6PgANX9tLuMO/x8GFjlzEmA4LIe9ikAtpGZw+Ezo547BIJQoJBIKCJYR0knE4BmbFeSQ=="],
"@angular-devkit/schematics": ["@angular-devkit/schematics@22.2.7", "", { "dependencies": { "@angular-devkit/core": "22.2.7", "jsonc-parser": "3.3.1", "magic-string": "1.4.1", "ora": "9.4.1", "rxjs": "7.8.2" } }, "sha512-a1h7xNqBLQVo1e5eCyOU3axSbA9AFU6nnSH5QhlNhggfMeZde+eBrueSt25xsewoxlKO8EvkVT3+knMUkDYiGQ=="],
"@angular/build": ["@angular/build@22.2.3", "", { "dependencies": { "@ampproject/remapping": "2.3.0", "@angular-devkit/architect": "0.2202.3", "@babel/core": "8.0.5", "@inquirer/confirm": "6.3.2", "@parcel/watcher": "2.6.0", "@vitejs/plugin-basic-ssl": "2.3.0", "beasties": "0.5.4", "browserslist": "^4.26.0", "chokidar": "5.0.0", "esbuild": "0.28.2", "https-proxy-agent": "9.1.0", "jsonc-parser": "3.3.1", "listr2": "11.1.0", "magic-string": "1.4.1", "mrmime": "2.0.1", "oxc-parser": "0.150.0", "parse5-html-rewriting-stream": "8.0.1", "picomatch": "4.0.7", "piscina": "5.3.2", "rolldown": "1.2.8", "sass": "1.104.1", "sass-embedded": "1.104.1", "semver": "7.8.5", "source-map-support": "0.5.21", "tinyglobby": "0.2.17", "vite": "8.3.0", "xxhash-wasm": "1.1.0" }, "optionalDependencies": { "lmdb": "3.5.6" }, "peerDependencies": { "@angular/compiler": "^22.0.0", "@angular/compiler-cli": "^22.0.0", "@angular/core": "^22.0.0", "@angular/localize": "^22.0.0", "@angular/platform-browser": "^22.0.0", "@angular/platform-server": "^22.0.0", "@angular/service-worker": "^22.0.0", "@angular/ssr": "^22.2.3", "istanbul-lib-instrument": "^6.0.0", "karma": "^6.4.0", "less": "^4.2.0", "ng-packagr": "^22.0.0", "postcss": "^8.4.0", "rollup": "^4.0.0", "tailwindcss": "^2.0.0 || ^3.0.0 || ^4.0.0", "tslib": "^2.3.0", "typescript": ">=6.0 <6.1", "vitest": "^4.0.8 || ^5.0.0" }, "optionalPeers": ["@angular/core", "@angular/localize", "@angular/platform-browser", "@angular/platform-server", "@angular/service-worker", "@angular/ssr", "istanbul-lib-instrument", "karma", "less", "ng-packagr", "postcss", "rollup", "tailwindcss", "vitest"] }, "sha512-EtNEuPBUCyIuzdXrQ/nINvgFzW8bUI5AkAZtJiSn7nsFOlvaygaKN0kENNTO3zRl3T9B4GDog+Ks5Nec3FBkhg=="],
"@angular/build": ["@angular/build@22.2.7", "", { "dependencies": { "@ampproject/remapping": "2.3.0", "@angular-devkit/architect": "0.2202.7", "@babel/core": "8.0.5", "@inquirer/confirm": "6.3.2", "@parcel/watcher": "2.6.0", "@vitejs/plugin-basic-ssl": "2.3.0", "beasties": "0.5.4", "browserslist": "^4.26.0", "chokidar": "5.0.0", "esbuild": "0.28.2", "https-proxy-agent": "9.1.0", "jsonc-parser": "3.3.1", "listr2": "11.1.0", "magic-string": "1.4.1", "mrmime": "2.0.1", "oxc-parser": "0.156.0", "parse5-html-rewriting-stream": "8.0.1", "picomatch": "4.0.7", "piscina": "5.3.2", "rolldown": "1.2.16", "sass": "1.104.1", "sass-embedded": "1.104.1", "semver": "7.8.5", "source-map-support": "0.5.21", "tinyglobby": "0.2.17", "vite": "8.3.5", "xxhash-wasm": "1.1.0" }, "optionalDependencies": { "@oxc-parser/binding-wasm32-wasi": "0.156.0", "lmdb": "3.5.6" }, "peerDependencies": { "@angular/compiler": "^22.0.0", "@angular/compiler-cli": "^22.0.0", "@angular/core": "^22.0.0", "@angular/localize": "^22.0.0", "@angular/platform-browser": "^22.0.0", "@angular/platform-server": "^22.0.0", "@angular/service-worker": "^22.0.0", "@angular/ssr": "^22.2.7", "istanbul-lib-instrument": "^6.0.0", "karma": "^6.4.0", "less": "^4.2.0", "ng-packagr": "^22.0.0", "postcss": "^8.4.0", "rollup": "^4.0.0", "tailwindcss": "^2.0.0 || ^3.0.0 || ^4.0.0", "tslib": "^2.3.0", "typescript": ">=6.0 <6.1", "vitest": "^4.0.8 || ^5.0.0" }, "optionalPeers": ["@angular/core", "@angular/localize", "@angular/platform-browser", "@angular/platform-server", "@angular/service-worker", "@angular/ssr", "istanbul-lib-instrument", "karma", "less", "ng-packagr", "postcss", "rollup", "tailwindcss", "vitest"] }, "sha512-tQGzQPHvPK2oG5CqAsOMayU49WliSLlFV001poDpClmZ5d7cBsPeUZZlsEv84aMkplFDfhxqj6Guqd38T9HRdQ=="],
"@angular/cdk": ["@angular/cdk@22.2.1", "", { "dependencies": { "parse5": "^8.0.0", "tslib": "^2.3.0" }, "peerDependencies": { "@angular/common": "^22.0.0 || ^23.0.0", "@angular/core": "^22.0.0 || ^23.0.0", "@angular/forms": "^22.0.0 || ^23.0.0", "@angular/platform-browser": "^22.0.0 || ^23.0.0", "rxjs": "^6.5.3 || ^7.4.0" } }, "sha512-0vjlqYBbLif1EwHhKz2r4thTDvtRI2CKi2js9TzPRD0n4VlFUnAXaaW47s5TCCObIoYun6Bo1zZ0uPgwb+qEMw=="],
"@angular/cli": ["@angular/cli@22.2.3", "", { "dependencies": { "@angular-devkit/architect": "0.2202.3", "@angular-devkit/core": "22.2.3", "@angular-devkit/schematics": "22.2.3", "@inquirer/prompts": "8.7.2", "@listr2/prompt-adapter-inquirer": "4.2.7", "@modelcontextprotocol/server": "2.3.1", "@schematics/angular": "22.2.3", "jsonc-parser": "3.3.1", "listr2": "11.1.0", "npm-package-arg": "14.0.0", "parse5-html-rewriting-stream": "8.0.1", "semver": "7.8.5", "yargs": "18.1.0", "zod": "4.6.6" }, "bin": { "ng": "bin/ng.js" } }, "sha512-ObTX0DxJ0/PMl4pkUKI+uWPr7UC7Je94KpHP8l1lr3exhundapgr7VvNsozprJb1hMlOMDab6+quTReSYvF85Q=="],
"@angular/cli": ["@angular/cli@22.2.7", "", { "dependencies": { "@angular-devkit/architect": "0.2202.7", "@angular-devkit/core": "22.2.7", "@angular-devkit/schematics": "22.2.7", "@inquirer/prompts": "8.7.2", "@listr2/prompt-adapter-inquirer": "4.2.7", "@modelcontextprotocol/server": "2.3.1", "@schematics/angular": "22.2.7", "jsonc-parser": "3.3.1", "listr2": "11.1.0", "npm-package-arg": "14.0.0", "parse5-html-rewriting-stream": "8.0.1", "semver": "7.8.5", "yargs": "18.1.0", "zod": "4.6.6" }, "bin": { "ng": "bin/ng.js" } }, "sha512-TtO2qiDJj3OjeqZ1V/SiDYkwBKDVk45PxDBxjNksw5sLe2H122RYjdcVPDteEGJjAJGwnP2qkQ5wa/6YRitNiA=="],
"@angular/common": ["@angular/common@22.2.3", "", { "dependencies": { "tslib": "^2.3.0" }, "peerDependencies": { "@angular/core": "22.2.3", "rxjs": "^6.5.3 || ^7.4.0" } }, "sha512-sRzcvxzurbkCDVFJMguNVgsHds3NvDj5qbZ44NHjH7J9MBk5oZYXHppdHVm8AolBhCXAWvMk0vx+NO8Bt4rS7A=="],
@@ -125,11 +125,11 @@
"@csstools/css-tokenizer": ["@csstools/css-tokenizer@4.0.2", "", {}, "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw=="],
"@emnapi/core": ["@emnapi/core@1.10.0", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" } }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="],
"@emnapi/core": ["@emnapi/core@2.0.0-alpha.6", "", { "dependencies": { "@emnapi/wasi-threads": "2.2.0", "tslib": "^2.4.0" } }, "sha512-MNVvMV7WtEJMgqaWJMvCyupK7Oi8sZctUIgPRZTsiS3cVvefk8DXPflOU3MSBddtj/rrYHygpYgpHDgwXnI3+w=="],
"@emnapi/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="],
"@emnapi/runtime": ["@emnapi/runtime@2.0.0-alpha.6", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-5ZR49ZsZ3cLvu5lkrVj6CMpHRgZjYz7XSlqK23GYYpyEqp749RVuIH0bEUKaGNghMh2pXRhIC3cnVrH28Y1j1Q=="],
"@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w=="],
"@emnapi/wasi-threads": ["@emnapi/wasi-threads@2.2.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw=="],
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="],
@@ -321,7 +321,7 @@
"@napi-rs/nice-win32-x64-msvc": ["@napi-rs/nice-win32-x64-msvc@1.1.1", "", { "os": "win32", "cpu": "x64" }, "sha512-vB+4G/jBQCAh0jelMTY3+kgFy00Hlx2f2/1zjMoH821IbplbWZOkLiTYXQkygNTzQJTq5cvwBDgn2ppHD+bglQ=="],
"@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.4", "", { "dependencies": { "@tybys/wasm-util": "^0.10.1" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow=="],
"@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.7", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" } }, "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ=="],
"@oxc-parser/binding-android-arm-eabi": ["@oxc-parser/binding-android-arm-eabi@0.121.0", "", { "os": "android", "cpu": "arm" }, "sha512-n07FQcySwOlzap424/PLMtOkbS7xOu8nsJduKL8P3COGHKgKoDYXwoAHCbChfgFpHnviehrLWIPX0lKGtbEk/A=="],
@@ -355,7 +355,7 @@
"@oxc-parser/binding-openharmony-arm64": ["@oxc-parser/binding-openharmony-arm64@0.121.0", "", { "os": "none", "cpu": "arm64" }, "sha512-R+4jrWOfF2OAPPhj3Eb3U5CaKNAH9/btMveMULIrcNW/hjfysFQlF8wE0GaVBr81dWz8JLgQlsxwctoL78JwXw=="],
"@oxc-parser/binding-wasm32-wasi": ["@oxc-parser/binding-wasm32-wasi@0.121.0", "", { "dependencies": { "@napi-rs/wasm-runtime": "^1.1.1" }, "cpu": "none" }, "sha512-5TFISkPTymKvsmIlKasPVTPuWxzCcrT8pM+p77+mtQbIZDd1UC8zww4CJcRI46kolmgrEX6QpKO8AvWMVZ+ifw=="],
"@oxc-parser/binding-wasm32-wasi": ["@oxc-parser/binding-wasm32-wasi@0.156.0", "", { "dependencies": { "@emnapi/core": "2.0.0-alpha.6", "@emnapi/runtime": "2.0.0-alpha.6", "@napi-rs/wasm-runtime": "~1.2.6" } }, "sha512-FWs20Zd4XCqpVwiTgKhyXWplIliulfwJMCI+POY2z1YF9IFr91qDLa7Jfqu0f1i95GFOy0GUGx8s6C4EtfFM3g=="],
"@oxc-parser/binding-win32-arm64-msvc": ["@oxc-parser/binding-win32-arm64-msvc@0.121.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-V0pxh4mql4XTt3aiEtRNUeBAUFOw5jzZNxPABLaOKAWrVzSr9+XUaB095lY7jqMf5t8vkfh8NManGB28zanYKw=="],
@@ -393,43 +393,43 @@
"@pkgr/core": ["@pkgr/core@0.3.6", "", {}, "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA=="],
"@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.8", "", { "os": "android", "cpu": "arm" }, "sha512-tN5aztYkKCte4i5SIrrz5yK/HMjEuCqCSCJa418jOV8tZ1cBY3YF2otxB1ktPxzsLA1BeTqwapK0bfjxNvHJVw=="],
"@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.16", "", { "os": "android", "cpu": "arm" }, "sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA=="],
"@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.8", "", { "os": "android", "cpu": "arm64" }, "sha512-dIYTWl9XprMUiQFoc55KUyk/oS8SKYH3zFl0LTR7RT0Xj4hgSVyuJcroH8JUu8RcpF8fTB6E0aOwCkZoYPcDSQ=="],
"@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.16", "", { "os": "android", "cpu": "arm64" }, "sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg=="],
"@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.8", "", { "os": "darwin", "cpu": "arm64" }, "sha512-PCSDQGXD2IyTEFrcgPyBM8jJuGmrbCMuoIOXdbEGVemruKACXoLQJrb+A45Z0L5t1RQkdfJprAYPkikbh7dzdA=="],
"@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.16", "", { "os": "darwin", "cpu": "arm64" }, "sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ=="],
"@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.2.8", "", { "os": "darwin", "cpu": "x64" }, "sha512-Uk7lRsGhPFHVX/sAUC6D5H9Ol30dFHd6iquokll2th3LpdJ3F5CzQB+7DHn0Ri2mG+U7k2zXiPHDrwZenXhwSA=="],
"@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.2.16", "", { "os": "darwin", "cpu": "x64" }, "sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ=="],
"@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.8", "", { "os": "freebsd", "cpu": "x64" }, "sha512-DjszaTEVogPqA5bYzsEeqDCQxbcp2fexQwKcRspYji2yzR68fCf+e4fx6kBSRDwX5/brZaHw/hWS9+A/+/w9sQ=="],
"@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.16", "", { "os": "freebsd", "cpu": "x64" }, "sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q=="],
"@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.8", "", { "os": "linux", "cpu": "arm" }, "sha512-zmwa7FTmdzB6aaEEuuls18H6Ap5JmJPSoPTuXixeJZV6tG40SyLkApQtz1g8ptZtiEKqj9OM0oNLPh1AgvE31Q=="],
"@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.16", "", { "os": "linux", "cpu": "arm" }, "sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA=="],
"@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.8", "", { "os": "linux", "cpu": "arm64" }, "sha512-KdYQDPHwJVnbFwdTGMgxsI9SqblBlz6STGM+w1We/d5B8OWWidYH0MwkU/uA1wM5fIpO2MkOVxXrNzzuZhw9ew=="],
"@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.16", "", { "os": "linux", "cpu": "arm64" }, "sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w=="],
"@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.8", "", { "os": "linux", "cpu": "arm64" }, "sha512-jFJTifHnNPY+yzOoNZQfSIysrVyXzEQPhPnOUjmD1bcQGHH6s7c8cViKWar8YplQImE5N9JRqMCLrM2CdxOrZA=="],
"@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.16", "", { "os": "linux", "cpu": "arm64" }, "sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg=="],
"@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.8", "", { "os": "linux", "cpu": "ppc64" }, "sha512-FhiOziBDWPBjbcmRzfLyIJnaP7AVMFXT7YCXPjXxj7wKU3vx24RjrCNN/zjvVa+N2vVoHJwCoUBvsrN/DG3zIA=="],
"@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.16", "", { "os": "linux", "cpu": "ppc64" }, "sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA=="],
"@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.2.8", "", { "os": "linux", "cpu": "s390x" }, "sha512-WnHfADMzOV2Y55wlx1hzzQnar/wDt/VdvWSD99r18Mz9ylNieIGOkRx3UV21h7m/eJvjySYJkO26VvGNFkwsIQ=="],
"@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.2.16", "", { "os": "linux", "cpu": "s390x" }, "sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg=="],
"@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.8", "", { "os": "linux", "cpu": "x64" }, "sha512-H9tRr5ibfXFVLxbPOseVewewFpl28zcEdjRDt2FTUZU7odxP0gEv1ki4/kGmcGOh78oRwZuuQllGLZ9zTJp84g=="],
"@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.16", "", { "os": "linux", "cpu": "x64" }, "sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w=="],
"@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.8", "", { "os": "linux", "cpu": "x64" }, "sha512-UefiqfM3D6IVNlZ8tSGs9+Ejjud2T+oxO0IHADU45Y+lyEjD2dVFyZHbkfX0LUb5Zugo/oIv1eCO/KVYhgYJYA=="],
"@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.16", "", { "os": "linux", "cpu": "x64" }, "sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA=="],
"@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.8", "", { "os": "none", "cpu": "arm64" }, "sha512-637Ke4kWSy6rp9cxQ9gMOXlxPgIw/c1beASV4M//3+9I4uwBVOOl74G+e3zyU3u19U7RkRl/HuewixZ/Z6+Rjg=="],
"@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.16", "", { "os": "none", "cpu": "arm64" }, "sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ=="],
"@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.2.8", "", { "os": "win32", "cpu": "arm64" }, "sha512-xWBkPOF1Q9k/Gv1nQXnVdLxKu74jXppuOM4Z3mnypVUJJJwLsMl7hNJGRAUJoG8A5MgOI1ACKM+wBFxSJzKy4A=="],
"@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.2.16", "", { "os": "win32", "cpu": "arm64" }, "sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw=="],
"@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.8", "", { "os": "win32", "cpu": "x64" }, "sha512-uz2ZvfgXbxqNwijjjbxrnvALwpyODDcgc1T1N8N3rf/DXKQmaFwmB4LX4yyjggpwN2obdQLb2rgirX5ffCWYng=="],
"@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.16", "", { "os": "win32", "cpu": "x64" }, "sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw=="],
"@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],
"@schematics/angular": ["@schematics/angular@22.2.3", "", { "dependencies": { "@angular-devkit/core": "22.2.3", "@angular-devkit/schematics": "22.2.3", "jsonc-parser": "3.3.1", "oxc-parser": "0.150.0", "typescript": "6.0.3" } }, "sha512-DY8wv/LtNf3YD/EEoFdER4ihMyw5yywuOQEKasm4d2uBJ5peGIWV3LXJXXqD7b4WVC8xS1eUAjingyWfI9reHw=="],
"@schematics/angular": ["@schematics/angular@22.2.7", "", { "dependencies": { "@angular-devkit/core": "22.2.7", "@angular-devkit/schematics": "22.2.7", "jsonc-parser": "3.3.1", "oxc-parser": "0.156.0", "typescript": "6.0.3" } }, "sha512-cdwLAc0m6mWZ3HA0VHqulUKItviExnENQwDQ01f9lQS9bTAWBEkg7Pgua+3BijMUEE5sf/kamqCdwaKPUn1uXQ=="],
"@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
"@tybys/wasm-util": ["@tybys/wasm-util@0.10.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg=="],
"@tybys/wasm-util": ["@tybys/wasm-util@0.10.4", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A=="],
"@types/bun": ["@types/bun@1.4.3", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="],
@@ -853,7 +853,7 @@
"restore-cursor": ["restore-cursor@5.1.0", "", { "dependencies": { "onetime": "^7.0.0", "signal-exit": "^4.1.0" } }, "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA=="],
"rolldown": ["rolldown@1.2.8", "", { "dependencies": { "@oxc-project/types": "=0.149.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.8", "@rolldown/binding-android-arm64": "1.2.8", "@rolldown/binding-darwin-arm64": "1.2.8", "@rolldown/binding-darwin-x64": "1.2.8", "@rolldown/binding-freebsd-x64": "1.2.8", "@rolldown/binding-linux-arm-gnueabihf": "1.2.8", "@rolldown/binding-linux-arm64-gnu": "1.2.8", "@rolldown/binding-linux-arm64-musl": "1.2.8", "@rolldown/binding-linux-ppc64-gnu": "1.2.8", "@rolldown/binding-linux-s390x-gnu": "1.2.8", "@rolldown/binding-linux-x64-gnu": "1.2.8", "@rolldown/binding-linux-x64-musl": "1.2.8", "@rolldown/binding-openharmony-arm64": "1.2.8", "@rolldown/binding-win32-arm64-msvc": "1.2.8", "@rolldown/binding-win32-x64-msvc": "1.2.8" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-Z67nTmhZe7anqnM/EjI392w5i/ANUinjip7QYsOyN37oayduxt3ksdX0hf5OOamkAd53BiIHfbfSzfUmzKFQqQ=="],
"rolldown": ["rolldown@1.2.16", "", { "dependencies": { "@oxc-project/types": "=0.156.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.16", "@rolldown/binding-android-arm64": "1.2.16", "@rolldown/binding-darwin-arm64": "1.2.16", "@rolldown/binding-darwin-x64": "1.2.16", "@rolldown/binding-freebsd-x64": "1.2.16", "@rolldown/binding-linux-arm-gnueabihf": "1.2.16", "@rolldown/binding-linux-arm64-gnu": "1.2.16", "@rolldown/binding-linux-arm64-musl": "1.2.16", "@rolldown/binding-linux-ppc64-gnu": "1.2.16", "@rolldown/binding-linux-s390x-gnu": "1.2.16", "@rolldown/binding-linux-x64-gnu": "1.2.16", "@rolldown/binding-linux-x64-musl": "1.2.16", "@rolldown/binding-openharmony-arm64": "1.2.16", "@rolldown/binding-win32-arm64-msvc": "1.2.16", "@rolldown/binding-win32-x64-msvc": "1.2.16" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw=="],
"rxjs": ["rxjs@7.8.2", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
@@ -1009,9 +1009,9 @@
"@angular/build/magic-string": ["magic-string@1.4.1", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-8lyCu36ErXR0J9uaGKlKQoiLZKmtI63YGLE8G2o9jyRPdr4X47LusSOwgOJOzcVtp81fTAAjxR7BwKz682Jhow=="],
"@angular/build/oxc-parser": ["oxc-parser@0.150.0", "", { "dependencies": { "@oxc-project/types": "^0.150.0" }, "optionalDependencies": { "@oxc-parser/binding-android-arm-eabi": "0.150.0", "@oxc-parser/binding-android-arm64": "0.150.0", "@oxc-parser/binding-darwin-arm64": "0.150.0", "@oxc-parser/binding-darwin-x64": "0.150.0", "@oxc-parser/binding-freebsd-x64": "0.150.0", "@oxc-parser/binding-linux-arm-gnueabihf": "0.150.0", "@oxc-parser/binding-linux-arm-musleabihf": "0.150.0", "@oxc-parser/binding-linux-arm64-gnu": "0.150.0", "@oxc-parser/binding-linux-arm64-musl": "0.150.0", "@oxc-parser/binding-linux-ppc64-gnu": "0.150.0", "@oxc-parser/binding-linux-riscv64-gnu": "0.150.0", "@oxc-parser/binding-linux-riscv64-musl": "0.150.0", "@oxc-parser/binding-linux-s390x-gnu": "0.150.0", "@oxc-parser/binding-linux-x64-gnu": "0.150.0", "@oxc-parser/binding-linux-x64-musl": "0.150.0", "@oxc-parser/binding-openharmony-arm64": "0.150.0", "@oxc-parser/binding-win32-arm64-msvc": "0.150.0", "@oxc-parser/binding-win32-ia32-msvc": "0.150.0", "@oxc-parser/binding-win32-x64-msvc": "0.150.0" } }, "sha512-zwajKw1GUa57IOdafIS7/yOObGF2NihwIfZfs5yJTRprMSkiwhWOc/k+n8bwnUPbHr2/XsjfBO8KyTPaW3VpWg=="],
"@angular/build/oxc-parser": ["oxc-parser@0.156.0", "", { "dependencies": { "@oxc-project/types": "^0.156.0" }, "optionalDependencies": { "@oxc-parser/binding-android-arm-eabi": "0.156.0", "@oxc-parser/binding-android-arm64": "0.156.0", "@oxc-parser/binding-darwin-arm64": "0.156.0", "@oxc-parser/binding-darwin-x64": "0.156.0", "@oxc-parser/binding-freebsd-x64": "0.156.0", "@oxc-parser/binding-linux-arm-gnueabihf": "0.156.0", "@oxc-parser/binding-linux-arm-musleabihf": "0.156.0", "@oxc-parser/binding-linux-arm64-gnu": "0.156.0", "@oxc-parser/binding-linux-arm64-musl": "0.156.0", "@oxc-parser/binding-linux-ppc64-gnu": "0.156.0", "@oxc-parser/binding-linux-riscv64-gnu": "0.156.0", "@oxc-parser/binding-linux-riscv64-musl": "0.156.0", "@oxc-parser/binding-linux-s390x-gnu": "0.156.0", "@oxc-parser/binding-linux-x64-gnu": "0.156.0", "@oxc-parser/binding-linux-x64-musl": "0.156.0", "@oxc-parser/binding-openharmony-arm64": "0.156.0", "@oxc-parser/binding-win32-arm64-msvc": "0.156.0", "@oxc-parser/binding-win32-ia32-msvc": "0.156.0", "@oxc-parser/binding-win32-x64-msvc": "0.156.0" } }, "sha512-7JhjgOfZjrIFJH5TlHrpRua864Si5GvwrPr5+eIRCY2sszhKXo6pyhP0HQKOGTtfO4UowwZ72XTGba0+lZphOQ=="],
"@angular/build/vite": ["vite@8.3.0", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.28", "rolldown": "~1.2.6", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ=="],
"@angular/build/vite": ["vite@8.3.5", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.30", "rolldown": "~1.2.14", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1 || ^0.8.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ=="],
"@angular/compiler-cli/@babel/core": ["@babel/core@8.0.1", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-compilation-targets": "^8.0.0", "@babel/helpers": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/template": "^8.0.0", "@babel/traverse": "^8.0.0", "@babel/types": "^8.0.0", "@types/gensync": "^1.0.5", "convert-source-map": "^2.0.0", "empathic": "^2.0.1", "gensync": "^1.0.0-beta.2", "import-meta-resolve": "^4.2.0", "json5": "^2.2.3", "obug": "^2.1.1", "semver": "^7.7.3" } }, "sha512-5FgxM4dLQpMJHSiVATk8foW263dVHQHBVpXYiimNECVWG01f4nFyEbQixeT6Mwvg7TayREJ2gpKl3o2RoMdnqw=="],
@@ -1053,9 +1053,13 @@
"@modelcontextprotocol/server/zod": ["zod@4.6.5", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="],
"@napi-rs/wasm-runtime/@emnapi/core": ["@emnapi/core@1.10.0", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" } }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="],
"@napi-rs/wasm-runtime/@emnapi/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="],
"@parcel/watcher/node-addon-api": ["node-addon-api@7.1.1", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],
"@schematics/angular/oxc-parser": ["oxc-parser@0.150.0", "", { "dependencies": { "@oxc-project/types": "^0.150.0" }, "optionalDependencies": { "@oxc-parser/binding-android-arm-eabi": "0.150.0", "@oxc-parser/binding-android-arm64": "0.150.0", "@oxc-parser/binding-darwin-arm64": "0.150.0", "@oxc-parser/binding-darwin-x64": "0.150.0", "@oxc-parser/binding-freebsd-x64": "0.150.0", "@oxc-parser/binding-linux-arm-gnueabihf": "0.150.0", "@oxc-parser/binding-linux-arm-musleabihf": "0.150.0", "@oxc-parser/binding-linux-arm64-gnu": "0.150.0", "@oxc-parser/binding-linux-arm64-musl": "0.150.0", "@oxc-parser/binding-linux-ppc64-gnu": "0.150.0", "@oxc-parser/binding-linux-riscv64-gnu": "0.150.0", "@oxc-parser/binding-linux-riscv64-musl": "0.150.0", "@oxc-parser/binding-linux-s390x-gnu": "0.150.0", "@oxc-parser/binding-linux-x64-gnu": "0.150.0", "@oxc-parser/binding-linux-x64-musl": "0.150.0", "@oxc-parser/binding-openharmony-arm64": "0.150.0", "@oxc-parser/binding-win32-arm64-msvc": "0.150.0", "@oxc-parser/binding-win32-ia32-msvc": "0.150.0", "@oxc-parser/binding-win32-x64-msvc": "0.150.0" } }, "sha512-zwajKw1GUa57IOdafIS7/yOObGF2NihwIfZfs5yJTRprMSkiwhWOc/k+n8bwnUPbHr2/XsjfBO8KyTPaW3VpWg=="],
"@schematics/angular/oxc-parser": ["oxc-parser@0.156.0", "", { "dependencies": { "@oxc-project/types": "^0.156.0" }, "optionalDependencies": { "@oxc-parser/binding-android-arm-eabi": "0.156.0", "@oxc-parser/binding-android-arm64": "0.156.0", "@oxc-parser/binding-darwin-arm64": "0.156.0", "@oxc-parser/binding-darwin-x64": "0.156.0", "@oxc-parser/binding-freebsd-x64": "0.156.0", "@oxc-parser/binding-linux-arm-gnueabihf": "0.156.0", "@oxc-parser/binding-linux-arm-musleabihf": "0.156.0", "@oxc-parser/binding-linux-arm64-gnu": "0.156.0", "@oxc-parser/binding-linux-arm64-musl": "0.156.0", "@oxc-parser/binding-linux-ppc64-gnu": "0.156.0", "@oxc-parser/binding-linux-riscv64-gnu": "0.156.0", "@oxc-parser/binding-linux-riscv64-musl": "0.156.0", "@oxc-parser/binding-linux-s390x-gnu": "0.156.0", "@oxc-parser/binding-linux-x64-gnu": "0.156.0", "@oxc-parser/binding-linux-x64-musl": "0.156.0", "@oxc-parser/binding-openharmony-arm64": "0.156.0", "@oxc-parser/binding-win32-arm64-msvc": "0.156.0", "@oxc-parser/binding-win32-ia32-msvc": "0.156.0", "@oxc-parser/binding-win32-x64-msvc": "0.156.0" } }, "sha512-7JhjgOfZjrIFJH5TlHrpRua864Si5GvwrPr5+eIRCY2sszhKXo6pyhP0HQKOGTtfO4UowwZ72XTGba0+lZphOQ=="],
"@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.5", "", {}, "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg=="],
@@ -1071,7 +1075,9 @@
"magic-string/@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],
"rolldown/@oxc-project/types": ["@oxc-project/types@0.149.0", "", {}, "sha512-Efcc+iF0j3Bf67YjEqIqWXbX5XddXoK/Mw4K1/JuXwRCZ8N16VR7iT23nlCc9XrveFVh/E5Rqs2StT0V8v9LdA=="],
"oxc-parser/@oxc-parser/binding-wasm32-wasi": ["@oxc-parser/binding-wasm32-wasi@0.121.0", "", { "dependencies": { "@napi-rs/wasm-runtime": "^1.1.1" }, "cpu": "none" }, "sha512-5TFISkPTymKvsmIlKasPVTPuWxzCcrT8pM+p77+mtQbIZDd1UC8zww4CJcRI46kolmgrEX6QpKO8AvWMVZ+ifw=="],
"rolldown/@oxc-project/types": ["@oxc-project/types@0.156.0", "", {}, "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw=="],
"sass-embedded/supports-color": ["supports-color@8.1.1", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="],
@@ -1079,94 +1085,98 @@
"@angular-devkit/core/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"@angular/build/oxc-parser/@oxc-parser/binding-android-arm-eabi": ["@oxc-parser/binding-android-arm-eabi@0.150.0", "", { "os": "android", "cpu": "arm" }, "sha512-oQef2Zu4Prz1KLKznz3HqZzU9uVoA5PMoDZuuLmqms7hKmKSAPzlaMnLllJq3t+rgKmfJJ2siPrpZfFrW06btw=="],
"@angular/build/oxc-parser/@oxc-parser/binding-android-arm-eabi": ["@oxc-parser/binding-android-arm-eabi@0.156.0", "", { "os": "android", "cpu": "arm" }, "sha512-RMq7DKNzEp1T51QKNLTn0NryNEt2IYfh7mZBlIdi2Ju52ltOEDMeIXv0XBpA6dL7j7ChjlcovtGcc1Jv4qMipg=="],
"@angular/build/oxc-parser/@oxc-parser/binding-android-arm64": ["@oxc-parser/binding-android-arm64@0.150.0", "", { "os": "android", "cpu": "arm64" }, "sha512-B6ofpoFiAUwIZ0MJ2IgHPvZK8FAtL4qzSZRwOkAKIfxEobE1mQC8nDdiFZj7pUaJiVUVCsfkMsBJKedzO8rZvA=="],
"@angular/build/oxc-parser/@oxc-parser/binding-android-arm64": ["@oxc-parser/binding-android-arm64@0.156.0", "", { "os": "android", "cpu": "arm64" }, "sha512-mwkWKhOBpmh8fWc3m4MiLsmEAtx0YuHmvyo9ff557cnb3QZ2kt2eauSz75wCGIpiZG3gUsJ4WwzEjm4R4/BHig=="],
"@angular/build/oxc-parser/@oxc-parser/binding-darwin-arm64": ["@oxc-parser/binding-darwin-arm64@0.150.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-J+9IHKzx/bSz1JetOfD4zKXSK9sOm4/a7+0qomJODcTL6JsRXGeV/ZdkAPSIDydfFmWzYCraMlQEosSZEyBYkQ=="],
"@angular/build/oxc-parser/@oxc-parser/binding-darwin-arm64": ["@oxc-parser/binding-darwin-arm64@0.156.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-6pGR5fUszM9M4eBBapqpGjCRJolFwuCldx8bRQjqXyM09cQysBTWVF2Ttg4UNJVxYSaw5RRINbveCOOCrsuGvA=="],
"@angular/build/oxc-parser/@oxc-parser/binding-darwin-x64": ["@oxc-parser/binding-darwin-x64@0.150.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-v6IPfcAcSYrBWXV5Tce1DmxDMXLhEYpIIWiRFPJopgCVscZdLaV4MRQOUxvL3usQlw+yrwYOjBFB9IwBx+jUiQ=="],
"@angular/build/oxc-parser/@oxc-parser/binding-darwin-x64": ["@oxc-parser/binding-darwin-x64@0.156.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-M9QghL7uCAqMKjYJv1rDGblfEvkeQu3QzTPd7Uwo16gG3uO7m9ikVQ9OL8FZTnKzU4vbCEby6kTlEkqN+JeEMA=="],
"@angular/build/oxc-parser/@oxc-parser/binding-freebsd-x64": ["@oxc-parser/binding-freebsd-x64@0.150.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-AoR/4jD02HET0KO0yNT4nbTE+XJUxiO9jB1X/ycEjUE3WrIJ3IjV/Vf+gskhWLcqqeXfvNnkDtBR7epllAm88A=="],
"@angular/build/oxc-parser/@oxc-parser/binding-freebsd-x64": ["@oxc-parser/binding-freebsd-x64@0.156.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-lX0ANxSwAOrpOT7NHB+YsrBqDJ8sOVon5m7GS9eQtkuUeNzQMMGpFsJLsStawTbrdwOF5KDVxgPWcKmt/DIZUQ=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-arm-gnueabihf": ["@oxc-parser/binding-linux-arm-gnueabihf@0.150.0", "", { "os": "linux", "cpu": "arm" }, "sha512-A/hycCFjLUrCmLoL5O/vBp40ohlaXO1Ta3v5hqYZxicYFs129wZmgZJggcW4mYGYbZebQLhup+N8JjeQl8qwyw=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-arm-gnueabihf": ["@oxc-parser/binding-linux-arm-gnueabihf@0.156.0", "", { "os": "linux", "cpu": "arm" }, "sha512-iPgYpasRcqk7X3TGncQg7B+6RotDvG8weug0UrgF+FXLf4KmaNDyT91BKONlqbHcNgK9Nryp7AEZGuQn32fP6g=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-arm-musleabihf": ["@oxc-parser/binding-linux-arm-musleabihf@0.150.0", "", { "os": "linux", "cpu": "arm" }, "sha512-pbqahg1Pkz7J4RKmXm30s/iQu99hv64ayXCu8P4p75HcEH5azOdR4eGqiB6lFGkFR3mMpzaYsSKLkS8oJbjmeQ=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-arm-musleabihf": ["@oxc-parser/binding-linux-arm-musleabihf@0.156.0", "", { "os": "linux", "cpu": "arm" }, "sha512-sJqJDEZevtkEfoxrXfaRTkSt6Itckr549cIfBbs11UgXv8bFyqQsXTQa6iKm8mTiWYmCDDFJf7TLnqxcbqzPOw=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-arm64-gnu": ["@oxc-parser/binding-linux-arm64-gnu@0.150.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-HV11aRbBQGwqv8bEo+K/6qr88uB4fEe1mhXncMhlVCrj+WpBSraxrUzHaPVmeQRU6x6x8v/3DuCbbo93rpp+fw=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-arm64-gnu": ["@oxc-parser/binding-linux-arm64-gnu@0.156.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-mrQs5OdRiqKskRuWEORPKT6YGIFhrpVvCvL9hqVaIh60EzgR4qjPvSsV6hWZcOfyWHBTbdEvfnDJPh/eQlxPRQ=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-arm64-musl": ["@oxc-parser/binding-linux-arm64-musl@0.150.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-k6pVkJqALwtEuP4zukVhGRhdIy4+ofChUIUUsAHHyqDZlNsknmel3JjbggrJiWGaes6h/dIcWmEXsKW4SmK9oQ=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-arm64-musl": ["@oxc-parser/binding-linux-arm64-musl@0.156.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-ZtPqgCU3+wpU7dvX7YbaEiw71r0UdguzuPhcx4PIEZSs4XFqc6F5wXCtNdb6M7m3DMErlxrwosryoXrzYOY/Gg=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-ppc64-gnu": ["@oxc-parser/binding-linux-ppc64-gnu@0.150.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-tEFg39mw/rHO5n8GK2DR4ZMFfsPQZtnQIPbsIpjoQRomJc/2tRfsCSmCT6gNit+NZGoeJG5aH9ATDH5bf0WnoQ=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-ppc64-gnu": ["@oxc-parser/binding-linux-ppc64-gnu@0.156.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-ZuGRT/adReZZJn3PYNneb1HQIOH0iIZ2fzFgC1/XJYpMQ5KsRKmWIEzy3wEFsUwIOTomCmnmTZ/zbFYo9z9VeA=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-riscv64-gnu": ["@oxc-parser/binding-linux-riscv64-gnu@0.150.0", "", { "os": "linux", "cpu": "none" }, "sha512-0JO7IFkoek6HqV589Menx3hJySNXi6quRhO4tq2P7kpEHKEXoDATnoPVUpn5B7gDH2KLkdo751N0uIrGJFCTCw=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-riscv64-gnu": ["@oxc-parser/binding-linux-riscv64-gnu@0.156.0", "", { "os": "linux", "cpu": "none" }, "sha512-T+iWCeAOoEAJpHqr6/pogHIv98g9p8Ctccysm/h962hG4ayX5OL2c0Ih4oYe+JuFndLXy/OASvwMlTPe76sIiw=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-riscv64-musl": ["@oxc-parser/binding-linux-riscv64-musl@0.150.0", "", { "os": "linux", "cpu": "none" }, "sha512-7XPzREnyAS5wHU9aB+49Uaqgoo1gVCklHc3DRlc3fJy2tXD/eAJFN1QFz/crj+Ulup5P1+axNREF+/RGaB/IRA=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-riscv64-musl": ["@oxc-parser/binding-linux-riscv64-musl@0.156.0", "", { "os": "linux", "cpu": "none" }, "sha512-wL55bI2kVKfwdxScbw60zVgzAqbQbmE5zpSPWPZoZ9RSG8egm6ITE/UWE5mDWlglxz1QElJCcUbpaJCtHD11BQ=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-s390x-gnu": ["@oxc-parser/binding-linux-s390x-gnu@0.150.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-7n7ZxcbRWDFaTdyj8M8p0O9OfzoMKm8O6syBAIgcSutbOALq0Bb9G52Me+XH0anMLZV+NgXc726gqgG2q39vcQ=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-s390x-gnu": ["@oxc-parser/binding-linux-s390x-gnu@0.156.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-+D+JilhLqwrDLODYEl4qtovVwgxKALb23FkAWBiPvgmUWYgjCV83KKuwwxZJM8GCdKlNA1vt3iKtow8HUFjXtg=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-x64-gnu": ["@oxc-parser/binding-linux-x64-gnu@0.150.0", "", { "os": "linux", "cpu": "x64" }, "sha512-Vx0GSA9ZCRTUiczoEQnIIyXkMvtEY8uc6IiwLQtMe5ci2sXPqjrry0Ek5fsPP1k2kCzkML3ow9UOOEgnEDi7Bw=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-x64-gnu": ["@oxc-parser/binding-linux-x64-gnu@0.156.0", "", { "os": "linux", "cpu": "x64" }, "sha512-jRfwpN4xKrsEpC+SgrUPY5k0mINYZn7aLrt22I3uQFoumiSgHgsLYgS9f84ntbkvSydH4HiwGuDa2b1XCHaJzw=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-x64-musl": ["@oxc-parser/binding-linux-x64-musl@0.150.0", "", { "os": "linux", "cpu": "x64" }, "sha512-ii4/9m3viDLssMnfXU7/Pni/3nYplApuGayceX4qsVGaqqQJCx3tHIH9M/HWIeSty5i8LjS21zPYT6lVIkwLxw=="],
"@angular/build/oxc-parser/@oxc-parser/binding-linux-x64-musl": ["@oxc-parser/binding-linux-x64-musl@0.156.0", "", { "os": "linux", "cpu": "x64" }, "sha512-P/ajnypgLmxmuRRyCIZcp2o4lOwmCaXYH5+eqDTcCW+MCTI+csKSw/Zc6GB67jZoVa4ey3q1jXEt7S60adBEMQ=="],
"@angular/build/oxc-parser/@oxc-parser/binding-openharmony-arm64": ["@oxc-parser/binding-openharmony-arm64@0.150.0", "", { "os": "none", "cpu": "arm64" }, "sha512-ZtoxX5rez36ZWkwtiEhjkCPnlTPoQ2I7lIL0IYZ1yjxMYohbvoOjBmUIZzrf9W/HouONq0omIfTeCWEY+R380w=="],
"@angular/build/oxc-parser/@oxc-parser/binding-openharmony-arm64": ["@oxc-parser/binding-openharmony-arm64@0.156.0", "", { "os": "none", "cpu": "arm64" }, "sha512-WSN6rQZZc9KqgZ4lMfjVDvqKhVOCjey/YEZIPisGXmwBqwgWOzru207dyiH50LHcf1n9LO2oceGk/id6RL9v0g=="],
"@angular/build/oxc-parser/@oxc-parser/binding-win32-arm64-msvc": ["@oxc-parser/binding-win32-arm64-msvc@0.150.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-VqeRb5JX/bKYBrff7TUDvJyKY0914UzuCkuXIGxJS4FUmvMNfqkCbc7Sq90iMz9DlmAtlggwaBYQ9eg3h3ltiw=="],
"@angular/build/oxc-parser/@oxc-parser/binding-win32-arm64-msvc": ["@oxc-parser/binding-win32-arm64-msvc@0.156.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-l21Tz6tjraGBC3JefVeJZ9pojD0fCiB62PydAv+i9nrqJX7z/pDmyDNYLamDr/PRcQ4UQbFwkSnz7NKBB9UMLw=="],
"@angular/build/oxc-parser/@oxc-parser/binding-win32-ia32-msvc": ["@oxc-parser/binding-win32-ia32-msvc@0.150.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-EPqJfeZ4Pgg2BJSsCV8GozxV0FDltRzpVtGVa1r2noJu1iu+opOw3gtBWXwIo9odCT/MdFfyHxdy0/CRqs3OqA=="],
"@angular/build/oxc-parser/@oxc-parser/binding-win32-ia32-msvc": ["@oxc-parser/binding-win32-ia32-msvc@0.156.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-CUq0ZFl/RODqPiIgfNNSamkpTj5x8AjBTkR/y1DNVIQiTGnmWqjHcn3o08ZW3q/LgkI4g9G9g6UirmmQFvuOZw=="],
"@angular/build/oxc-parser/@oxc-parser/binding-win32-x64-msvc": ["@oxc-parser/binding-win32-x64-msvc@0.150.0", "", { "os": "win32", "cpu": "x64" }, "sha512-n5YMzbqwPQqozbkrexi0lNZrUz5cnPHalYpFWe6Dau7AmKIWNo+y24IwzDuZEQtEdUHuKhXmMMih/MPjOI+CMw=="],
"@angular/build/oxc-parser/@oxc-parser/binding-win32-x64-msvc": ["@oxc-parser/binding-win32-x64-msvc@0.156.0", "", { "os": "win32", "cpu": "x64" }, "sha512-dcpx5Y1x2v/cs7U/q3SZMvmxfyXjVvqC86jMuw2ZZUbHDd7W2cW7uSMQfg3GLVaE68Su3H9xd/Pc4v6QNyeSRg=="],
"@angular/build/oxc-parser/@oxc-project/types": ["@oxc-project/types@0.150.0", "", {}, "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw=="],
"@angular/build/oxc-parser/@oxc-project/types": ["@oxc-project/types@0.156.0", "", {}, "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw=="],
"@angular/build/vite/rolldown": ["rolldown@1.2.12", "", { "dependencies": { "@oxc-project/types": "=0.152.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.12", "@rolldown/binding-android-arm64": "1.2.12", "@rolldown/binding-darwin-arm64": "1.2.12", "@rolldown/binding-darwin-x64": "1.2.12", "@rolldown/binding-freebsd-x64": "1.2.12", "@rolldown/binding-linux-arm-gnueabihf": "1.2.12", "@rolldown/binding-linux-arm64-gnu": "1.2.12", "@rolldown/binding-linux-arm64-musl": "1.2.12", "@rolldown/binding-linux-ppc64-gnu": "1.2.12", "@rolldown/binding-linux-s390x-gnu": "1.2.12", "@rolldown/binding-linux-x64-gnu": "1.2.12", "@rolldown/binding-linux-x64-musl": "1.2.12", "@rolldown/binding-openharmony-arm64": "1.2.12", "@rolldown/binding-win32-arm64-msvc": "1.2.12", "@rolldown/binding-win32-x64-msvc": "1.2.12" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ=="],
"@angular/build/vite/postcss": ["postcss@8.5.33", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ=="],
"@angular/compiler-cli/@babel/core/convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-android-arm-eabi": ["@oxc-parser/binding-android-arm-eabi@0.150.0", "", { "os": "android", "cpu": "arm" }, "sha512-oQef2Zu4Prz1KLKznz3HqZzU9uVoA5PMoDZuuLmqms7hKmKSAPzlaMnLllJq3t+rgKmfJJ2siPrpZfFrW06btw=="],
"@napi-rs/wasm-runtime/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-android-arm64": ["@oxc-parser/binding-android-arm64@0.150.0", "", { "os": "android", "cpu": "arm64" }, "sha512-B6ofpoFiAUwIZ0MJ2IgHPvZK8FAtL4qzSZRwOkAKIfxEobE1mQC8nDdiFZj7pUaJiVUVCsfkMsBJKedzO8rZvA=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-android-arm-eabi": ["@oxc-parser/binding-android-arm-eabi@0.156.0", "", { "os": "android", "cpu": "arm" }, "sha512-RMq7DKNzEp1T51QKNLTn0NryNEt2IYfh7mZBlIdi2Ju52ltOEDMeIXv0XBpA6dL7j7ChjlcovtGcc1Jv4qMipg=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-darwin-arm64": ["@oxc-parser/binding-darwin-arm64@0.150.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-J+9IHKzx/bSz1JetOfD4zKXSK9sOm4/a7+0qomJODcTL6JsRXGeV/ZdkAPSIDydfFmWzYCraMlQEosSZEyBYkQ=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-android-arm64": ["@oxc-parser/binding-android-arm64@0.156.0", "", { "os": "android", "cpu": "arm64" }, "sha512-mwkWKhOBpmh8fWc3m4MiLsmEAtx0YuHmvyo9ff557cnb3QZ2kt2eauSz75wCGIpiZG3gUsJ4WwzEjm4R4/BHig=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-darwin-x64": ["@oxc-parser/binding-darwin-x64@0.150.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-v6IPfcAcSYrBWXV5Tce1DmxDMXLhEYpIIWiRFPJopgCVscZdLaV4MRQOUxvL3usQlw+yrwYOjBFB9IwBx+jUiQ=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-darwin-arm64": ["@oxc-parser/binding-darwin-arm64@0.156.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-6pGR5fUszM9M4eBBapqpGjCRJolFwuCldx8bRQjqXyM09cQysBTWVF2Ttg4UNJVxYSaw5RRINbveCOOCrsuGvA=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-freebsd-x64": ["@oxc-parser/binding-freebsd-x64@0.150.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-AoR/4jD02HET0KO0yNT4nbTE+XJUxiO9jB1X/ycEjUE3WrIJ3IjV/Vf+gskhWLcqqeXfvNnkDtBR7epllAm88A=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-darwin-x64": ["@oxc-parser/binding-darwin-x64@0.156.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-M9QghL7uCAqMKjYJv1rDGblfEvkeQu3QzTPd7Uwo16gG3uO7m9ikVQ9OL8FZTnKzU4vbCEby6kTlEkqN+JeEMA=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-arm-gnueabihf": ["@oxc-parser/binding-linux-arm-gnueabihf@0.150.0", "", { "os": "linux", "cpu": "arm" }, "sha512-A/hycCFjLUrCmLoL5O/vBp40ohlaXO1Ta3v5hqYZxicYFs129wZmgZJggcW4mYGYbZebQLhup+N8JjeQl8qwyw=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-freebsd-x64": ["@oxc-parser/binding-freebsd-x64@0.156.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-lX0ANxSwAOrpOT7NHB+YsrBqDJ8sOVon5m7GS9eQtkuUeNzQMMGpFsJLsStawTbrdwOF5KDVxgPWcKmt/DIZUQ=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-arm-musleabihf": ["@oxc-parser/binding-linux-arm-musleabihf@0.150.0", "", { "os": "linux", "cpu": "arm" }, "sha512-pbqahg1Pkz7J4RKmXm30s/iQu99hv64ayXCu8P4p75HcEH5azOdR4eGqiB6lFGkFR3mMpzaYsSKLkS8oJbjmeQ=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-arm-gnueabihf": ["@oxc-parser/binding-linux-arm-gnueabihf@0.156.0", "", { "os": "linux", "cpu": "arm" }, "sha512-iPgYpasRcqk7X3TGncQg7B+6RotDvG8weug0UrgF+FXLf4KmaNDyT91BKONlqbHcNgK9Nryp7AEZGuQn32fP6g=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-arm64-gnu": ["@oxc-parser/binding-linux-arm64-gnu@0.150.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-HV11aRbBQGwqv8bEo+K/6qr88uB4fEe1mhXncMhlVCrj+WpBSraxrUzHaPVmeQRU6x6x8v/3DuCbbo93rpp+fw=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-arm-musleabihf": ["@oxc-parser/binding-linux-arm-musleabihf@0.156.0", "", { "os": "linux", "cpu": "arm" }, "sha512-sJqJDEZevtkEfoxrXfaRTkSt6Itckr549cIfBbs11UgXv8bFyqQsXTQa6iKm8mTiWYmCDDFJf7TLnqxcbqzPOw=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-arm64-musl": ["@oxc-parser/binding-linux-arm64-musl@0.150.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-k6pVkJqALwtEuP4zukVhGRhdIy4+ofChUIUUsAHHyqDZlNsknmel3JjbggrJiWGaes6h/dIcWmEXsKW4SmK9oQ=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-arm64-gnu": ["@oxc-parser/binding-linux-arm64-gnu@0.156.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-mrQs5OdRiqKskRuWEORPKT6YGIFhrpVvCvL9hqVaIh60EzgR4qjPvSsV6hWZcOfyWHBTbdEvfnDJPh/eQlxPRQ=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-ppc64-gnu": ["@oxc-parser/binding-linux-ppc64-gnu@0.150.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-tEFg39mw/rHO5n8GK2DR4ZMFfsPQZtnQIPbsIpjoQRomJc/2tRfsCSmCT6gNit+NZGoeJG5aH9ATDH5bf0WnoQ=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-arm64-musl": ["@oxc-parser/binding-linux-arm64-musl@0.156.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-ZtPqgCU3+wpU7dvX7YbaEiw71r0UdguzuPhcx4PIEZSs4XFqc6F5wXCtNdb6M7m3DMErlxrwosryoXrzYOY/Gg=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-riscv64-gnu": ["@oxc-parser/binding-linux-riscv64-gnu@0.150.0", "", { "os": "linux", "cpu": "none" }, "sha512-0JO7IFkoek6HqV589Menx3hJySNXi6quRhO4tq2P7kpEHKEXoDATnoPVUpn5B7gDH2KLkdo751N0uIrGJFCTCw=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-ppc64-gnu": ["@oxc-parser/binding-linux-ppc64-gnu@0.156.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-ZuGRT/adReZZJn3PYNneb1HQIOH0iIZ2fzFgC1/XJYpMQ5KsRKmWIEzy3wEFsUwIOTomCmnmTZ/zbFYo9z9VeA=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-riscv64-musl": ["@oxc-parser/binding-linux-riscv64-musl@0.150.0", "", { "os": "linux", "cpu": "none" }, "sha512-7XPzREnyAS5wHU9aB+49Uaqgoo1gVCklHc3DRlc3fJy2tXD/eAJFN1QFz/crj+Ulup5P1+axNREF+/RGaB/IRA=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-riscv64-gnu": ["@oxc-parser/binding-linux-riscv64-gnu@0.156.0", "", { "os": "linux", "cpu": "none" }, "sha512-T+iWCeAOoEAJpHqr6/pogHIv98g9p8Ctccysm/h962hG4ayX5OL2c0Ih4oYe+JuFndLXy/OASvwMlTPe76sIiw=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-s390x-gnu": ["@oxc-parser/binding-linux-s390x-gnu@0.150.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-7n7ZxcbRWDFaTdyj8M8p0O9OfzoMKm8O6syBAIgcSutbOALq0Bb9G52Me+XH0anMLZV+NgXc726gqgG2q39vcQ=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-riscv64-musl": ["@oxc-parser/binding-linux-riscv64-musl@0.156.0", "", { "os": "linux", "cpu": "none" }, "sha512-wL55bI2kVKfwdxScbw60zVgzAqbQbmE5zpSPWPZoZ9RSG8egm6ITE/UWE5mDWlglxz1QElJCcUbpaJCtHD11BQ=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-x64-gnu": ["@oxc-parser/binding-linux-x64-gnu@0.150.0", "", { "os": "linux", "cpu": "x64" }, "sha512-Vx0GSA9ZCRTUiczoEQnIIyXkMvtEY8uc6IiwLQtMe5ci2sXPqjrry0Ek5fsPP1k2kCzkML3ow9UOOEgnEDi7Bw=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-s390x-gnu": ["@oxc-parser/binding-linux-s390x-gnu@0.156.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-+D+JilhLqwrDLODYEl4qtovVwgxKALb23FkAWBiPvgmUWYgjCV83KKuwwxZJM8GCdKlNA1vt3iKtow8HUFjXtg=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-x64-musl": ["@oxc-parser/binding-linux-x64-musl@0.150.0", "", { "os": "linux", "cpu": "x64" }, "sha512-ii4/9m3viDLssMnfXU7/Pni/3nYplApuGayceX4qsVGaqqQJCx3tHIH9M/HWIeSty5i8LjS21zPYT6lVIkwLxw=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-x64-gnu": ["@oxc-parser/binding-linux-x64-gnu@0.156.0", "", { "os": "linux", "cpu": "x64" }, "sha512-jRfwpN4xKrsEpC+SgrUPY5k0mINYZn7aLrt22I3uQFoumiSgHgsLYgS9f84ntbkvSydH4HiwGuDa2b1XCHaJzw=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-openharmony-arm64": ["@oxc-parser/binding-openharmony-arm64@0.150.0", "", { "os": "none", "cpu": "arm64" }, "sha512-ZtoxX5rez36ZWkwtiEhjkCPnlTPoQ2I7lIL0IYZ1yjxMYohbvoOjBmUIZzrf9W/HouONq0omIfTeCWEY+R380w=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-linux-x64-musl": ["@oxc-parser/binding-linux-x64-musl@0.156.0", "", { "os": "linux", "cpu": "x64" }, "sha512-P/ajnypgLmxmuRRyCIZcp2o4lOwmCaXYH5+eqDTcCW+MCTI+csKSw/Zc6GB67jZoVa4ey3q1jXEt7S60adBEMQ=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-win32-arm64-msvc": ["@oxc-parser/binding-win32-arm64-msvc@0.150.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-VqeRb5JX/bKYBrff7TUDvJyKY0914UzuCkuXIGxJS4FUmvMNfqkCbc7Sq90iMz9DlmAtlggwaBYQ9eg3h3ltiw=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-openharmony-arm64": ["@oxc-parser/binding-openharmony-arm64@0.156.0", "", { "os": "none", "cpu": "arm64" }, "sha512-WSN6rQZZc9KqgZ4lMfjVDvqKhVOCjey/YEZIPisGXmwBqwgWOzru207dyiH50LHcf1n9LO2oceGk/id6RL9v0g=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-win32-ia32-msvc": ["@oxc-parser/binding-win32-ia32-msvc@0.150.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-EPqJfeZ4Pgg2BJSsCV8GozxV0FDltRzpVtGVa1r2noJu1iu+opOw3gtBWXwIo9odCT/MdFfyHxdy0/CRqs3OqA=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-win32-arm64-msvc": ["@oxc-parser/binding-win32-arm64-msvc@0.156.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-l21Tz6tjraGBC3JefVeJZ9pojD0fCiB62PydAv+i9nrqJX7z/pDmyDNYLamDr/PRcQ4UQbFwkSnz7NKBB9UMLw=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-win32-x64-msvc": ["@oxc-parser/binding-win32-x64-msvc@0.150.0", "", { "os": "win32", "cpu": "x64" }, "sha512-n5YMzbqwPQqozbkrexi0lNZrUz5cnPHalYpFWe6Dau7AmKIWNo+y24IwzDuZEQtEdUHuKhXmMMih/MPjOI+CMw=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-win32-ia32-msvc": ["@oxc-parser/binding-win32-ia32-msvc@0.156.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-CUq0ZFl/RODqPiIgfNNSamkpTj5x8AjBTkR/y1DNVIQiTGnmWqjHcn3o08ZW3q/LgkI4g9G9g6UirmmQFvuOZw=="],
"@schematics/angular/oxc-parser/@oxc-project/types": ["@oxc-project/types@0.150.0", "", {}, "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-win32-x64-msvc": ["@oxc-parser/binding-win32-x64-msvc@0.156.0", "", { "os": "win32", "cpu": "x64" }, "sha512-dcpx5Y1x2v/cs7U/q3SZMvmxfyXjVvqC86jMuw2ZZUbHDd7W2cW7uSMQfg3GLVaE68Su3H9xd/Pc4v6QNyeSRg=="],
"@schematics/angular/oxc-parser/@oxc-project/types": ["@oxc-project/types@0.156.0", "", {}, "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw=="],
"@typescript-eslint/typescript-estree/tinyglobby/picomatch": ["picomatch@4.0.4", "", {}, "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A=="],
"ajv-formats/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"oxc-parser/@oxc-parser/binding-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.4", "", { "dependencies": { "@tybys/wasm-util": "^0.10.1" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow=="],
"vite/rolldown/@oxc-project/types": ["@oxc-project/types@0.152.0", "", {}, "sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw=="],
"vite/rolldown/@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.12", "", { "os": "android", "cpu": "arm" }, "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A=="],
@@ -1199,36 +1209,16 @@
"vite/rolldown/@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.12", "", { "os": "win32", "cpu": "x64" }, "sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ=="],
"@angular/build/vite/rolldown/@oxc-project/types": ["@oxc-project/types@0.152.0", "", {}, "sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw=="],
"@angular/build/vite/postcss/nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="],
"@angular/build/vite/rolldown/@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.12", "", { "os": "android", "cpu": "arm" }, "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A=="],
"@angular/build/vite/postcss/source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="],
"@angular/build/vite/rolldown/@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.12", "", { "os": "android", "cpu": "arm64" }, "sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg=="],
"oxc-parser/@oxc-parser/binding-wasm32-wasi/@napi-rs/wasm-runtime/@emnapi/core": ["@emnapi/core@1.10.0", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" } }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="],
"@angular/build/vite/rolldown/@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.12", "", { "os": "darwin", "cpu": "arm64" }, "sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w=="],
"oxc-parser/@oxc-parser/binding-wasm32-wasi/@napi-rs/wasm-runtime/@emnapi/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="],
"@angular/build/vite/rolldown/@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.2.12", "", { "os": "darwin", "cpu": "x64" }, "sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA=="],
"oxc-parser/@oxc-parser/binding-wasm32-wasi/@napi-rs/wasm-runtime/@tybys/wasm-util": ["@tybys/wasm-util@0.10.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg=="],
"@angular/build/vite/rolldown/@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.12", "", { "os": "freebsd", "cpu": "x64" }, "sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ=="],
"@angular/build/vite/rolldown/@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.12", "", { "os": "linux", "cpu": "arm" }, "sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g=="],
"@angular/build/vite/rolldown/@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw=="],
"@angular/build/vite/rolldown/@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw=="],
"@angular/build/vite/rolldown/@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.12", "", { "os": "linux", "cpu": "ppc64" }, "sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ=="],
"@angular/build/vite/rolldown/@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.2.12", "", { "os": "linux", "cpu": "s390x" }, "sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw=="],
"@angular/build/vite/rolldown/@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.12", "", { "os": "linux", "cpu": "x64" }, "sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw=="],
"@angular/build/vite/rolldown/@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.12", "", { "os": "linux", "cpu": "x64" }, "sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g=="],
"@angular/build/vite/rolldown/@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.12", "", { "os": "none", "cpu": "arm64" }, "sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA=="],
"@angular/build/vite/rolldown/@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.2.12", "", { "os": "win32", "cpu": "arm64" }, "sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew=="],
"@angular/build/vite/rolldown/@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.12", "", { "os": "win32", "cpu": "x64" }, "sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ=="],
"oxc-parser/@oxc-parser/binding-wasm32-wasi/@napi-rs/wasm-runtime/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w=="],
}
}
@@ -1,3 +1,5 @@
# Restore Saved Planning Inputs Before Generating Random Defaults
[ADR 0013](0013-empty-leave-balances-on-first-visit.md) supersedes the random initial balances below: an absent or unreadable saved list now starts empty. Restoring saved inputs, deleting unreadable data first and saving the whole list on every balance edit are unchanged.
VacOptimizer restores a single locally saved leave-balance list, including an intentionally empty list, with its quantities, leave types, availability dates, and expiry dates; planning rules retain their existing local persistence. Random initial balances are generated when the saved balance list is absent or unreadable: unreadable balance data is deleted first, and the generated list remains unsaved until the first balance edit, after which every balance edit automatically saves the entire current list. Restoring valid saved inputs before initialization prevents random defaults from overwriting user data and keeps a single dataset within the client-side scope of ADR 0002.
@@ -0,0 +1,13 @@
# Obligation Solutions Hold Only the Preference Patterns That Fund an Obligation
Accepted on 2026-11-11 for [issue #347](https://gitea.nessar.fr/nessar/vac-optimizer/issues/347). This is a search change under [ADR 0010](0010-rank-obligation-solutions-before-preferences.md).
An obligation can depend on leave that a preference IF_THEN rule earns, so the obligation search may place that rule's pattern. Until now, every occurrence of an enabled preference IF_THEN rule that earns leave joined the obligation search whenever an obligation needed a placement, and its presence lifted the obligation solution limit. The search then enumerated every obligation solution, times every way to place or skip each pattern, and ranked them all. With Samedi Malin and one obligation of 5 days in a four-week window, three years of 5 CP took 12.8 seconds in the `obligations` stage on the development desktop, and an unsatisfiable four-year variant took 245 seconds to report its planning conflict. The best-ranked solution also kept patterns that funded nothing, ahead of higher-priority preferences: over two years, adding an unrelated February 2024 obligation made Samedi Malin satisfied, whereas the same request without the obligation leaves it unsatisfied with reason `higher-priority`.
An obligation solution does not pre-place a preference pattern whose earned leave funds no obligation. An occurrence joins the obligation search only if its earned leave can fund a compatible obligation date after the occurrence, directly or through the pattern of another joining occurrence. An earned leave entitlement becomes available only after its time-off period, which holds the occurrence, so this test never drops an occurrence that an obligation can use; it may keep one that turns out unable to fund. When no occurrence joins, the obligation search is the one of the request without that preference rule, including its solution limit. A pattern that funds no obligation is planned in its own stage, in rule priority order.
## Consequences
The three requests of the issue complete in under a second on the development laptop: the three-year request, the four-year conflict and the three-year request with two obligations, which did not finish in four minutes on the desktop. The two-year request now leaves Samedi Malin unsatisfied with reason `higher-priority`, with 10 placements instead of 11, as without its obligation. That is the accepted loss: where loss prevention ranks first and spends the CP a Samedi Malin pattern needs, the plan no longer earns that day; the three-year request plans 15 placements instead of 17 and earns no day instead of two. Whether loss prevention should leave room for such a pattern belongs to its own stage, not to the obligation search.
The 5,000 seeded requests of the [frozen-engine differential check](../benchmark/README.md#frozen-engine-differential-check) keep identical outcomes; their horizons last at most ten weeks. Of its six multi-year requests, only the two-year request with a TIME_WINDOW obligation changes, the same way as above: Samedi Malin goes from 1 to 0, and no lower objective gets worse. The [comparison record](../benchmark/issue-347.md) lists every request that became worse. When occurrences do fund an obligation, the enumeration stays unbounded.
@@ -0,0 +1,11 @@
---
status: accepted
---
# Empty Leave Balances on a First Visit
Accepted on 2026-11-13 for [issue #356](https://gitea.nessar.fr/nessar/vac-optimizer/issues/356). This supersedes the random initial balances of [ADR 0005](0005-saved-planning-inputs-before-random-defaults.md); restoring the saved list, including an intentionally empty one, deleting unreadable data first and saving the whole list on every balance edit are unchanged.
A first-time visitor saw a plan calculated on three random balances of 10 to 20 days that they never entered. When the saved leave-balance list is absent or unreadable, VacOptimizer now starts from an empty list, and no quantity is ever generated. The configuration panel then invites the user to add a first leave balance.
With no leave balance and no declared non-working day there is nothing to plan: no calculation starts when the page opens, Calculate is disabled with the reason given to assistive technologies, as for an invalid planning horizon, and the results panel shows the planning horizon's calendar, with its weekends and public holidays, and an invitation instead of plan figures. Declared non-working days alone still start a calculation, because they can earn leave that the plan then places ([ADR 0007](0007-declared-days-and-reported-balances.md)). A plan already on screen stays until the next calculation, as after any other edit.
@@ -0,0 +1,24 @@
---
status: accepted
---
# Rule Sets Shared Through the URL Fragment
Accepted on 2026-11-15 for [issue #363](https://gitea.nessar.fr/nessar/vac-optimizer/issues/363).
Users share their planning strategy with colleagues by sending a link whose fragment carries their whole rule set: every rule in order, disabled and optimization rules included. The link has its own versioned envelope, modelled on the stored `{ version, rules }` list but versioned independently of it. TIME_WINDOW boundaries travel as calendar dates, so a recipient in another time zone keeps the same window. The envelope is compressed with raw deflate and encoded in base64url. The server stores nothing and never receives the fragment, so ADR 0011's stateless server holds. A link is a snapshot: later edits by the sender do not reach it. Opening it replaces the recipient's whole rule set after confirmation, and it never carries leave balances, declared non-working days, or a planning horizon, which belong to each person.
## Considered Options
- **Server-stored short links**: rejected. They would need storage, expiry and abuse handling on a server that keeps no state, for a link of roughly 860 characters for the default rule set that messaging tools already accept.
- **A query parameter**: rejected. It is as long as the fragment and reaches server and proxy logs.
- **Sharing a selection of rules merged into the recipient's list**: rejected. The order is the rule priority, and inserting rules into someone else's order has no sensible default.
- **Sharing a plan**: deferred. Recomputing a plan from shared inputs depends on the calculation's Europe/Paris date and on the planner build, so a shared plan must be a read-only snapshot of the result, designed separately.
## Consequences
The envelope is a public contract. Every published version must remain decodable, and any change to the rule format needs a migration for links already sent.
Anyone can craft a link, so an import is all or nothing. It requires canonical values, known fields only, at most 100 rules and a bounded decompressed size, and every rule, including disabled ones, must pass the planner's own rule checks. Otherwise nothing changes. The sender is refused a link when one of their rules fails those checks, and the refusal names the rule, so that nobody sends a link that cannot be opened. A confirmed import is saved even when the recipient's stored rules are unreadable, and edits stay saved for the rest of the session, because the guard against overwriting them exists to stop accidental writes and the person has just accepted the replacement.
Another open tab still holds the previous rules and can overwrite an import with its next edit, as it can overwrite any rule edit today.
+59 -12
View File
@@ -48,9 +48,13 @@ tab-separated report follows the table.
| loaded year | 2.70 | 0.78 | 1.25 |
| two years | 0.54 | 0.16 | 0.25 |
| three years | 1.66 | 0.48 | 0.75 |
| default rules | 2.86 | 0.81 | 1.25 |
Ratios come from the development machine's Bun protocol after #321
(calibration 3.44 s, [record](issue-321.md#benchmark-protocol)); the multipliers
(calibration 3.44 s, [record](issue-321.md#benchmark-protocol)), and for
`default rules`, added by #348, from the development laptop after its exact
changes (calibration 3.53 s; 2.79 before them, [record](issue-348.md#benchmark));
the multipliers
add roughly 1.5x headroom, rounded up, with a floor of 0.05 for the two tiny
scenarios. Typed obligations gets 0.1: its 0.07-second run would leave a 0.05
budget only about 100 ms of headroom for runner jitter. After #302, the
@@ -78,7 +82,8 @@ needs roughly 400 seconds. The original 300-second `timeout` killed it during
the loaded year, while every completed scenario was within budget. The CI
`timeout` was therefore 600 seconds and the test timeout 570 seconds. After
#302 the whole local protocol took about 41 seconds, so srvhome should need
about 80; after #321 it takes about 39 seconds locally. #286 lowered the CI `timeout` to 240 seconds and the test timeout to
about 80; after #321 it takes about 39 seconds locally, and about 48 with the
`default rules` scenario of #348. #286 lowered the CI `timeout` to 240 seconds and the test timeout to
210 seconds, about three times that. They are only hang guards and do not
judge speed.
@@ -132,14 +137,23 @@ trace counters and timings are historical; current evidence is in
`src/app/services/frozen-engine.spec.ts` runs 5,000 seeded random planning
requests (seeds 280000 to 284999, one test per 200 seeds) through the current
engine and through a frozen copy of the engine. The copy was rebuilt for #302
from `8168137`, which plans from the best-ranked obligation solution
([comparison record](issue-302.md#comparison-record)). Until then it was the
engine at `a871f8f`, develop after PR #278, which remains the calibration
engine. For each request, the planning outcome, stable plan explanation,
explanation error and final-state snapshot must be strictly deep-equal,
including `PlanningConflict` and `InvalidInput` outcomes. Timings are not
compared.
engine and through a frozen copy of the engine. For each request, the planning
outcome, stable plan explanation, explanation error and final-state snapshot
must be strictly deep-equal, including `PlanningConflict` and `InvalidInput`
outcomes. Timings are not compared.
The frozen engine is the engine at `5aa3f39`. Its rebuilds, latest first:
| Built from | For | The commit | Record |
| ---------- | ---- | -------------------------------------------------------------------------------------- | ---------------------------------------------- |
| `5aa3f39` | #348 | reaches the same plans with less search behind an IF_THEN rule | [issue-348.md](issue-348.md) |
| `52059dc` | #347 | lets a preference producer join the obligation search only when it funds an obligation | [issue-347.md](issue-347.md) |
| `c86829d` | #349 | lets loss prevention skip relocation chains that cannot improve the protected prefix | [issue-349.md](issue-349.md) |
| `ea2feaf` | #350 | stopped IF_THEN patterns at a weekday public holiday | [issue-350.md](issue-350.md) |
| `8168137` | #302 | plans from the best-ranked obligation solution | [issue-302.md](issue-302.md#comparison-record) |
Until #302 it was the engine at `a871f8f`, develop after PR #278, which remains
the calibration engine.
Start dates span 2025 to 2027. About 15% of requests start in late December and
cross a year boundary, and about 15% start shortly before a weekday French
@@ -153,16 +167,48 @@ if an outcome kind, rule type, year-crossing horizon or public-holiday horizon
stops appearing. Requests stay small because candidate search grows quickly
with horizon length and balances; the slowest case takes about one second.
The seeded requests last at most ten weeks, so seven fixed requests of one to
three years with the default rules run beside them
(`src/app/services/frozen-engine/multi-year-planning-requests.ts`), with explicit
calculation dates and Christmas window dates. The default rules are loss
prevention, Samedi Malin, a Christmas preference of 20 December to 3 January,
then the five other optimization presets. The requests are three years of 5 CP
(the request of #350, where the frozen engine once differed), two years of 5 CP
with a TIME_WINDOW obligation (the obligation search of #347, whose change
altered its plan), two years of 5 CP with Samedi Malin ahead of loss
prevention, one year of 25 CP and 12 RTT, the same year in 2027 (three Saturday
public holidays, the stages after Samedi Malin of #348), three years of 5 CP
from 2026, and one year of 10 CP and 4 RTT from 1 September. They are compared
like the seeded requests, and a failure prints the request name and the request
as JSON. Keep them to a few seconds each.
The generator is `src/app/services/frozen-engine/random-planning-requests.ts`.
`compare-engines.ts` beside it is an opt-in runner, outside the functional suite
and CI, that classifies how the current engine's plans differ from the frozen
engine's, or with `calibration` from the calibration engine's, over the same
seeds; [the #302 record](issue-302.md#comparison-record) shows its use.
`repro-requests.ts` is a second opt-in runner: it plans one of the named
requests of the #347 to #350 records (`347-3y`, `348x-2027-1y-default`,
`349-samedi-first`...) on the current or the frozen engine, with a
planning-work budget, and prints the outcome, the time per planning stage, the
preference verdicts and the peak resident memory:
```sh
bun src/app/services/frozen-engine/repro-requests.ts list
bun src/app/services/frozen-engine/repro-requests.ts 348x-2027-1y-default
bun src/app/services/frozen-engine/repro-requests.ts 347-2y frozen 30000 /tmp/347-2y.json
```
To time a request before a change, run it on a checkout of the earlier commit,
or on the frozen engine while it still predates the change.
The fixture is `src/app/services/frozen-engine/leave-planner.core.frozen.mjs`,
a generated bundle with `date-holidays` left external, and its hand-written
`leave-planner.core.frozen.d.mts`. Rebuild it only for an intended behavior
change, in its own reviewed commit, from the commit that introduces the change.
The cancelled comparisons stop both engines after the same number of steps and
compare that number, so a change that removes steps needs a rebuild too, even
when every completed calculation stays identical ([#349](issue-349.md)).
Before rebuilding, while the frozen engine is still the previous one, run the
comparison and record its counts and every request that became worse on a real
objective with the change, as [the #302 record](issue-302.md#comparison-record)
@@ -186,7 +232,8 @@ FROZEN_ENGINE_SEED=<seed> bun test --isolate src/app/services/frozen-engine.spec
```
The check runs in the functional suite. On the development laptop with Bun
1.4.3 it takes about 54 seconds with or without coverage
1.4.3 it takes about 32 seconds, about 12 of them for the seven multi-year
requests (6 for the 2027 one), and about 36 seconds with coverage
(`bun test --config=bunfig.coverage.toml --isolate src/app/services/frozen-engine.spec.ts`; coverage is line-level only).
A flipped objective direction in `compareObjectiveValues` made 26 of its tests
fail, starting at seed 280002; the change was reverted.
@@ -194,7 +241,7 @@ fail, starting at seed 280002; the change was reverted.
## Reference-phone protocol
Open the deployed application at `/benchmark` on the reference phone. Tap
**Run benchmark**, wait for the seven scenarios to finish, then tap **Copy
**Run benchmark**, wait for the eight scenarios to finish, then tap **Copy
report** and save the tab-separated output with the date and build identifier.
The harness measures preparation, planning-to-outcome latency, planning work, and total wall time through stable explanation delivery. It also reports the largest extra delay of a 50 ms UI heartbeat, available main-thread heap, outcome, last completed quality stage, placement count and determinism. `PlanningIncomplete` retains its last completed stage and valid incumbent and is distinct from a conflict.
+12 -2
View File
@@ -92,21 +92,31 @@ are after the changes above.
plans: in the two-year case Samedi Malin is no longer satisfied (10
placements instead of 11), because the obligation search no longer places its
pattern ahead of higher-priority preferences. The seeded check does not see
the difference.
the difference. Since resolved: an occurrence now joins only when its earned
leave can fund an obligation ([record](issue-347.md),
[ADR 0012](../adr/0012-obligation-solutions-hold-only-funding-preference-patterns.md)).
- **A window preference after a rule that earns leave**
([#348](https://gitea.nessar.fr/nessar/vac-optimizer/issues/348)). With the default
rules, three years of 25 CP and 12 RTT take 17 seconds, 12.6 of them in the
Christmas stage; without Samedi Malin that stage takes 6 milliseconds. The
likely cause, not verified here, is the stage's early return when every
earlier objective is at its bound, which an unsatisfied IF_THEN preference
never is.
never is. The [#348 record](issue-348.md) measures it: exact changes take a
default year in 2027 from 11.0 to 3.4 seconds on the development laptop, where
this request still spends 12.6 of its 17.2 seconds in the Christmas stage, on
moves the plan needs on other requests.
- **Samedi Malin as the first priority**
([#349](https://gitea.nessar.fr/nessar/vac-optimizer/issues/349)). One year of 25 CP and 12 RTT with
Samedi Malin ahead of loss prevention does not finish the loss-prevention
stage in 100 seconds; with loss prevention first it takes 0.3 seconds.
The [#349 record](issue-349.md) explains it: relocation chains that could not
improve the protected prefix. The stage now skips them, and the request plans
in about 1.5 seconds on the development laptop.
- **The frozen engine differs from `5810b59` on a three-year request**
([#350](https://gitea.nessar.fr/nessar/vac-optimizer/issues/350)). With
the default rules, 5 CP per year from 2025 to 2027 and a 2025-01-01
calculation date, the two engines place four placements differently around
May 2027. The difference predates this issue and the seeded check does not
reach it.
The [#350 record](issue-350.md) explains it, rebuilds the frozen engine and
adds multi-year requests to the check.
+220
View File
@@ -0,0 +1,220 @@
# Issue #347: let a preference producer join the obligation search only when it funds an obligation
Record for [issue #347](https://gitea.nessar.fr/nessar/vac-optimizer/issues/347).
With one obligation and Samedi Malin, the `obligations` stage took seconds to
minutes, and an unsatisfiable request took minutes to report its planning
conflict. An occurrence of a preference IF_THEN rule that earns leave now joins
the obligation search only when its earned leave can fund an obligation
([ADR 0012](../adr/0012-obligation-solutions-hold-only-funding-preference-patterns.md)).
This is a search change under
[ADR 0010](../adr/0010-rank-obligation-solutions-before-preferences.md): the
change is `52059dc`, and the frozen engine of the
[differential check](README.md#frozen-engine-differential-check) was rebuilt
from it.
Unless noted, times are single runs of the repro runner
(`src/app/services/frozen-engine/repro-requests.ts`, which names the requests
below) on the development laptop (AMD Ryzen 5 7640U, WSL2, Bun 1.4.3), through
`calculatePlanningAsyncInternal`. Peak memory is the runner's `VmHWM`.
## Cause
When an obligation needed a placement, `calculatePlanningSteps` added every
occurrence of every enabled preference IF_THEN rule that earns leave to the
obligation search as an optional requirement, whether or not its earned leave
could pay for an obligation date. Any such occurrence also lifted the
obligation solution limit. `satisfyObligations` then enumerated every
obligation solution: every choice of dates in the obligation windows, times
every way to place or skip each occurrence's pattern. Each solution was
finalized and ranked before the preferences ran once on the best-ranked one.
The request of the issue: three years from 2024-01-01, calculated on
2024-01-01, 5 CP per year (`cp-2024`, `cp-2025`, `cp-2026`, each available on
1 January and expiring on 31 December), and the rules loss prevention, Samedi
Malin (IF_THEN preference, Saturday, 2 CP, `auto`, earning 1 Other day), a
TIME_WINDOW obligation of 5 days of any type from 2024-02-01 to 2024-02-28,
then the five other optimization presets. The Saturday public holidays of the
horizon, 1 November 2025 and 15 August 2026, all come after the obligation, so
their earned days could never fund it, yet both patterns were enumerated with
every choice of 5 dates among the window's 20.
The ranking also kept a pattern that funded nothing: the best-ranked obligation
solution held a Samedi Malin pattern, placed before loss prevention could run.
Over two years, the same request without its obligation leaves Samedi Malin
unsatisfied with reason `higher-priority`; adding the unrelated February 2024
obligation made it satisfied.
## The rule
A preference occurrence that earns leave stays in the obligation search only
if some obligation that still needs placements accepts its reward's leave type
and has a candidate date after the occurrence, or if the pattern of another
occurrence that stays does. The set is grown until no occurrence joins, so
chains and cycles between producers settle. An earned leave entitlement
becomes available the day after its time-off period ends, and that period
holds the occurrence, so a date after the occurrence is a necessary condition:
the rule never drops an occurrence an obligation could use. It may keep one
that cannot fund in the end, because of expiry, a date inside the period, or an
entitlement available before the calculation date. When no occurrence stays,
the obligation search is the one of the request without that preference rule,
including its solution limit.
## Times
Before is the frozen engine built from `c86829d`, the engine of the branch
without this change, with a 30-second budget; after is `52059dc`.
| Request | Before | After | Peak memory before → after |
| ------------------------------------------- | ------------------------------------------------------------ | --------------------------------------- | -------------------------: |
| `347-3y` (the request of the issue) | Plan, 12.16 s (`obligations` 11.16 s), 17 placements | Plan, 0.49 s (`obligations` 0.17 s), 15 | 2.9 GB → 162 MB |
| `347-2y` (the same over two years) | Plan, 2.47 s (`obligations` 2.23 s), 11 placements | Plan, 0.36 s (`obligations` 0.17 s), 10 | 750 MB → 152 MB |
| `347-3y-two-obligations` | `PlanningIncomplete`, deadline, 30 s, still in `obligations` | Plan, 0.66 s (`obligations` 0.19 s), 15 | 6.8 GB → 162 MB |
| `347-4y-conflict` | see below | `PlanningConflict`, 0.28 s | → 93 MB |
| `347x-3y-obligation-after` (producer funds) | Plan, 3.20 s (`obligations` 2.76 s), 16 placements | Plan, 0.86 s (`obligations` 0.58 s), 15 | 693 MB → 239 MB |
`347-3y-two-obligations` adds the Christmas preference (5 days of any type,
2024-12-20 to 2025-01-03) and replaces the obligation by 3 CP from 2024-08-01 to
2024-08-28 and 2 days of any type in February 2024. The issue reported it still
running after 4 minutes on the development desktop (Ryzen 7 7800X3D). Here the
engine before the change held 6.8 GB after 30 seconds.
`347-4y-conflict` is four years with the Christmas preference, 10 CP from
2024-08-01 to 2024-08-28 and the February obligation. It was not rerun before
the change: during triage, on this laptop with develop at `2dbd232`, it
reported `PlanningConflict` after 244.5 seconds; the issue measured 245 seconds
on the desktop, and 12.8 seconds for `347-3y`.
Without Samedi Malin, the same requests take 0.40 s (`347-3y`), 0.54 s
(`347-3y-two-obligations`), 0.25 s (`347-4y-conflict`) and 0.35 s
(`347x-3y-obligation-after`) after the change. `347-3y`, `347-2y` and
`347-3y-two-obligations` now plan exactly like their variants without Samedi
Malin, apart from its unsatisfied verdict.
## Comparison record
Before the rebuild, with the frozen engine built from `c86829d` still in place:
```sh
bun src/app/services/frozen-engine/compare-engines.ts small 280000 5000
```
| Result | Requests |
| ------------------ | -------: |
| Identical | 5,000 |
| Any other category | 0 |
The frozen engine took 7.5 seconds and `52059dc` 7.4 seconds. The 500
cancelled comparisons of `bun test --isolate src/app/services/frozen-engine.spec.ts`
also matched, step counts included. Their horizons last at most ten weeks.
Of the six multi-year requests of the check, compared the same way with a small
script, five are deep-equal. The request of two years of 5 CP with a
TIME_WINDOW obligation (2024 and 2025, the default rules and 5 days of any type
in February 2024) differs, and the check failed on it before the rebuild. It
took 1.75 seconds on the frozen engine and 0.19 on `52059dc`. Both return a
plan; outcome, stable explanation and final-state snapshot differ, the
explanation error does not. Eight placements are common, including the five
February ones. The others:
| `52059dc` | Frozen engine (`c86829d`) |
| ----------------------------------------- | ------------------------------------------------------------------------------- |
| `cp-2025` on 2025-05-02 (loss prevention) | `cp-2025` on 2025-10-30 (Samedi Malin) |
| `cp-2025` on 2025-05-30 (loss prevention) | `cp-2025` on 2025-10-31 (Samedi Malin) |
| | earned for Saturday 2025-11-01 on 2025-11-10 (non-working-day gain, supporting) |
Its objective vector, in planning objective order:
| Objective | Direction | Frozen engine | `52059dc` |
| --------------------------- | --------- | ------------: | --------: |
| obligation validity | minimize | 0 | 0 |
| loss prevention | minimize | 0 | 0 |
| **Samedi Malin** | maximize | **1** | **0** |
| Christmas preference | maximize | 2 | 2 |
| public-holiday week value | maximize | 0 | 0 |
| non-working-day gain | maximize | 19 | 20 |
| longest work sequence | minimize | 210 | 210 |
| short work-sequence deficit | minimize | 6 | 6 |
| supporting placements | minimize | 1 | 0 |
Samedi Malin is the first objective to differ, and it is worse: 0 of 1,
unsatisfied with reason `higher-priority`, as for the same request without the
obligation. The Christmas verdict (2 of 5, `capacity`) is unchanged.
Because the seeded requests cannot see the change, the runner's requests above
were compared the same way, from their outcomes and artifacts. In each, the
first objective to differ is Samedi Malin, worse; every later objective is
equal or better:
| Request | Samedi Malin | Non-working-day gain | Longest work sequence | Supporting placements |
| -------------------------- | -----------: | -------------------: | --------------------: | --------------------: |
| `347-3y` | 2 → 0 | 22 → 24 | 418 → 286 | 1 → 0 |
| `347-2y` | 1 → 0 | 15 → 16 | 418 → 286 | 1 → 0 |
| `347x-3y-obligation-after` | 1 → 0 | 26 → 27 | 263 → 263 | 1 → 0 |
Loss prevention, the public-holiday week value and the short work-sequence
deficit are equal in all three. `347-3y-two-obligations` and `347-4y-conflict`
have no plan before the change within the budget, so they cannot be compared.
Every request that became worse on a real objective is listed above: the
multi-year obligation request of the check, and the three runner requests, all
on Samedi Malin.
The frozen engine was then rebuilt from `52059dc` with the documented command,
and `bun test --isolate src/app/services/frozen-engine.spec.ts` passes: 46
tests in 32.9 seconds, 13.6 of them for the six multi-year requests alone.
## The accepted loss
Each loss is a Samedi Malin pattern that funded no obligation and that the
obligation search used to place ahead of loss prevention. Loss prevention now
runs first, as its rule priority says, and spends the CP the pattern needs, so
the plan earns no day: `347-3y` earned two Other days and spent them, and now
plans 15 placements instead of 17. In `347x-3y-obligation-after`, the
occurrence of 1 November 2025 still joins, because its day could fund the
December 2025 obligation, but the best-ranked solution does not use it; the
15 August 2026 occurrence, after the obligation, no longer joins. The same
plans without the obligation already gave this verdict; whether loss
prevention should leave room for such a pattern is a question for its own
stage and for the rule priority, not for the obligation search.
## Tests
`leave-planner-obligation-solutions.spec.ts` covers the rule:
- the two-year request leaves Samedi Malin unsatisfied with reason
`higher-priority` and 10 placements, gives the same verdict as without the
obligation, and plans the same placements as without Samedi Malin (about
2 seconds before the change, 0.4 after);
- an obligation of one Other day after Saturday 1 November 2025, with only
2 CP, is paid by the Samedi Malin day;
- a Saturday pattern earning RTT, which no obligation accepts, funds an
Armistice pattern that earns the Other day the obligation needs; filtering
only direct producers turns it into a planning conflict;
- two obligations in 2025 that 5 CP cannot meet, with Samedi Malin over 2025
and 2026 and a 2-second budget, report `PlanningConflict`. The engine before
the change needs about 4.3 seconds and returns `PlanningIncomplete` at the
budget.
## Left open
- **The enumeration when producers do fund an obligation.** An occurrence that
joins still multiplies the obligation solutions and lifts the solution limit.
In `347x-3y-obligation-after` (three years of 5 CP, Samedi Malin and 5 days
of any type from 2025-12-01 to 2025-12-28), the `obligations` stage still
takes 0.58 seconds, against 0.16 without Samedi Malin, for a producer the
best-ranked solution does not use. More Saturday holidays before more
obligations would grow it as before.
With fuller balances it is already costly. `347x-16-months-obligation-after`,
found by comparing random long requests before the pull request, plans May
2025 to August 2026 with 16 CP and 12 RTT per year, a Christmas preference of
5 CP and an obligation of 4 days of any type from 2026-02-03 to 2026-02-24.
The obligation follows Saturday 1 November 2025, so that occurrence joins. On
the engine of the pull request it takes 11.8 seconds, 10.0 of them in the
`obligations` stage, and peaks at 3.2 GB; without Samedi Malin, 1.2 seconds
and 0.4 GB. The engine before this change did not finish it within an
8-second budget. Bounding this enumeration is a search change of its own.
- **The indicative wait** still does not count obligation solutions (see
[planning duration](../planning-duration.md)); after this change the stage it
cannot predict remains only where a producer funds an obligation.
+247
View File
@@ -0,0 +1,247 @@
# Issue #348: preference stages behind an IF_THEN rule
Record for [issue #348](https://gitea.nessar.fr/nessar/vac-optimizer/issues/348).
With Samedi Malin among the active rules, the preference stages after it
searched far more than the same stages without it. Four exact changes
(`5aa3f39`) keep every completed plan, explanation and final state and cut a
one-year request with the default rules in 2027 from 11.0 to 3.4 seconds. The
changes remove steps, so the frozen engine was rebuilt from that commit
(`23b5ff1`). The three-year request of the issue still spends 12.6 of its 17.2
seconds in the Christmas stage: what remains there is a search the plan needs on
other requests, and the search changes tried below either change nothing or make
the primary request worse. None is committed.
Unless noted, times are single runs of the repro runner
(`src/app/services/frozen-engine/repro-requests.ts`, which names the requests
below) on the development laptop (AMD Ryzen 5 7640U, WSL2, Bun 1.4.3), through
`calculatePlanningAsyncInternal`, with no other heavy process running; before and
after were measured back to back in the same sitting. Times on this laptop drift
by 30 to 40% between sessions.
## The requests
The default rules are loss prevention, Samedi Malin (IF_THEN preference,
Saturday, 2 CP, `auto`, earning 1 Other day), a Christmas preference of 5 days
of any type from 20 December to 3 January, then the five other optimization
presets. `348-default` is the issue's request: three years from 2024 of 25 CP
and 12 RTT per year. `348x-2027-1y-default` is one year from 2027 with the same
balances. 2027 has three Saturday public holidays (1 May, 8 May and 25 December,
inside the Christmas window), and 1 January 2028 is a Saturday too, so every
user with the default rules meets this request's shape in 2027. Without Samedi
Malin, the same year takes 0.5 seconds.
## What the stages do
Every preference stage runs `optimizeRulePlacements`: each pass judges every
single addition, removal, reassignment, move and swap (with move destinations
sampled once more than 24 placements exist), plus the stage's own bundles, keeps
the best candidate by the whole objective vector if it beats the current plan,
and starts again. A stage returns early when every objective of its protected
prefix is at a bound, and a stage after another one reuses its completed scan
when every balance is spent. Neither applied with an enabled IF_THEN rule:
`prefixBounds` has no bound for an IF_THEN preference, and the reuse was
switched off by any IF_THEN rule.
Counters added to the engine at `72e290e` (in another session, so their times
are higher than the table at the end; the counts are deterministic):
`348x-2027-1y-default`
| Stage | Passes | Candidates judged | Improvements kept | Time |
| ------------------------------------------------- | -----: | ----------------: | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------: |
| loss prevention | 37 | 18,840 | 37 additions, then the bound | 0.9 s |
| Christmas | 21 | 87,886 | 18 moves for the placement-date tie-break, 2 moves shortening the longest work sequence | 5.7 s |
| holiday weeks | 14 | 109,273 | 5 bundles completing a holiday week, 1 bundle completing a Samedi Malin pattern, 1 move for gain, 1 for the longest sequence, 5 for the date tie-break | 10.6 s |
| replay of Christmas | 1 | 4,543 | none | 0.2 s |
| each of the four later stages, and the final pass | 1 | 4,543 | none | ~0.12 s |
`348-default`
| Stage | Passes | Candidates judged | Improvements kept | Time |
| ------------------------------------------------- | -----: | ----------------: | ----------------------------------------------------------------------------------------------- | ------: |
| loss prevention | 111 | 131,344 | 111 additions, then the bound | 4.1 s |
| Christmas | 45 | 1,859,220 | 42 moves for the placement-date tie-break, 2 moves shortening the short-sequence deficit | 25.7 s |
| holiday weeks | 31 | 168,153 | 27 bundles completing a holiday week, 1 move for the longest sequence, 2 for the date tie-break | 2.3 s |
| replay of Christmas | 1 | 41,912 | none | 0.6 s |
| each of the four later stages, and the final pass | 1 | 41,912 | none | ~0.37 s |
The Christmas window is full (5 of 5) when its stage starts in both requests,
and Samedi Malin is 2 of 3 in 2027 and 0 of 2 in the issue's request, so the
stage has no bound. Its improvements are plateau moves: a bridge day moves from
a Monday to the previous Friday, or the other way, keeping every objective and
lowering the placement-date tie-break. In 2027 its 87,886 candidates split as
73,815 moves, 12,600 swaps, 777 removals, 505 reassignments and 189 additions.
Measured against the best candidate of their pass, about 17,000 were worse on a
protected objective, 39,522 on non-working-day gain, 19,183 on the longest work
sequence and 1,586 on the short-sequence deficit; about 10,500 were equal up to
the tie-breaks.
In the 2027 holiday-week stage, 7.6 of its 10.6 seconds went to building
bundles rather than judging them. One week did it: the week of Monday 1 November
was still incomplete in six passes, and in four of them the search tried 14,000
to 21,000 allocations before one was accepted (108,202 search nodes and 69,598
complete allocations over the six passes, 30,308 of them invalid, 14,240 worse
on Christmas, 13,844 worse on Samedi Malin and 11,200 worse on holiday weeks).
Donors are ranked once per pass, and the first ones were the Monday and Tuesday
of the complete week of 14 July: every allocation that used them broke a week
worth 3 to complete one worth 1, and the search enumerated all of them before
moving on.
Is the work needed? The later stages repeat a scan whose answer is already known.
The holiday-week search reaches the allocation it accepts today, only after
redoing the rejected ones every pass. The Christmas stage's plateau moves are not
always undone: without them (search changes below) the 2027 plan ends with a
longest work sequence of 25 or 35 working days instead of 24, while the issue's
request and the 2025 year end with the same objective values.
## The exact changes
`5aa3f39` makes four changes. Each keeps the same sequence of states for every
calculation that runs to its end.
- **Judge generic candidates on what finalizing cannot change.** The generic
scan reads no answer from a removal, reassignment, move or swap: it only keeps
a candidate whose whole vector beats the best one so far, and only such a
candidate is retained for cancellation. Such a candidate is now first compared
with the best one on the objectives that finalizing cannot change (calendar
objectives, calendar preferences, leave balances when earning is settled, and
the tie-breaks: placement dates never change, balance expiries only with
earned leave), and dropped when its first difference is worse or it has none.
It no longer pays for finalizing. Supporting placements are rewritten when
finalizing, so a candidate equal up to that objective is still finalized.
- **Stop a bundle that no completion can accept.** A holiday-week or time-off
period bundle fills its remaining target dates one at a time, each with an
addition or a donor moved from outside the targets, and finalizing never moves
or retypes a placement. So every protected objective has an optimistic value
over all completions of a partial bundle: loss prevention at most one day lower
per open date (earned balances counted as zero), a TIME_WINDOW preference with
every open date counted in its window, an IF_THEN preference with every open
date counted as satisfied, holiday weeks with every open date filled. When the
first optimistic value that differs from the stage's baseline is worse, every
completion is rejected, and the search backtracks. Any other objective before
that point stops the check.
- **Reuse a completed generic scan with an IF_THEN rule.** When every balance is
spent, the scan has no addition, and a candidate counts only if its whole
vector beats the current plan, which no stage index changes: a whole-vector
improvement is never worse on any prefix. The candidates themselves (moves,
swaps, reassignments, removals) do not depend on the stage either. So a scan
that found nothing on a state finds nothing on the same state at a later
stage, IF_THEN rule or not. Bundles still run.
- **Find the period of an earned entitlement by binary search.** Checking that
earning is settled looks up the time-off period holding a pattern's dates; it
scanned every period and built each one, and now searches the disjoint,
ordered period ranges.
The frozen-engine check gains the 2027 request (seven fixed requests), which
exercises all four.
## Times
Back to back, before at `72e290e` and after at `9d64f43`; every after plan has
the same outcome, explanation and final state as before.
| Request | Before | After | Largest stages after |
| ----------------------- | -----: | -----: | ------------------------------------------ |
| `348x-2027-1y-default` | 11.0 s | 3.4 s | Christmas 1.7 s, holiday weeks 0.7 s |
| `348-default` | 22.6 s | 17.2 s | Christmas 12.6 s, loss prevention 2.8 s |
| `348x-2027-2y-default` | 29.8 s | 10.5 s | Christmas 6.0 s, holiday weeks 2.2 s |
| `348-samedi` | 8.1 s | 5.2 s | loss prevention 4.0 s, holiday weeks 0.8 s |
| `348-presets` | 3.1 s | 3.1 s | loss prevention 1.7 s |
| `348-christmas` | 3.0 s | 3.0 s | loss prevention 1.8 s |
| `348x-2027-1y-nosamedi` | 0.55 s | 0.47 s | |
In `348-default` the four later stages no longer scan (each took about 0.26 s
before). The runner requests of #347, #349 and #350 plan identically too, in the
same or less time: for instance `349x-christmas-first-deferred` 3.0 to 0.9 s,
`349x-loss-first-deferred` 2.4 to 0.5 s and `350` 2.2 to 1.1 s.
## Comparison record
Before the rebuild, with the frozen engine built from `52059dc`:
```sh
bun src/app/services/frozen-engine/compare-engines.ts small 280000 5000
```
| Result | Requests |
| ------------------ | -------: |
| Identical | 5,000 |
| Any other category | 0 |
The seven fixed requests were deep-equal as well, and so were the outcomes,
explanations and final states of 25 runner requests of #347, #348, #349 and
#350: `349-samedi-first`, the four `349x` requests, `349-loss-first`,
`349-samedi-first-2y-5cp`, `350`, the ten `347` requests, and `348-presets`,
`348-christmas`, `348-samedi`, `348-default`, `348x-2027-1y-default`,
`348x-2027-1y-nosamedi` and `348x-2027-2y-default`. No request is worse on any objective.
Of the 500 cancelled runs, 48 run fewer steps, and 20 differ: 10 only in their
step count (seeds 280220, 280730, 281020, 281220, 282060, 283680, 283780, 284080,
284380, 284600, cancelled after the last step) and 10 cancelled at another point
of the calculation (280380, 280560, 281040, 281430, 282660, 283010, 283120,
283930, 284060, 284310). The `loaded-year` sample was not run.
The frozen engine was then rebuilt from `5aa3f39`, and
`bun test --isolate src/app/services/frozen-engine.spec.ts` passes.
## Benchmark
The planner benchmark had no scenario with Samedi Malin or the Christmas window.
`default rules` (`9d64f43`) plans the 2027 year above through the in-process
calculation service:
| Engine | Mean planning | Ratio to calibration |
| ------------------ | ------------: | -------------------: |
| before (`72e290e`) | 9.86 s | 2.79 |
| after | 2.86 s | 0.81 |
Its multiplier is 1.25, the usual headroom of about 1.5 times the measured
ratio, so the former cost fails the gate. The protocol takes about 9 seconds
longer (48 seconds in all on the laptop).
## Tests
No regression test bounded by a deadline separates the two engines with wide
margins: the exact changes make the requests found at most 5 times faster, and a
test must pass on a runner several times slower than the laptop. The guards are
the 2027 request in the differential check, which fails on any change to its
plan, and the benchmark gate above, which judges time relative to the runner.
## Search changes tried, not committed
Each was measured against the exact engine.
- **A bound for an IF_THEN preference** (every occurrence that has an eligible
pattern complete) in the stage's early return: no effect on either request,
since Samedi Malin is 2 of 3 and 0 of 2 when the Christmas stage starts. The
5,000 seeded requests were not compared.
- **The early return ignoring an IF_THEN preference ahead of the stage:**
`348-default` takes 4.9 s with the same objective values (24 placements fund
the same dates from the other balance, as triage found) and the 2025 year
0.4 s instead of 1.5 s, with the same objective values. But
`348x-2027-1y-default` gets worse and slower: its longest work sequence is 25
working days instead of 24, in 6.8 s. The two-year 2027 request is worse on the
placement-date tie-break only, in 3.8 s instead of 10.3 s. The 5,000 seeded
requests are identical; of the seven fixed requests, the two one-year requests
differ.
- **Preference stages accepting no tie-break-only improvement** (tie-breaks left
to the final pass): 2.0 s for 2027 but with a longest work sequence of 35
instead of 24, and over the seeded requests 9 worse on a real objective, 1
better, 17 with the same objective values and 1 worse on a tie-break only.
## Left open
- **The Christmas stage of `348-default`** still runs 45 passes of 41,912
candidates for plateau moves (12.6 s). Skipping them keeps the objective values
on that request but not on the 2027 year; a narrower rule would need to know
when plateau moves can still lead to a real improvement.
- **The Samedi Malin stage itself** can be slow: one year from 1 April 2027 with
18 CP and 9 RTT and only loss prevention, Samedi Malin and holiday weeks takes
28 seconds, 27.7 of them in the Samedi Malin stage, before and after these
changes. With the default rules the same balances take 1.9 s. Not
investigated.
- **Supporting placements** are rewritten when finalizing, so a generic
candidate equal on every objective before them is still finalized; about
10,500 of the 87,886 candidates of the 2027 Christmas stage.
- **The indicative wait** weighs each IF_THEN rule 4, fitted on the former cost;
see [Planning duration](../planning-duration.md).
+231
View File
@@ -0,0 +1,231 @@
# Issue #349: let loss prevention finish behind another preference
Record for [issue #349](https://gitea.nessar.fr/nessar/vac-optimizer/issues/349).
With a preference ahead of loss prevention in the rule priority, the loss
prevention stage could search without finishing and grow memory without bound
once every at-risk day was placed. The stage now skips the relocation chains that cannot
improve the protected prefix. Every calculation that runs to its end keeps its
outcome, stable explanation and final-state snapshot. The change removes steps,
so the frozen engine was rebuilt under
[ADR 0010](../adr/0010-rank-obligation-solutions-before-preferences.md): five
of the 500 cancelled runs of the
[differential check](README.md#frozen-engine-differential-check) stop at
another point.
Unless noted, times are single runs of the repro runner
(`src/app/services/frozen-engine/repro-requests.ts`, which names the requests
below) on the development laptop (AMD Ryzen 5 7640U, WSL2, Bun 1.4.3), through
`calculatePlanningAsyncInternal`, with no other heavy process running.
## Cause
The request of the issue: one year from 2025-01-01, calculated on 2025-01-01,
25 CP and 12 RTT available on 1 January and expiring on 31 December, and the
rules Samedi Malin (IF_THEN preference, Saturday, 2 CP, `auto`, earning 1 Other
day), loss prevention, then the five other optimization presets.
The loss prevention stage places every at-risk day in about half a second. It
then keeps iterating: each pass scans single additions, removals, moves and
swaps, and when that scan finds no improvement of the protected prefix (Samedi
Malin, then loss prevention), it searches relocation chains
(`relocateForAddition`) for every balance with days left, from every occupied
date. Here the only such balance is the earned leave entitlement of Samedi
Malin for Saturday 1 November, which is not at risk. A chain gives the balance
an occupied date and moves the displaced placement to another date, which may
displace another one, until a free date ends it. The candidate is an addition,
so it is accepted only if it strictly improves the protected prefix.
Nothing can: Samedi Malin is complete and loss prevention is at 0. Every chain
is therefore rejected, and the depth-first search enumerates every simple chain
through the 37 occupied dates. Its failure memo is keyed on the visited dates
and on the whole plan, which differ from one path to the next, so it rarely
matches. An instrumented run of the engine before the fix, stopped after
10 seconds, was still inside the first of these searches: 259,227 calls,
chains 29 dates deep, no accepted candidate, 106,294 memo hits, and 152,906
memo keys holding 413 million characters. Those keys live until the search
returns, so memory grows with the search:
| Request (30-second budget, before the fix) | Peak resident memory (`VmHWM`) |
| ------------------------------------------ | -----------------------------: |
| `349-samedi-first` | 2.2 GB |
| `349x-christmas-first-deferred` | 2.5 GB |
| `349x-holiday-weeks-first-deferred` | 2.8 GB |
During triage, the request without a budget reached 14 GB in 14 minutes.
The search is exponential by design: it is exhaustive over chains and stops at
the first accepted one. The stage does not reach it with loss prevention first,
because it returns as soon as every objective of its prefix is at its bound,
and a prefix of loss prevention alone is at its bound once nothing at risk is
left. A preference ahead of it has no bound in that early return, so the stage
goes on to the chains. Any balance with days left once the at-risk ones are
placed triggers it: an earned leave entitlement, or a deferred balance (a CP day
available from 2025-06-01 and expiring on 2026-05-31) behind a Christmas
preference or the holiday-week preset.
## What the stage may still do
Once loss prevention is at 0, its own objective cannot improve. An addition is
accepted only through a strict improvement of the protected prefix, so it must
improve an earlier preference. Moves, swaps and reassignments that keep the
prefix and improve a lower objective or a tie-break are still accepted, and
they do real work: the triage found that returning from the stage as soon as
nothing at risk is unplaced moves the August 2026 Samedi Malin pattern of the
two-year request of 5 CP per year, and swaps the funding of two November 2025
dates. A deferred balance needs no ordinary placement, but stays available to
later rules and supporting placements, so the stage must not use it up either.
The fix therefore removes only the chains, and only when no chain can be
accepted. A chain keeps every occupied date and adds one free date, and
finalizing a candidate never moves or retypes a placement. Before searching
chains, the loss prevention stage checks each objective of its prefix:
- an objective already at a value no plan can beat cannot improve: a minimized
optimization at 0 (every measure is a non-negative count, quantity, length or
distance), a TIME_WINDOW preference at its requested quantity, an IF_THEN
preference with every occurrence that has an eligible pattern complete, or a
holiday-week maximum with every week complete;
- an objective that depends only on occupied dates (public-holiday weeks,
time-off periods, work sequences, a TIME_WINDOW preference of any type) can
improve only if adding one free date improves it; the stage tries each free
working date on a copy of the plan;
- any other objective keeps the chain search as before.
If no objective can improve, the stage skips the chains. Every candidate it
skips is one the old stage would have rejected, so a calculation that runs to
its end goes through the same states. Only rejected candidates are lost, and
with them their cancellation retention and their steps: a calculation
cancelled after a fixed number of steps can stop at another point. With loss
prevention first, the stage only reaches the chains while something at risk is
unplaced, so the check returns at once and the stage runs exactly as before,
step for step.
A simpler rule, skipping the chains whenever loss prevention is at 0, also
lets the stage finish on every request below, but it is a search change: over the 5,000 seeded
requests, seed 283938 lost 2 days of non-working-day gain, a preference ahead
of loss prevention that a relocation chain had improved.
## Times
Before is the engine at the start of the branch (`2d912e8`), with a 30-second
budget; after is `c86829d`.
| Request | Before | After | Peak memory after |
| ----------------------------------- | ------------------------------------ | ------------ | ----------------: |
| `349-samedi-first` | `PlanningIncomplete`, deadline, 30 s | Plan, 1.46 s | 114 MB |
| `349x-christmas-first-deferred` | `PlanningIncomplete`, deadline, 30 s | Plan, 2.70 s | 126 MB |
| `349x-holiday-weeks-first-deferred` | `PlanningIncomplete`, deadline, 30 s | Plan, 0.34 s | 111 MB |
All three stopped in the loss prevention stage before. After, that stage takes
0.56, 0.62 and 0.09 seconds. Most of the Christmas request's time is the
holiday-week stage (1.96 s), as with loss prevention first: the same balances
with loss prevention first (`349x-loss-first-deferred`) take 2.20 s, 1.80 s of
it in that stage. The issue reported 100 seconds without a plan for the first
request on another machine.
With loss prevention first, `349-loss-first`, `349x-loss-first-deferred`,
`348-default` (120-second budget) and `350` plan exactly as before: the
outcomes, explanations and final states, without timings, are equal on the
frozen engine built from `ea2feaf` and on `c86829d`.
### Other preferences ahead of loss prevention
A survey over rule orders, distinct from the three named requests above: the
same year of 25 CP and 12 RTT, with one rule moved ahead of loss prevention and
the default rules after it (Samedi Malin, the Christmas preference, then the
presets), with and without the deferred CP day, and a 15-second budget. Its
requests carry more rules than the named ones, so its times are not theirs:
| First rule | Deferred day | Before | After |
| --------------------------- | ------------ | --------------------------- | -------------------------------------------- |
| Samedi Malin | no | deadline in loss prevention | Plan, 2.6 s |
| Samedi Malin | yes | deadline in loss prevention | Plan, 5.4 s |
| Christmas preference | no | Plan, 1.2 s | Plan, 1.0 s |
| Christmas preference | yes | deadline in loss prevention | Plan, 3.0 s |
| holiday weeks | no | Plan, 0.6 s | Plan, 0.5 s |
| holiday weeks | yes | deadline in loss prevention | Plan, 0.7 s |
| non-working-day gain | no | Plan, 5.2 s | Plan, 4.4 s |
| non-working-day gain | yes | Plan, 4.0 s | Plan, 4.0 s |
| longest work sequence | no | Plan, 9.2 s | Plan, 9.2 s |
| longest work sequence | yes | deadline in loss prevention | deadline in non-working-day gain (see below) |
| short work-sequence deficit | no | Plan, 1.1 s | Plan, 0.9 s |
| short work-sequence deficit | yes | deadline in loss prevention | Plan, 1.1 s |
| supporting placements | no | Plan, 1.6 s | Plan, 1.3 s |
| supporting placements | yes | deadline in loss prevention | Plan, 3.7 s |
Loss prevention finishes in every row, in at most 1.9 seconds. The seven
requests that finished before plan identically on the frozen engine built from
`ea2feaf` and on `c86829d` (outcome, explanation and final state, without
timings).
## Comparison record
Before the rebuild, with the frozen engine built from `ea2feaf` still in place:
```sh
bun src/app/services/frozen-engine/compare-engines.ts small 280000 5000
```
| Result | Requests |
| ------------------ | -------: |
| Identical | 5,000 |
| Any other category | 0 |
The frozen engine took 8.5 seconds and `c86829d` 7.6 seconds. The six
multi-year requests of the check, compared the same way with a small script,
are deep-equal: 1.8, 1.9, 0.6, 1.7, 0.4 and 1.9 seconds on `c86829d`, against
3.6, 3.3, 1.4, 3.3, 0.6 and 3.4 on that frozen engine. No request is worse on
any objective.
The cancelled asynchronous comparisons cancel both engines after the same
number of steps, and compare that number. Of their 500 seeds (280000 to 284990,
every tenth), ten run fewer steps on `c86829d`, and five of them differ:
| Seed | Cancelled after (steps) | Steps without cancellation | Difference |
| ------ | ----------------------: | -------------------------: | ------------------------------------------------------------------------------ |
| 280410 | never | 2,238 → 1,962 | step count only |
| 282230 | never | 1,226 → 1,225 | step count only |
| 281850 | 955 | 1,008 → 964 | cancelled later: last completed stage short-sequence deficit → loss prevention |
| 282840 | 1,036 | 1,121 → 1,081 | cancelled later: last completed stage loss prevention → `tw0` preference |
| 284010 | 1,692 | 2,292 → 1,713 | cancelled later: last completed stage `composed` → loss prevention |
The `loaded-year` sample was not run: its generator always puts loss
prevention first, where the stage runs as before.
The frozen engine was then rebuilt from `c86829d` with the documented command,
and `bun test --isolate src/app/services/frozen-engine.spec.ts` passes. The
bundle also takes up the exact performance changes merged since `ea2feaf`, so
the check now runs in about 36 seconds instead of 48, 17 of them for the
multi-year requests instead of 27.
## Tests
`optimization-rule.spec.ts` plans two requests from 1 September to the end of
2025, with 8 CP and 4 RTT expiring on 31 December and a 5-second budget:
Samedi Malin, loss prevention, then non-working-day gain; and a Christmas
preference of 5 days of any type, loss prevention, and one deferred CP day. Each
must return a plan with no unplaced at-risk leave and the first preference
satisfied; the earned day must be placed by the later rule as a supporting
placement, and the deferred day must stay unplaced. They take about 0.2 and
0.1 seconds; on the engine before the fix both hit the 5-second budget, and
the same requests ran past 20 seconds without a plan on the frozen engine
built from `ea2feaf`.
## Left open
- **Preferences ahead of loss prevention that are not at their best and do not
depend only on occupied dates**: an incomplete IF_THEN preference, an
unfilled typed TIME_WINDOW preference, or supporting placements above 0. The
stage still searches chains there, as before. An optimistic bound for those
(counting every occupied date as the right leave type) would extend the check.
- **The same chains in a TIME_WINDOW stage.** A window preference below its
quantity searches chains in the same way. With Samedi Malin first, 2026, only
RTT at risk and one deferred CP day, the Christmas stage after loss
prevention still runs past 15 seconds, on `c86829d` and on the frozen engine
built from `ea2feaf`.
- **Slow preference stages after loss prevention.** With the longest work
sequence first and the deferred day, loss prevention now finishes in
0.35 seconds, and the holiday-week stage then takes about 13 seconds before
the non-working-day gain stage reaches the 15-second budget. The holiday-week
stage also dominates the Christmas row above. Both belong with
[#348](https://gitea.nessar.fr/nessar/vac-optimizer/issues/348).
+111
View File
@@ -0,0 +1,111 @@
# Issue #350: rebuild the frozen engine and compare multi-year requests
Record for [issue #350](https://gitea.nessar.fr/nessar/vac-optimizer/issues/350).
The frozen engine of the
[differential check](README.md#frozen-engine-differential-check) planned a
three-year request differently from the current engine. It is rebuilt from the
commit that introduced the difference, and the check now also compares six
fixed multi-year requests with the default rules ([#348](issue-348.md) later
added a seventh). No planning behavior changes.
## Cause
The frozen engine was rebuilt for #302 from `8168137`. Commit `ea2feaf`
(`fix(planning): stop IF_THEN patterns at a weekday public holiday`) later
changed IF_THEN patterns on purpose: a weekday public holiday now ends a side of
the pattern, where the planner used to skip it. Saturday 8 May 2027 follows
Ascension (Thursday 6 May), so the frozen engine still completed its Samedi
Malin pattern with Wednesday 5 and Friday 7 May, across Ascension, which the
Samedi Malin entry of `CONTEXT.md` rules out. The commit left the bundle alone
because the 5,000 seeded requests planned identically, and they still do. Their
horizons last at most ten weeks, which is why the check could not see it.
Run on the request of the issue, the engine at `ea2feaf^` plans like the old
frozen engine and the engine at `ea2feaf` plans like develop at `2dbd232`.
## Comparison before the rebuild
With the old frozen engine still in place, on the development laptop (AMD Ryzen
5 7640U, WSL2, Bun 1.4.3), where every time of this record was measured:
```sh
bun src/app/services/frozen-engine/compare-engines.ts small 280000 5000
```
| Result | Requests |
| ------------------ | -------: |
| Identical | 5,000 |
| Any other category | 0 |
The old frozen engine took 8.5 seconds over the 5,000 requests and the current
engine 7.5 seconds. The rebuild therefore changes no seeded plan.
## The difference on the request of the issue
Three years from 2025-01-01, calculated on 2025-01-01, with 5 CP per year
(`cp-2025`, `cp-2026`, `cp-2027`, each available on 1 January and expiring on
31 December) and the default rules: loss prevention, Samedi Malin, a Christmas
preference of 5 days of any type from 2025-12-20 to 2026-01-03, then the five
other optimization presets. Both engines return a plan with 17 placements, and
13 of them are identical. The other four:
| Current engine | Old frozen engine |
| ---------------------------------------------------------- | ---------------------------------------------------------- |
| `cp-2027` on 2027-05-05 (loss prevention) | `cp-2027` on 2027-01-04 (loss prevention) |
| `cp-2027` on 2027-05-10 (loss prevention and Samedi Malin) | `cp-2027` on 2027-05-05 (loss prevention and Samedi Malin) |
| earned for Saturday 2027-05-08 on 2027-10-29 (supporting) | earned for Saturday 2027-05-08 on 2027-05-18 (supporting) |
| earned for Saturday 2027-05-01 on 2027-11-12 (supporting) | earned for Saturday 2027-05-01 on 2027-10-29 (supporting) |
The outcome, the stable explanation and the final-state snapshot differ; the
explanation error does not. In the final metrics the old frozen engine's
non-working-day gain is 30 and the current engine's 27, and its longest time-off
period is 9 days against 10. The current engine's plan is the intended one.
## The new requests
`src/app/services/frozen-engine/multi-year-planning-requests.ts` builds six
fixed requests, all with explicit calculation dates and Christmas window dates
and nothing read from the clock. `frozen-engine.spec.ts` compares each one like
a seeded request: outcome, stable explanation, explanation error and final-state
snapshot strictly deep-equal, with the request printed as JSON on a failure. The
default rules are loss prevention, Samedi Malin (IF_THEN preference, Saturday,
2 CP, `auto`, earning 1 Other day), the Christmas window preference, then the
five other presets.
| Request | Current (s) | Rebuilt frozen (s) |
| ----------------------------------------------------------------------- | ----------: | -----------------: |
| three years from 2025 of 5 CP (the request of this issue) | 1.79 | 3.92 |
| two years from 2024 of 5 CP, default rules and a TIME_WINDOW obligation | 2.17 | 3.50 |
| two years from 2025 of 5 CP, Samedi Malin before loss prevention | 0.66 | 1.49 |
| one year from 2025 of 25 CP and 12 RTT | 1.78 | 3.67 |
| three years from 2026 of 5 CP | 0.39 | 0.69 |
| one year from 2025-09-01 of 10 CP and 4 RTT, balances of 2025 and 2026 | 2.07 | 3.78 |
The obligation request adds a TIME_WINDOW obligation of 5 days of any type from
2024-02-01 to 2024-02-28, after the Christmas preference: the obligation search
with a rule that earns leave of
[#347](https://gitea.nessar.fr/nessar/vac-optimizer/issues/347). The third
request puts Samedi Malin ahead of loss prevention, the order of
[#349](https://gitea.nessar.fr/nessar/vac-optimizer/issues/349), with 5 CP
per year so that it finishes quickly. The fourth is a year with realistic
balances. The last two use another start year and a horizon that starts in
September. The times are single runs of each request on each engine in one Bun
process, with the rebuilt frozen engine. All six requests are deep-equal on the
two engines.
## The new test against the previous bundle
Before the rebuild, the new test group ran against the old frozen bundle
(`bun test --isolate src/app/services/frozen-engine.spec.ts -t multi-year`):
five of the six tests passed, and the test for the three-year request of this
issue failed, printing the request and a diff of outcome, explanation and final
state. The four placements above are the ones that differ.
## Added run time
`bun test --isolate src/app/services/frozen-engine.spec.ts` ran its 46 tests in
48 seconds, and the same command with `--config=bunfig.coverage.toml` took 57
seconds. In the report of the first run, the six multi-year tests take 27.1
seconds, the 25 seeded tests and 13 cancelled ones 20.0 seconds. The group
therefore adds about 27 seconds, which covers both engines planning each
request once.
+1 -1
View File
@@ -24,7 +24,7 @@ remain manual deployment options.
| `policy` | Tests the policy and publisher with Bun, then validates the checked-out commit, GitFlow, PR title, commits, and stable release version. |
| `validate` | Runs ESLint, Prettier (application, `scripts/ci-*.mjs` and workflow files) and `bun check` type checks of application and test code, all on Bun with the frozen lockfile. |
| `test` | Runs functional coverage with `bun test --isolate` (line coverage only), converts it to HTML and Cobertura, and uploads coverage for seven days even on failure. |
| `benchmark` | Required seven-scenario protocol (one warm-up, two measured repetitions) outside coverage in a container limited to 3 GiB. It times the frozen engine on `two years` (best of three) before and after the protocol, and fails any scenario whose mean planning time exceeds its multiplier times that calibration; the 240-second timeout is only a hang guard. |
| `benchmark` | Required eight-scenario protocol (one warm-up, two measured repetitions) outside coverage in a container limited to 3 GiB. It times the frozen engine on `two years` (best of three) before and after the protocol, and fails any scenario whose mean planning time exceeds its multiplier times that calibration; the 240-second timeout is only a hang guard. |
| `build` | Builds the client-only Angular production bundle (the only check of Angular templates; `bun check` does not replace it) and the Bun static-server bundle, and retains `dist` for seven days. |
| `security` | Runs Semgrep JavaScript/TypeScript SAST and Trivy dependency/secret scans; retains SARIF reports for seven days. Scanner execution must succeed; findings remain reports rather than a new severity gate. The scanners are not project JavaScript, so this job installs no Bun. |
| `images` | Publishes branch/SHA images after required validation, including the benchmark, or promotes an existing SHA image for a stable tag, running the publisher with Bun. Runs only for pushes and same-repository PRs. |
+4 -1
View File
@@ -41,7 +41,10 @@ its non-negative earned quantity times `D / 365.25` as a rough allowance.
`R` starts at 1. Each enabled IF_THEN rule adds 4: a rule that can earn leave
makes the planner judge every candidate plan in full, and the default Samedi
Malin rule made the measured requests about 3.6 times slower. Every other
Malin rule made the measured requests about 3.6 times slower. That weight was
fitted before the exact changes of #348, which make some requests with an
IF_THEN rule up to three times faster (a default year in 2027 from 11.0 to 3.4
seconds) and leave others almost unchanged; it needs a follow-up refit. Every other
enabled rule adds `max(1, placeDays / 3)` times 0.5 for an obligation or 0.15
for a preference. TIME_WINDOW rules wholly outside the horizon contribute
nothing. These weights approximate extra search, rather than solving
+22 -3
View File
@@ -239,9 +239,28 @@ full-vector expiry/date pass still run. Other configurations and preference orde
retain their search. This schedules lower priorities later; it does not claim an
exhaustive full-vector search in the bounded stage.
When every balance is exhausted and there is no active IF_THEN rule, a complete generic
iteration that finds no full-vector improvement can be reused for the identical ordered
state at a later preference. Explicit balance assignments use the same dates, validity,
A generic removal, reassignment, move or swap matters only if it beats the best
candidate of its pass, so it is first compared with that candidate on the objectives and
tie-breaks that finalizing cannot change, and is not finalized when it provably cannot
beat it. A holiday-week or time-off-period bundle backtracks as soon as an optimistic
value of its protected prefix over every completion of the partial bundle is worse than
the stage's baseline. Both are exact ([#348](benchmark/issue-348.md)).
Wherever a sum/minimize unplaced-quantity rule sits in the order, its stage
searches augmenting chains only while one could still strictly improve its
protected prefix. A chain keeps every occupied date and adds one free date, so
the stage skips it when every prefix objective is either at a value no plan can
beat (a minimized optimization at zero, a time-window preference at its
quantity, an IF_THEN preference with every occurrence that has an eligible
pattern complete, a holiday maximum with every week complete) or depends only on
occupied dates and no single free date would improve it. This is exact for every
calculation that runs to its end; it removes steps, so a cancelled calculation
can stop at another point ([#349](benchmark/issue-349.md)).
When every balance is exhausted, a complete generic iteration that finds no full-vector
improvement can be reused for the identical ordered state at a later preference, with or
without an active IF_THEN rule: without additions, a candidate counts only if it improves
the full vector, whatever the stage. Explicit balance assignments use the same dates, validity,
provenance and configured move sampling regardless of the current rule. Rule-specific
bundles still run, and any balance, placement, supporting, provenance or activation change
invalidates reuse. Bound returns and interrupted iterations never admit a state. Reuse
+21 -2
View File
@@ -12,7 +12,26 @@ The statistics page requested by #3 and the popup requested by #29 describe the
Provide one statistics popup opened from the calendar. It summarizes the most recent calculated valid plan, including a valid plan retained by a cancelled or interrupted calculation, using that calculation's submitted inputs and Europe/Paris calendar date.
The popup presents nine metrics, a breakdown of earned leave by generating rule, and dated warnings for weeks with one workday. Its figures describe the calculated result and become available with the valid outcome, independently of calculation-trace delivery. Input edits and trace or counterfactual exploration leave those figures attached to the producing calculation until a new outcome arrives.
The popup presents nine metrics, a breakdown of earned leave by generating rule, and dated warnings for weeks with one workday. The figures displayed today are those of the [2026-11-14 review](#review-of-2026-11-14-displayed-figures); the metric definitions below still hold. Its figures describe the calculated result and become available with the valid outcome, independently of calculation-trace delivery. Input edits and trace or counterfactual exploration leave those figures attached to the producing calculation until a new outcome arrives.
## Review of 2026-11-14: displayed figures
[Issue #362](https://gitea.nessar.fr/nessar/vac-optimizer/issues/362) reviewed the summary tiles and the popup with the maintainer. A figure stays only if it informs a decision; the unit sits next to the number, never in the label; a tile and the popup use the same label for the same figure.
| Displayed figure | Definition |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Leave days placed | Newly placed leave days, shown out of the leave days the plan could use: the placements plus the unplaced days. |
| Unplaced leave days | Total quantity of the remaining balances of the plan. The lost part is the quantity whose balance is at risk or an unavoidable expiry; a deferred balance is kept for later and is not lost. These equal the figures of the configuration panel's remaining-days warning. |
| Total days off | Sum of the calendar-day durations of the planned time-off periods, with the non-working-day gain as its detail. The gain is no longer presented as days "gained": those weekends and public holidays are part of the time off, not a net benefit. |
| Time-off periods | Number of planned time-off periods holding a leave placement or a declared non-working day, as listed by the time-off periods disclosure, with the longest time-off period length as its detail. |
| Longest stretch without leave | Longest work-sequence length, in working days. |
| Bridged public holidays | Public holidays connected to a weekend, out of the distinct Monday-to-Friday public holidays of the horizon plus any connected holiday outside it, so the part never exceeds the whole. |
| Earned leave | Unchanged definition. Absent when nothing is earned; a single earning rule is named without repeating the total. |
| Weeks with one workday | Unchanged definition. Shown as a warning with each week and its lone workday when there is at least one; absent otherwise. This was delivered by #69 on `main` only and was brought to `develop` by #362. |
The three summary tiles are leave days placed (with the unplaced and lost days), total days off, and the longest stretch without leave.
No longer displayed: the average work-sequence length and the average time-off period length. An average over a handful of sequences or periods guided no decision. Both remain planner metrics. A ratio of days off per leave day was considered and rejected: it rises mechanically with any Friday placement and flatters without informing.
## User Stories
@@ -82,4 +101,4 @@ Use behavior-level tests that assert returned planning facts and user-visible fi
- Domain definitions are maintained in [CONTEXT.md](../CONTEXT.md). Relevant architectural constraints are [server-side planning for every device](adr/0011-server-side-planning-for-every-device.md), which superseded the [personal client-side planner](adr/0002-personal-client-side-planner-for-now.md), [separate calculation outcome and trace](adr/0004-stable-explanation-original-trace-counterfactual.md), [selected horizons and cancellation](adr/0006-user-selected-horizons-and-cancellable-calculations.md), and [declared days and reported balances](adr/0007-declared-days-and-reported-balances.md).
- **Current integration gaps:** The inspected outcome exposes placements, periods, remaining balances, and several quality metrics, but no dedicated gross earned-leave summary or fixed calculation date. Remaining balances omit fully consumed entitlements. Declared-day support is in progress in the working tree: declarations are carried with outcomes, while the inspected period and work-sequence calculations still use placements alone. Coordinate with #13's finalized semantics before relying on those values; avoid a second conflicting calendar model in the popup.
- **Proposed empty-value convention, not explicitly confirmed:** Counts show 0 when there are no qualifying items. An average with no samples, or longest time-off period length when no periods exist, shows "—". The existing longest work-sequence length remains 0 when there are no work sequences. Empty samples should remain distinguishable from a measured zero in the underlying data.
- **Remaining presentation choices:** Exact decimal precision for averages, metric layout, and whether eligible rules with zero earnings receive breakdown rows were not decided. These do not change the agreed counting or date rules. Use existing presentation conventions and keep any selected defaults explicit during implementation.
- **Remaining presentation choices:** Metric layout and whether eligible rules with zero earnings receive breakdown rows were not decided. Statistics show at most one decimal in the active locale (#353). These do not change the agreed counting or date rules. Use existing presentation conventions and keep any selected defaults explicit during implementation.
+2 -2
View File
@@ -45,8 +45,8 @@
},
"devDependencies": {
"@analogjs/vite-plugin-angular": "^2.7.5",
"@angular/build": "22.2.3",
"@angular/cli": "22.2.3",
"@angular/build": "22.2.7",
"@angular/cli": "22.2.7",
"@angular/compiler-cli": "22.2.3",
"@eslint/js": "^10.0.1",
"@types/bun": "1.4.3",
+95 -97
View File
@@ -110,108 +110,106 @@ describe('Application Settings', () => {
await createApp(startJob);
}
it('keeps random starting balances unsaved through calculation and restores the first edited list', async () => {
it.each([
['absent', null],
['unreadable', '{'],
])(
'starts with nothing to plan when saved balances are %s, then calculates once a balance is added',
async (_, saved) => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date(2026, 9, 4, 12));
vi.spyOn(console, 'warn').mockImplementation(() => {});
if (saved === null) localStorage.removeItem('leaveBalances');
else localStorage.setItem('leaveBalances', saved);
await revisitApp(true, startInProcessJob);
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('app-day-input')).toBeNull();
expect(localStorage.getItem('leaveBalances')).toBeNull();
expect(localStorage.getItem('unrelated.entry')).toBe('keep this value');
expect(root.querySelector('#leave-balances-empty')?.textContent).toContain(
'No leave balance yet',
);
const button = root.querySelector<HTMLButtonElement>('.calculate-button')!;
expect(button.disabled).toBe(true);
expect(button.getAttribute('aria-describedby')).toBe('leave-balances-empty');
expect(root.querySelector('.duration-estimate')).toBeNull();
expect(calculate).not.toHaveBeenCalled();
expect(root.querySelector('.planning-status')?.textContent).toContain(
'Add your leave balances',
);
expect(root.querySelector('.plan-summary')).toBeNull();
expect(root.querySelector('.statistics-button')).toBeNull();
// The default planning horizon still shows its weekends and public holidays.
expect(root.querySelectorAll('app-calendar-month')).toHaveLength(13);
expect(
root.querySelector('button[data-date="2026-11-11"]')?.getAttribute('aria-label'),
).toContain('Public holiday');
expect(
root.querySelector('button[data-date="2026-10-10"]')?.getAttribute('aria-label'),
).toContain('Weekend');
root.querySelector<HTMLButtonElement>('.add-day-button')!.click();
fixture.detectChanges();
await fixture.whenStable();
const added = localStorage.getItem('leaveBalances');
expect(JSON.parse(added!)).toMatchObject([
{
type: 'cp',
numberOfDays: 1,
availableDate: '2026-10-04',
expiryDate: '2027-10-04',
},
]);
expect(root.querySelector('#leave-balances-empty')).toBeNull();
expect(root.querySelector('.planning-status')).toBeNull();
expect(calculate).not.toHaveBeenCalled();
expect(button.disabled).toBe(false);
button.click();
await fixture.whenStable();
expect(calculate).toHaveBeenCalledOnce();
expect(calculate.mock.calls[0][0].balances).toMatchObject([
{ type: 'cp', quantity: 1 },
]);
await expect.poll(() => root.querySelector('.plan-summary')).not.toBeNull();
await revisitApp(true);
expect(fixture.nativeElement.querySelectorAll('app-day-input')).toHaveLength(1);
expect(calculate).toHaveBeenCalledOnce();
expect(localStorage.getItem('leaveBalances')).toBe(added);
},
);
it('restores a saved empty list without calculating, and calculates declared days on their own', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date(2026, 9, 4, 12));
const random = vi
.spyOn(Math, 'random')
.mockReturnValueOnce(0)
.mockReturnValueOnce(0.5)
.mockReturnValue(1 - Number.EPSILON);
localStorage.removeItem('leaveBalances');
await revisitApp(true);
const root = fixture.nativeElement as HTMLElement;
expect(
Array.from(root.querySelectorAll<HTMLInputElement>('app-day-input input')).map(
(input) => input.value,
),
).toEqual([
'10',
'04/10/2026',
'04/10/2027',
'15',
'04/10/2026',
'04/10/2027',
'20',
'04/10/2026',
'04/10/2027',
]);
const types = await loader.getAllHarnesses(
MatSelectHarness.with({ selector: 'app-day-input mat-select' }),
);
expect(await Promise.all(types.map((type) => type.getValueText()))).toEqual([
'Paid Leave',
'RTT',
'Other',
]);
expect(calculate).toHaveBeenCalledOnce();
const initialRequest = calculate.mock.calls[0][0];
expect(initialRequest.balances.map((balance) => balance.quantity)).toEqual([10, 15, 20]);
expect(calculatePlanningInternal(initialRequest).kind).toBe('Plan');
await expect.poll(() => root.querySelector('.planning-status')).not.toBeNull();
expect(localStorage.getItem('leaveBalances')).toBeNull();
root.querySelector<HTMLButtonElement>('.calculate-button')!.click();
await fixture.whenStable();
expect(calculate).toHaveBeenCalledTimes(2);
expect(calculate.mock.calls[1][0].balances).toEqual(initialRequest.balances);
await expect.poll(() => root.querySelector('.planning-status')).not.toBeNull();
expect(localStorage.getItem('leaveBalances')).toBeNull();
const quantity = root.querySelector<HTMLInputElement>(
'app-day-input input[type="number"]',
)!;
quantity.value = '7';
quantity.dispatchEvent(new Event('input'));
await fixture.whenStable();
const saved = localStorage.getItem('leaveBalances');
expect(JSON.parse(saved!)).toMatchObject([
{ type: 'cp', numberOfDays: 7, availableDate: '2026-10-04', expiryDate: '2027-10-04' },
{
type: 'rtt',
numberOfDays: 15,
availableDate: '2026-10-04',
expiryDate: '2027-10-04',
},
{
type: 'other',
numberOfDays: 20,
availableDate: '2026-10-04',
expiryDate: '2027-10-04',
},
]);
random.mockReturnValue(0);
await revisitApp(true);
expect(
Array.from(
fixture.nativeElement.querySelectorAll('app-day-input input[type="number"]'),
(input) => (input as HTMLInputElement).value,
),
).toEqual(['7', '15', '20']);
expect(calculate).toHaveBeenCalledOnce();
expect(calculate.mock.calls[0][0].balances).toEqual(
initialRequest.balances.map((balance, index) =>
index === 0 ? { ...balance, quantity: 7 } : balance,
),
);
expect(localStorage.getItem('leaveBalances')).toBe(saved);
});
it('calculates with a saved empty balance list without generating replacement rows', async () => {
localStorage.setItem('leaveBalances', '[]');
const random = vi.spyOn(Math, 'random');
await revisitApp(true);
expect(fixture.nativeElement.querySelector('app-day-input')).toBeNull();
let root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('app-day-input')).toBeNull();
expect(root.querySelector('#leave-balances-empty')).not.toBeNull();
expect(root.querySelector<HTMLButtonElement>('.calculate-button')!.disabled).toBe(true);
expect(calculate).not.toHaveBeenCalled();
expect(localStorage.getItem('leaveBalances')).toBe('[]');
localStorage.setItem(
'declaredNonWorkingDays',
JSON.stringify([{ date: '2026-10-06', type: 'cp' }]),
);
await revisitApp(true, startInProcessJob);
root = fixture.nativeElement as HTMLElement;
expect(calculate).toHaveBeenCalledOnce();
expect(calculate.mock.calls[0][0].balances).toEqual([]);
expect(calculatePlanningInternal(calculate.mock.calls[0][0]).kind).toBe('Plan');
await expect
.poll(() => fixture.nativeElement.querySelector('.planning-status'))
.not.toBeNull();
expect(random).not.toHaveBeenCalled();
expect(calculate.mock.calls[0][0].declaredDays).toEqual([
{ date: '2026-10-06', type: 'cp' },
]);
await expect.poll(() => root.querySelector('.plan-summary')).not.toBeNull();
expect(root.querySelector('.planning-status.info')).toBeNull();
expect(root.querySelector('#leave-balances-empty')).not.toBeNull();
const button = root.querySelector<HTMLButtonElement>('.calculate-button')!;
expect(button.disabled).toBe(false);
expect(button.getAttribute('aria-describedby')).toBe('planning-duration-estimate');
expect(localStorage.getItem('leaveBalances')).toBe('[]');
});
@@ -259,7 +257,7 @@ describe('Application Settings', () => {
[
'reversed dates',
{ availableDate: '2026-06-01' },
'A leave balance must become available on or before its expiry date.',
'A leave balance’s availability date cannot be after its expiry date.',
],
])('leaves readable saved inputs (%s) to planner validation', async (_, invalid, reason) => {
const saved = JSON.stringify([
@@ -361,7 +359,7 @@ describe('Application Settings', () => {
).toBeTruthy();
expect(period.querySelector('legend')?.textContent).toBe('Planning period');
expect(period.querySelector('#planning-dates-help')?.textContent).toContain(
'Calculate plan',
'next calculation',
);
const start = period.querySelector<HTMLInputElement>('input[name="planningStart"]')!;
const last = period.querySelector<HTMLInputElement>('input[name="lastPlanningDate"]')!;
+36 -3
View File
@@ -1,6 +1,8 @@
@if (showPlanner()) {
<div class="app-shell">
<a class="skip-link" href="#planning-results-title">{{ tr().app.skipToPlan }}</a>
<a class="skip-link" href="#planning-results-title" (click)="showPlanHeading()">{{
tr().app.skipToPlan
}}</a>
<header class="app-header">
<div class="brand">
<mat-icon aria-hidden="true">beach_access</mat-icon>
@@ -21,14 +23,45 @@
</button>
</header>
<main class="planner-layout">
<section class="configuration-panel" aria-labelledby="leave-settings-title">
<main class="planner-layout" [attr.data-view]="view()">
<section
class="configuration-panel"
cdkScrollable
aria-labelledby="leave-settings-title"
>
<app-user-input></app-user-input>
</section>
<section class="results-panel" aria-labelledby="planning-results-title">
<app-calendar-year></app-calendar-year>
</section>
<div #actionBar class="action-bar">
@if (declarationEntry() && view() === 'plan') {
<app-declaration-controls></app-declaration-controls>
}
<div class="action-bar-row">
<div class="view-switch" role="group" [attr.aria-label]="tr().app.view">
<button
type="button"
[attr.aria-pressed]="view() === 'configuration'"
(click)="show('configuration')"
>
<mat-icon aria-hidden="true">tune</mat-icon>
{{ tr().app.configuration }}
</button>
<button
type="button"
[attr.aria-pressed]="view() === 'plan'"
(click)="show('plan')"
>
<mat-icon aria-hidden="true">calendar_month</mat-icon>
{{ tr().app.plan }}
</button>
</div>
<app-calculate-button (started)="showPlanHeading()"></app-calculate-button>
</div>
</div>
</main>
</div>
<app-rule-set-import />
}
<router-outlet></router-outlet>
+84 -2
View File
@@ -82,7 +82,8 @@ app-calendar-year {
}
.configuration-panel {
padding: 1.25rem;
--panel-padding: 1.25rem;
padding: var(--panel-padding);
background: var(--ui-card-bg);
border: 1px solid var(--ui-border);
border-radius: var(--ui-radius-lg);
@@ -102,10 +103,91 @@ app-calendar-year {
}
}
// Below 75rem, only the chosen view is displayed; the bar at the bottom switches it and calculates.
@media (width < 75rem) {
.app-shell {
padding-block-end: var(--action-bar-height, 0px);
}
.planner-layout[data-view='plan'] .configuration-panel,
.planner-layout[data-view='configuration'] .results-panel {
display: none;
}
}
.action-bar {
position: fixed;
inset: auto 0 0;
z-index: 2;
display: grid;
gap: 0.5rem;
padding: 0.5rem var(--workspace-gutter) calc(0.5rem + env(safe-area-inset-bottom, 0px));
background: var(--ui-card-bg);
border-block-start: 1px solid var(--ui-border);
box-shadow: 0 -0.25rem 1rem rgb(0 0 0 / 8%);
}
.action-bar-row {
display: flex;
align-items: stretch;
gap: 0.5rem;
app-calculate-button {
flex: 1;
min-width: 0;
}
}
.view-switch {
display: flex;
flex-shrink: 0;
gap: 0.25rem;
padding: 0.25rem;
border: 1px solid var(--ui-border);
border-radius: var(--ui-radius-sm);
background: var(--ui-panel-bg);
button {
display: grid;
justify-items: center;
align-content: center;
min-width: 4.5rem;
min-height: 2.75rem;
padding: 0.125rem 0.5rem;
border: 0;
border-radius: 0.375rem;
background: transparent;
color: var(--ui-text-secondary);
font: inherit;
font-size: 0.75rem;
font-weight: 600;
line-height: 1.25;
cursor: pointer;
&[aria-pressed='true'] {
background: var(--mat-sys-primary-container);
color: var(--mat-sys-on-primary-container);
}
}
}
@media (min-width: 75rem) {
.planner-layout {
grid-template-columns: clamp(26rem, 34%, 40rem) minmax(0, 1fr);
}
.action-bar {
display: none;
}
// Stays in view while the results scroll, and scrolls inside when taller than the screen.
// The 9rem leaves room for the header, which scrolls away, so that the panel fits on first load.
.configuration-panel {
position: sticky;
top: 1rem;
max-height: calc(100dvh - 9rem);
overflow-y: auto;
}
}
@media (max-width: 35rem) {
@@ -118,6 +200,6 @@ app-calendar-year {
}
.configuration-panel {
padding: 1rem;
--panel-padding: 1rem;
}
}
+227 -2
View File
@@ -1,7 +1,15 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { ScrollDispatcher } from '@angular/cdk/scrolling';
import { vi } from '../testing/vitest-compat';
import { App } from './app';
import { CalendarSettingsService } from './services/calendar-settings-service';
import { PlanningCalculationService } from './services/planning-calculation.service';
import { OPTIMIZATION_PRESETS } from './services/planning-objectives';
import { RuleService, RuleType, type VacationRule } from './services/rule-service';
import { encodeRuleSetLink } from './services/rule-set-link';
import { TranslationService } from './services/translation-service';
import { UserInputService } from './services/user-input-service';
describe('App', () => {
beforeEach(async () => {
@@ -12,7 +20,8 @@ describe('App', () => {
});
afterEach(() => {
localStorage.removeItem('app.language');
vi.restoreAllMocks();
localStorage.clear();
document.documentElement.lang = 'en';
});
@@ -26,7 +35,19 @@ describe('App', () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('vac-optimizer');
expect(compiled.querySelector('h1')?.textContent).toContain('VacOptimizer');
});
it('registers the scrolling configuration panel so that dragging a rule can auto-scroll it', () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const panel = fixture.nativeElement.querySelector('.configuration-panel') as HTMLElement;
const scrollables = TestBed.inject(ScrollDispatcher).getAncestorScrollContainers(
panel.querySelector('app-rules-panel')!,
);
expect(scrollables.map((scrollable) => scrollable.getElementRef().nativeElement)).toEqual([
panel,
]);
});
it('keeps the document language in sync with the selected language', () => {
@@ -47,4 +68,208 @@ describe('App', () => {
history.replaceState({}, '', originalPath);
}
});
describe('a share link', () => {
const shared: VacationRule[] = [
{
id: 'shared-loss',
name: 'Shared loss priority',
type: RuleType.OPTIMIZATION,
enabled: true,
force: 'preference',
configuration: structuredClone(OPTIMIZATION_PRESETS.unplacedAtRisk),
},
];
const dialog = () => document.querySelector<HTMLElement>('mat-dialog-container');
/** Everything saved except the rule set. */
const otherSavedEntries = () =>
Object.fromEntries(
Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index)!)
.filter((key) => key !== 'vacationRules')
.map((key) => [key, localStorage.getItem(key)]),
);
async function openWith(path: string) {
const result = await encodeRuleSetLink(shared);
if (!('link' in result)) throw new Error('The rule set was refused.');
history.replaceState({}, '', path + new URL(result.link).hash);
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
await fixture.whenStable();
return fixture;
}
afterEach(() => history.replaceState({}, '', '/'));
it('replaces the rule set once accepted, and leaves the leave balances, the declared days and the planning period as they are', async () => {
localStorage.setItem(
'leaveBalances',
JSON.stringify([
{
id: 'b1',
type: 'cp',
numberOfDays: 3,
availableDate: '2026-01-01',
expiryDate: '2026-12-31',
},
]),
);
localStorage.setItem(
'declaredNonWorkingDays',
JSON.stringify([{ date: '2026-03-02', type: 'cp' }]),
);
localStorage.setItem(
'calendarSettings.planningDates',
JSON.stringify({ start: '2026-01-01', lastPlanningDate: '2026-12-31' }),
);
vi.spyOn(
TestBed.inject(PlanningCalculationService),
'createPlanningCalculation',
).mockImplementation(() => ({ outcome: new Promise(() => undefined) }) as never);
const userInput = TestBed.inject(UserInputService);
const settings = TestBed.inject(CalendarSettingsService);
const fixture = await openWith('/');
await expect.poll(() => dialog()).not.toBeNull();
await fixture.whenStable();
const saved = otherSavedEntries();
const balances = userInput.vacationNumberSignal();
const declaredDays = userInput.declaredDaysSignal();
expect(balances).toHaveLength(1);
expect(declaredDays).toEqual([{ date: '2026-03-02', type: 'cp' }]);
expect(settings.planningDates()).toEqual({
start: '2026-01-01',
lastPlanningDate: '2026-12-31',
});
const period = settings.planningDates();
Array.from(dialog()!.querySelectorAll('button')).at(-1)!.click();
await expect.poll(() => dialog()).toBeNull();
await fixture.whenStable();
expect(TestBed.inject(RuleService).rules).toEqual(shared);
expect(location.hash).toBe('');
expect(otherSavedEntries()).toEqual(saved);
expect(userInput.vacationNumberSignal()).toBe(balances);
expect(userInput.declaredDaysSignal()).toBe(declaredDays);
expect(settings.planningDates()).toBe(period);
});
it('is ignored on the benchmark route', async () => {
const fixture = await openWith('/benchmark');
const link = location.hash;
window.dispatchEvent(new Event('hashchange'));
await new Promise((resolve) => setTimeout(resolve, 100));
await fixture.whenStable();
expect(dialog()).toBeNull();
expect(location.hash).toBe(link);
});
});
describe('narrow layout views', () => {
const balance = {
id: 'b1',
type: 'cp',
numberOfDays: 3,
availableDate: '2026-01-01',
expiryDate: '2026-12-31',
};
async function render(balances: unknown[]) {
localStorage.setItem('leaveBalances', JSON.stringify(balances));
const calculate = vi
.spyOn(TestBed.inject(PlanningCalculationService), 'createPlanningCalculation')
.mockImplementation(() => ({ outcome: new Promise(() => undefined) }) as never);
vi.spyOn(window, 'scrollTo').mockImplementation(() => undefined);
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
await fixture.whenStable();
const root = fixture.nativeElement as HTMLElement;
const view = () => root.querySelector('.planner-layout')?.getAttribute('data-view');
const bar = root.querySelector<HTMLElement>('.action-bar')!;
const [configuration, plan] =
bar.querySelectorAll<HTMLButtonElement>('.view-switch button');
const settle = async () => {
fixture.detectChanges();
await fixture.whenStable();
};
return { root, view, bar, configuration, plan, calculate, settle };
}
it('opens on the configuration when there is nothing to plan, and on the plan being calculated otherwise', async () => {
const empty = await render([]);
expect(empty.view()).toBe('configuration');
expect(empty.configuration.getAttribute('aria-pressed')).toBe('true');
expect(empty.plan.getAttribute('aria-pressed')).toBe('false');
expect(empty.calculate).not.toHaveBeenCalled();
expect(empty.bar.querySelector<HTMLButtonElement>('.calculate-button')!.disabled).toBe(
true,
);
TestBed.resetTestingModule();
await TestBed.configureTestingModule({
imports: [App],
providers: [provideZonelessChangeDetection()],
}).compileComponents();
const planned = await render([balance]);
expect(planned.view()).toBe('plan');
expect(planned.calculate).toHaveBeenCalledOnce();
});
it('switches views from the bar, and its Calculate shows the plan from its heading', async () => {
const { root, view, bar, configuration, plan, calculate, settle } = await render([
balance,
]);
configuration.click();
await settle();
expect(view()).toBe('configuration');
expect(plan.getAttribute('aria-pressed')).toBe('false');
expect(window.scrollTo).toHaveBeenCalledWith(0, 0);
const barCalculate = bar.querySelector<HTMLButtonElement>('.calculate-button')!;
expect(barCalculate.getAttribute('aria-describedby')).toBe(
'planning-duration-estimate',
);
barCalculate.focus();
barCalculate.click();
await settle();
expect(calculate).toHaveBeenCalledTimes(2);
expect(view()).toBe('plan');
expect(plan.getAttribute('aria-pressed')).toBe('true');
expect(document.activeElement).toBe(root.querySelector('#planning-results-title'));
});
it('shows the plan and its heading from the skip link', async () => {
const { root, view, configuration, settle } = await render([balance]);
configuration.click();
await settle();
root.querySelector<HTMLAnchorElement>('.skip-link')!.click();
await settle();
expect(view()).toBe('plan');
expect(document.activeElement).toBe(root.querySelector('#planning-results-title'));
expect(root.querySelector('.jump-to-plan')).toBeNull();
});
it('enters declared days on the plan with the type choices in the bar, then keeps focus in the bar', async () => {
const { root, view, bar, configuration, plan, settle } = await render([balance]);
configuration.click();
await settle();
expect(bar.querySelector('app-declaration-controls')).toBeNull();
root.querySelector<HTMLButtonElement>(
'.configuration-panel .declaration-entry-toggle',
)!.click();
await settle();
expect(view()).toBe('plan');
const controls = bar.querySelector('app-declaration-controls')!;
expect(
[
...controls.querySelectorAll('[data-declared-type], [data-declaration-erase]'),
].map((button) => button.textContent?.trim()),
).toEqual(['check CP', 'check RTT', 'check Other', 'backspace Erase']);
const finish = controls.querySelector<HTMLButtonElement>('.declaration-entry-toggle')!;
expect(finish.getAttribute('aria-pressed')).toBe('true');
finish.focus();
finish.click();
await settle();
expect(bar.querySelector('app-declaration-controls')).toBeNull();
expect(view()).toBe('plan');
expect(document.activeElement).toBe(plan);
});
});
});
+87 -2
View File
@@ -1,22 +1,35 @@
import {
afterNextRender,
ChangeDetectionStrategy,
Component,
DOCUMENT,
effect,
ElementRef,
inject,
Injector,
linkedSignal,
signal,
viewChild,
} from '@angular/core';
import { CdkScrollable } from '@angular/cdk/scrolling';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { provideNativeDateAdapter } from '@angular/material/core';
import { UserInput } from './components/user-input/user-input';
import { CalendarYear } from './components/calendar-year/calendar-year';
import { UserSettings } from './components/user-settings/user-settings';
import { CalculateButton } from './components/calculate-button/calculate-button';
import { DeclarationControls } from './components/declaration-controls/declaration-controls';
import { RuleSetImport } from './components/rule-set-import/rule-set-import';
import { MatButton } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog';
import { MatIcon } from '@angular/material/icon';
import { NavigationEnd, Router, RouterOutlet } from '@angular/router';
import { TranslationService } from './services/translation-service';
import { ThemeService } from './services/theme-service';
import { UserInputService } from './services/user-input-service';
/** Below 75rem, only one of the configuration and the plan is displayed. */
type PlannerView = 'configuration' | 'plan';
function isBenchmarkUrl(url: string): boolean {
return url.split(/[?#]/, 1)[0].replace(/\/+$/, '') === '/benchmark';
@@ -24,7 +37,18 @@ function isBenchmarkUrl(url: string): boolean {
@Component({
selector: 'app-root',
imports: [MatDatepickerModule, UserInput, CalendarYear, MatButton, MatIcon, RouterOutlet],
imports: [
CdkScrollable,
MatDatepickerModule,
UserInput,
CalendarYear,
CalculateButton,
DeclarationControls,
RuleSetImport,
MatButton,
MatIcon,
RouterOutlet,
],
templateUrl: './app.html',
styleUrl: './app.scss',
providers: [provideNativeDateAdapter()],
@@ -35,8 +59,20 @@ export class App {
private readonly dialog = inject(MatDialog);
private readonly document = inject(DOCUMENT);
private readonly translations = inject(TranslationService);
private readonly injector = inject(Injector);
private readonly userInput = inject(UserInputService);
private readonly actionBar = viewChild<ElementRef<HTMLElement>>('actionBar');
protected readonly declarationEntry = this.userInput.declarationEntrySignal;
/** The plan unless there is nothing to plan yet; declared days are entered on the plan's calendar. */
protected readonly view = linkedSignal<boolean, PlannerView>({
source: this.declarationEntry,
computation: (entry, previous) =>
entry
? 'plan'
: (previous?.value ?? (this.userInput.nothingToPlan() ? 'configuration' : 'plan')),
});
protected readonly tr = this.translations.tr;
protected readonly title = signal('vac-optimizer');
protected readonly title = signal('VacOptimizer');
protected readonly showPlanner = signal(
!isBenchmarkUrl(typeof window !== 'undefined' ? window.location.pathname : this.router.url),
);
@@ -48,6 +84,55 @@ export class App {
if (event instanceof NavigationEnd)
this.showPlanner.set(!isBenchmarkUrl(event.urlAfterRedirects));
});
effect((onCleanup) => {
const bar = this.actionBar()?.nativeElement;
if (!bar || typeof ResizeObserver === 'undefined') return;
// The fixed bar must not hide the end of the page or a focused element: see styles.scss.
const observer = new ResizeObserver(() =>
this.document.documentElement.style.setProperty(
'--action-bar-height',
`${bar.offsetHeight}px`,
),
);
observer.observe(bar, { box: 'border-box' });
onCleanup(() => {
observer.disconnect();
this.document.documentElement.style.removeProperty('--action-bar-height');
});
});
effect(() => {
this.view();
this.declarationEntry();
const focused = this.document.activeElement;
if (!(focused instanceof HTMLElement) || focused === this.document.body) return;
// A control that hides its own panel, or the bar's copy of the declaration controls, loses focus:
// move it to the bar's current choice instead of the start of the page.
afterNextRender(
() => {
const active = this.document.activeElement;
if (focused.isConnected && focused.checkVisibility?.() !== false) return;
if (active !== focused && active !== this.document.body) return;
this.actionBar()
?.nativeElement.querySelector<HTMLElement>('[aria-pressed="true"]')
?.focus();
},
{ injector: this.injector },
);
});
}
protected show(view: PlannerView): void {
if (view === this.view()) return;
this.view.set(view);
this.document.defaultView?.scrollTo?.(0, 0);
}
/** After Calculate in the bar, or the skip link: the plan, with its loading state and Cancel, from its heading. */
protected showPlanHeading(): void {
this.view.set('plan');
afterNextRender(() => this.document.getElementById('planning-results-title')?.focus(), {
injector: this.injector,
});
}
protected openSettings(): void {
@@ -17,9 +17,23 @@ describe('leave planner benchmark protocol', () => {
beforeEach(() => vi.setSystemTime(new Date('2024-01-01T12:00:00Z')));
afterEach(() => vi.useRealTimers());
// Warm-up and two repetitions include explanation delivery after planning.
it('keeps seven deterministic scenarios including two and three years and a later earned consumer', async () => {
it('keeps eight deterministic scenarios including two and three years, a later earned consumer and the default rules', async () => {
const scenarios = benchmarkScenarios();
expect(scenarios).toHaveLength(7);
expect(scenarios).toHaveLength(8);
expect(
scenarios
.find((scenario) => scenario.name === 'default rules')
?.request.rules?.map((rule) => rule.id),
).toEqual([
'default-unplaced-at-risk',
'samedi',
'christmas',
'default-holiday-week-value',
'default-non-working-day-gain',
'default-longest-work-sequence',
'default-short-sequence-deficit',
'default-supporting-placements',
]);
for (const [name, end] of [
['two years', '2026-01-01'],
['three years', '2027-01-01'],
@@ -122,6 +136,12 @@ describe('leave planner benchmark protocol', () => {
expect(longer.map((item) => item.placements)).toEqual([placements, placements]);
expect(longer.map((item) => item.deterministic)).toEqual(['baseline', 'yes']);
}
const defaults = measurements.filter(
(measurement) => measurement.scenario === 'default rules',
);
expect(defaults.map((item) => item.outcome)).toEqual(['Plan', 'Plan']);
expect(defaults.map((item) => item.lastCompletedStage)).toEqual(['dates', 'dates']);
expect(defaults.map((item) => item.deterministic)).toEqual(['baseline', 'yes']);
const chained = measurements.find(
(measurement) => measurement.scenario === 'chained earned entitlements',
);
@@ -141,7 +161,7 @@ describe('leave planner benchmark protocol', () => {
);
const report = benchmarkReport(measurements);
print(`\nRaw report (TSV):\n${report}\n`);
expect(report.split('\n')).toHaveLength(15);
expect(report.split('\n')).toHaveLength(17);
expect(report).toContain('planning_ms\twall_ms');
expect(report).toContain('planning_work_ms\tpeak_main_thread_heap_bytes');
expect(report).toContain('\tbaseline\t');
+39 -1
View File
@@ -164,6 +164,43 @@ export function benchmarkScenarios(): BenchmarkScenario[] {
},
}),
),
{
// The default rules, which no other scenario enables: 2027 has three Saturday public
// holidays, so Samedi Malin shapes every later stage (#348).
name: 'default rules',
request: {
horizon: { start: '2027-01-01', end: '2028-01-01' },
balances: (['cp', 'rtt'] as const).map((type) => ({
id: `${type}-2027`,
type,
quantity: type === 'cp' ? 25 : 12,
availableFrom: '2027-01-01',
expiryDate: '2027-12-31',
})),
rules: [
{
id: 'samedi',
type: 'if_then',
force: 'preference',
dayOfWeek: 6,
placeDays: 2,
placeType: 'cp',
placement: 'auto',
rewardDays: 1,
rewardType: 'other',
},
{
id: 'christmas',
type: 'time_window',
force: 'preference',
startDate: '2027-12-20',
endDate: '2028-01-03',
placeDays: 5,
placeType: 'any',
},
],
},
},
];
return scenarios.map((scenario) => ({
...scenario,
@@ -307,7 +344,7 @@ export function benchmarkReport(measurements: BenchmarkMeasurement[]): string {
].join('\n');
}
// About 1.5x the development machine's ratios to the calibration run after #321.
// About 1.5x the development machine's ratios to the calibration run after #321 (default rules: after #348).
export const BENCHMARK_BUDGET_MULTIPLIERS: Record<string, number> = {
'representative year': 0.1,
'typed obligations': 0.1,
@@ -316,6 +353,7 @@ export const BENCHMARK_BUDGET_MULTIPLIERS: Record<string, number> = {
'loaded year': 1.25,
'two years': 0.25,
'three years': 0.75,
'default rules': 1.25,
};
/** One message per scenario whose mean planning time exceeds multiplier x calibration, or that has no multiplier. */
@@ -0,0 +1,20 @@
<button
mat-flat-button
class="calculate-button"
color="primary"
type="button"
[disabled]="!!calendarSettings.planningHorizonError() || nothingToPlan()"
[attr.aria-describedby]="
calendarSettings.planningHorizonError()
? nothingToPlan()
? 'planning-dates-error leave-balances-empty'
: 'planning-dates-error'
: nothingToPlan()
? 'leave-balances-empty'
: 'planning-duration-estimate'
"
(click)="calculate()"
>
<mat-icon aria-hidden="true">auto_awesome</mat-icon>
{{ tr().userInput.calculate }}
</button>
@@ -0,0 +1,11 @@
// A grid, so that the button is laid out as a block, as it was as a direct child of its bar.
:host {
display: grid;
}
.calculate-button {
width: 100%;
min-height: 3.25rem;
border-radius: var(--ui-radius-sm);
font-weight: 600;
}
@@ -0,0 +1,32 @@
import { ChangeDetectionStrategy, Component, inject, output } from '@angular/core';
import { MatButton } from '@angular/material/button';
import { MatIcon } from '@angular/material/icon';
import { CalendarSettingsService } from '../../services/calendar-settings-service';
import { PlanningCalculationService } from '../../services/planning-calculation.service';
import { TranslationService } from '../../services/translation-service';
import { UserInputService } from '../../services/user-input-service';
/**
* Calculate, disabled and described by the reason while there is nothing valid to plan.
* The descriptions are the configuration panel's messages, referenced by id even where that panel is hidden.
*/
@Component({
selector: 'app-calculate-button',
imports: [MatButton, MatIcon],
templateUrl: './calculate-button.html',
styleUrl: './calculate-button.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CalculateButton {
protected readonly calendarSettings = inject(CalendarSettingsService);
protected readonly nothingToPlan = inject(UserInputService).nothingToPlan;
private readonly calculations = inject(PlanningCalculationService);
protected readonly tr = inject(TranslationService).tr;
readonly started = output();
calculate(): void {
if (this.calendarSettings.planningHorizonError() || this.nothingToPlan()) return;
this.calculations.start();
this.started.emit();
}
}
@@ -35,6 +35,7 @@ import { PlanningDurationService } from '../../services/planning-duration.servic
import { PlanningCalculationService } from '../../services/planning-calculation.service';
import { DateRange } from '@angular/material/datepicker';
import { translationsMap } from '../../i18n-registry';
import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives';
const invalid: InvalidInputOutcome = {
kind: 'InvalidInput',
@@ -205,7 +206,7 @@ function calculationFor(
{
date: '2024-05-08',
status: 'ineligible',
reason: { code: 'non-working', message: 'Public Holiday' },
reason: { code: 'non-working', message: 'Public holiday' },
},
],
};
@@ -255,6 +256,20 @@ function deferred<T>() {
return { promise, resolve, reject };
}
const text = (element: Element) => element.textContent?.replace(/\s+/g, ' ').trim();
/** Each figure of a statistics list: its label, then its value and notes. */
const figures = (root: ParentNode, list = '.statistics-summary') =>
Array.from(root.querySelectorAll(`${list} > div`), (figure) =>
Array.from(figure.children, text),
);
/** The earned-leave figure of the open statistics dialog: its total, then its rules. */
const earnedLeave = () =>
figures(document.querySelector('[role="dialog"]')!)
.find(([label]) => label === 'Days earned through your rules')
?.slice(1);
function activateWithKeyboard(element: HTMLElement, key: 'Enter' | ' ' = 'Enter'): void {
element.focus();
element.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }));
@@ -264,8 +279,22 @@ function activateWithKeyboard(element: HTMLElement, key: 'Enter' | ' ' = 'Enter'
const presets = createOptimizationPresetRules();
// The page calculates on load only when there is something to plan.
const savedBalances = JSON.stringify([
{
id: 'cp',
type: 'cp',
numberOfDays: 2,
availableDate: '2024-01-01',
expiryDate: '2024-12-31',
},
]);
describe('CalendarYear planning outcome boundary', () => {
beforeEach(() => localStorage.clear());
beforeEach(() => {
localStorage.clear();
localStorage.setItem('leaveBalances', savedBalances);
});
afterEach(() => {
localStorage.clear();
vi.useRealTimers();
@@ -416,13 +445,12 @@ describe('CalendarYear planning outcome boundary', () => {
fixture.detectChanges();
fixture.nativeElement.querySelector('.statistics-button').click();
await fixture.whenStable();
const holidayLabel = Array.from(document.querySelectorAll('[role="dialog"] dt')).find(
(label) => label.textContent?.includes('Public holidays connected to a weekend'),
);
expect(holidayLabel?.textContent?.replace(/\s+/g, ' ').trim()).toBe(
'Public holidays connected to a weekend (calendar days)',
);
expect(holidayLabel?.nextElementSibling?.textContent?.trim()).toBe(String(expected));
const [bridged, possible] = figures(document.querySelector('[role="dialog"]')!)
.find(([label]) => label === 'Public holidays bridged to a weekend')![1]!
.split(' of ')
.map(Number);
expect(bridged).toBe(expected);
expect(possible).toBeGreaterThanOrEqual(expected);
},
);
@@ -520,21 +548,15 @@ describe('CalendarYear planning outcome boundary', () => {
fixture.detectChanges();
const dialog = document.querySelector('[role="dialog"]')!;
expect(dialog.textContent).toContain('Plan statistics');
const statistics = () =>
Array.from(dialog.querySelectorAll('dt'), (label) => [
label.textContent?.replace(/\s+/g, ' ').trim(),
label.nextElementSibling?.textContent?.trim(),
]);
const statistics = () => figures(dialog);
const expectedStatistics = [
['New leave days', String(placements)],
['Non-working days gained (calendar days)', '4'],
['Average work sequence (working days)', '3.333'],
['Longest work sequence (working days)', '6'],
['Average time-off period (calendar days)', '2.5'],
['Longest time-off period (calendar days)', '4'],
['Public holidays connected to a weekend (calendar days)', '2'],
['Earned leave before use (days)', '3'],
['Original generating rule', '3'],
['Leave days taken', `${placements} of ${placements}`],
['Leave days not taken', '0'],
['Total days off', '5', 'including 4 weekend days and public holidays'],
['Time-off periods', '1', 'the longest: 4 days'],
['Longest stretch without leave', '6 working days'],
['Public holidays bridged to a weekend', '2 of 10'],
['Days earned through your rules', '3', 'Original generating rule'],
];
expect(statistics()).toEqual(expectedStatistics);
expect(dialog.textContent?.includes('Partial plan')).toBe(partial);
@@ -617,17 +639,8 @@ describe('CalendarYear planning outcome boundary', () => {
fixture.nativeElement.querySelector('.statistics-button').click();
await fixture.whenStable();
const dialog = document.querySelector('[role="dialog"]')!;
expect(
dialog
.querySelector('.statistics-summary > div:last-child dd')
?.textContent?.trim(),
).toBe('3');
expect(
Array.from(dialog.querySelectorAll('.earned-leave-breakdown dt'), (label) => [
label.textContent?.trim(),
label.nextElementSibling?.textContent?.trim(),
]),
).toEqual([['Samedi Malin', '3']]);
expect(dialog).not.toBeNull();
expect(earnedLeave()).toEqual(['3', 'Samedi Malin']);
} finally {
vi.useRealTimers();
}
@@ -776,18 +789,18 @@ describe('CalendarYear planning outcome boundary', () => {
fixture.nativeElement.querySelector('.statistics-button').click();
await fixture.whenStable();
const dialog = document.querySelector('[role="dialog"]')!;
expect(
dialog
.querySelector('.statistics-summary > div:last-child dd')
?.textContent?.trim(),
).toBe(String(total));
expect(
Array.from(dialog.querySelectorAll('.earned-leave-breakdown dt'), (label) => [
label.textContent?.trim(),
label.nextElementSibling?.textContent?.trim(),
]),
).toEqual(rows);
expect(!!dialog.querySelector('#earned-leave-title')).toBe(total > 0);
expect(dialog).not.toBeNull();
// Nothing earned shows no figure; a single earning rule is named without repeating the total.
expect(earnedLeave()).toEqual(
total
? [
String(total),
...rows.map(([rule, days]) =>
rows.length > 1 ? `${rule} · ${days}` : rule,
),
]
: undefined,
);
} finally {
vi.useRealTimers();
}
@@ -835,22 +848,7 @@ describe('CalendarYear planning outcome boundary', () => {
fixture.detectChanges();
fixture.nativeElement.querySelector('.statistics-button').click();
await fixture.whenStable();
expect(
document
.querySelector(
'[role="dialog"] .statistics-summary > div:last-child dd',
)
?.textContent?.trim(),
).toBe('2');
expect(
Array.from(
document.querySelectorAll('[role="dialog"] .earned-leave-breakdown dt'),
(label) => [
label.textContent?.trim(),
label.nextElementSibling?.textContent?.trim(),
],
),
).toEqual([['Samedi Malin', '2']]);
expect(earnedLeave()).toEqual(['2', 'Samedi Malin']);
} finally {
vi.useRealTimers();
}
@@ -939,17 +937,7 @@ describe('CalendarYear planning outcome boundary', () => {
await fixture.whenStable();
const dialog = document.querySelector('[role="dialog"]')!;
expect(dialog.textContent).toContain('Partial plan');
expect(
dialog
.querySelector('.statistics-summary > div:last-child dd')
?.textContent?.trim(),
).toBe('2');
expect(
Array.from(dialog.querySelectorAll('.earned-leave-breakdown dt'), (label) => [
label.textContent?.trim(),
label.nextElementSibling?.textContent?.trim(),
]),
).toEqual([['after', '2']]);
expect(earnedLeave()).toEqual(['2', 'after']);
} finally {
clock.mockRestore();
vi.useRealTimers();
@@ -957,7 +945,7 @@ describe('CalendarYear planning outcome boundary', () => {
});
it.each([false, true])(
'distinguishes empty averages from zero work and gain in a valid plan (all workdays off: %s)',
'shows a longest time-off period only when the plan has one (all workdays off: %s)',
async (allDaysOff) => {
const core = await import('../../services/leave-planner.core');
const validPlan = core.calculatePlanningInternal({
@@ -988,15 +976,22 @@ describe('CalendarYear planning outcome boundary', () => {
fixture.detectChanges();
fixture.nativeElement.querySelector('.statistics-button').click();
await fixture.whenStable();
expect(
Array.from(document.querySelectorAll('[role="dialog"] dd'), (value) =>
value.textContent?.trim(),
),
).toEqual(
allDaysOff
? ['0', '4', '—', '0', '9', '9', '0', '0']
: ['0', '0', '5', '5', '—', '—', '0', '0'],
);
expect(figures(document.querySelector('[role="dialog"]')!)).toEqual([
['Leave days taken', '0 of 0'],
['Leave days not taken', '0'],
...(allDaysOff
? [
['Total days off', '9', 'including 4 weekend days and public holidays'],
['Time-off periods', '1', 'the longest: 9 days'],
['Longest stretch without leave', '0 working days'],
]
: [
['Total days off', '0'],
['Time-off periods', '0'],
['Longest stretch without leave', '5 working days'],
]),
['Public holidays bridged to a weekend', '0 of 0'],
]);
},
);
@@ -1034,22 +1029,25 @@ describe('CalendarYear planning outcome boundary', () => {
expect(dialog.getAttribute('aria-labelledby')).toBe('plan-statistics-title');
expect(dialog.getAttribute('aria-describedby')).toBe('plan-statistics-help');
await vi.waitFor(() => expect(document.activeElement).toBe(dialog.querySelector('h2')));
for (const [language, workUnit, calendarUnit, holidayLabel] of [
['de', 'Arbeitstage', 'Kalendertage', 'Feiertage mit Wochenendanschluss'],
['es', 'días laborables', 'días naturales', 'Festivos conectados con un fin de semana'],
['fr', 'jours ouvrés', 'jours calendaires', 'Jours fériés reliés à un week-end'],
for (const [language, workUnit, holidayLabel] of [
['de', '6 Arbeitstage', 'Feiertage mit Brücke zum Wochenende'],
['es', '6 días trabajados', 'Festivos que hacen puente'],
['fr', '6 jours travaillés', 'Jours fériés qui font un pont'],
]) {
translation.setLanguage(language);
fixture.detectChanges();
expect(dialog.textContent).toContain(workUnit);
expect(dialog.textContent).toContain(calendarUnit);
expect(text(dialog)).toContain(workUnit);
expect(dialog.textContent).toContain(holidayLabel);
expect(
Array.from(dialog.querySelectorAll('dd'), (value) => value.textContent?.trim()),
).toEqual(['2', '4', '3,333', '6', '2,5', '4', '0', '0']);
}
expect(dialog.textContent).toContain('Statistiques du planning');
expect(dialog.querySelector('dt')?.textContent).toContain('Nouveaux jours de congé posés');
expect(figures(dialog)).toEqual([
['Jours de congé posés', '2 sur 2'],
['Jours non posés', '0'],
['Jours de repos au total', '0', 'dont 4 jours de week-end et fériés'],
['Périodes de repos', '0', 'la plus longue : 4 jours'],
['Plus longue période sans congé', '6 jours travaillés'],
['Jours fériés qui font un pont', '0 sur 10'],
]);
expect(dialog.querySelector('button')?.textContent?.trim()).toBe('Fermer');
dialog.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true }),
@@ -1095,10 +1093,10 @@ describe('CalendarYear planning outcome boundary', () => {
const root: HTMLElement = fixture.nativeElement;
activateWithKeyboard(root.querySelector<HTMLButtonElement>('.statistics-button')!);
await fixture.whenStable();
expect(document.querySelector('[role="dialog"] dd')?.textContent?.trim()).toBe('2');
expect(text(document.querySelector('[role="dialog"] dd')!)).toBe('2 of 2');
TestBed.inject(PlanningCalculationService).start();
fixture.detectChanges();
expect(document.querySelector('[role="dialog"] dd')?.textContent?.trim()).toBe('2');
expect(text(document.querySelector('[role="dialog"] dd')!)).toBe('2 of 2');
TestBed.inject(PlanningCalculationService).start();
fixture.detectChanges();
const otherControl = document.createElement('button');
@@ -1117,7 +1115,7 @@ describe('CalendarYear planning outcome boundary', () => {
expect(opener).not.toBeNull();
opener!.click();
await fixture.whenStable();
expect(document.querySelector('[role="dialog"] dd')?.textContent?.trim()).toBe('1');
expect(text(document.querySelector('[role="dialog"] dd')!)).toBe('1 of 1');
} else {
expect(opener).toBeNull();
expect(document.activeElement).toBe(
@@ -1172,7 +1170,6 @@ describe('CalendarYear planning outcome boundary', () => {
(value) => (artifacts = value),
);
if (outcome.kind !== 'Plan') throw new Error(`Expected Plan, got ${outcome.kind}`);
localStorage.setItem('leaveBalances', '[]');
localStorage.setItem('vacationRules', '{"version":1,"rules":[]}');
await TestBed.configureTestingModule({
imports: [CalendarYear],
@@ -1195,11 +1192,11 @@ describe('CalendarYear planning outcome boundary', () => {
expect(summary).toContain('Two CP including booked leave');
expect(summary).toContain(
partial
? '1 Already booked + 1 leave days used = 2 / 2'
: '2 Already booked + 0 leave days used = 2 / 2',
? '1 already booked day + 1 leave day booked = 2 / 2'
: '2 already booked days + 0 leave days booked = 2 / 2',
);
expect(summary).toContain('Paid Leave');
expect(summary).toContain('no remaining balance debit');
expect(summary).toContain('Paid leave');
expect(summary).toContain('does not deduct them from your balances');
for (const day of declaredDays) {
const cell = root.querySelector<HTMLButtonElement>(
`button[data-date="${day.date}"]`,
@@ -1274,9 +1271,9 @@ describe('CalendarYear planning outcome boundary', () => {
const summary =
root.querySelector('.declared-period')?.textContent?.replace(/\s+/g, ' ') ?? '';
expect(summary).toContain(`${duration} days off in a row`);
expect(summary).toContain(`${gain} weekend & holiday days`);
expect(summary).toContain('0 leave days used');
expect(summary).toContain('no remaining balance debit');
expect(summary).toContain(`${gain} weekend and public-holiday days`);
expect(summary).toContain('0 leave days booked');
expect(summary).toContain('does not deduct them from your balances');
const declared = root.querySelector<HTMLButtonElement>(`button[data-date="${start}"]`)!;
expect(declared.classList).toContain('other');
expect(declared.getAttribute('aria-label')).toContain('Already booked');
@@ -1286,9 +1283,7 @@ describe('CalendarYear planning outcome boundary', () => {
expect(context.disabled).toBe(true);
expect(context.classList).toContain('context-only');
expect(context.classList).toContain('selected');
expect(context.getAttribute('aria-label')).toContain(
'Context date outside the planning horizon',
);
expect(context.getAttribute('aria-label')).toContain('Outside the planning period');
if (outsideDeclarations.length) {
expect(context.classList).toContain('cp');
expect(context.getAttribute('aria-label')).toContain('Already booked');
@@ -1336,7 +1331,6 @@ describe('CalendarYear planning outcome boundary', () => {
(value) => (artifacts = value),
);
if (outcome.kind !== 'Plan') throw new Error('Expected a plan.');
localStorage.setItem('leaveBalances', '[]');
localStorage.setItem('vacationRules', '{"version":1,"rules":[]}');
await TestBed.configureTestingModule({
imports: [CalendarYear],
@@ -1438,7 +1432,7 @@ describe('CalendarYear planning outcome boundary', () => {
fixture.detectChanges();
expect(root.querySelector('.declaration-preview')).toBeNull();
expect(root.querySelector('[role="status"]')?.textContent).toContain(
'Jours déjà posés enregistrés : 3 (Congé Payé). Déclarations supprimées : 1.',
'Jours déjà posés enregistrés : 3 (Congé payé). Jours déjà posés retirés : 1.',
);
expect(new UserInputService().declaredDaysSignal()).toEqual([
{ date: '2024-04-26', type: 'other' },
@@ -1459,7 +1453,7 @@ describe('CalendarYear planning outcome boundary', () => {
expect(input.declaredDaysSignal()).toHaveLength(4);
pointer('pointerup', '2024-04-30');
expect(root.querySelector('[role="status"]')?.textContent).toContain(
'Déclarations supprimées : 2.',
'Jours déjà posés retirés : 2.',
);
expect(new UserInputService().declaredDaysSignal()).toEqual([
{ date: '2024-04-26', type: 'other' },
@@ -1637,7 +1631,6 @@ describe('CalendarYear planning outcome boundary', () => {
it('keeps the preceding calendar until a submitted snapshot returns and ignores later edits', async () => {
localStorage.setItem('vacationRules', '{"version":1,"rules":[]}');
localStorage.setItem('leaveBalances', '[]');
await TestBed.configureTestingModule({
imports: [CalendarYear, UserInput],
providers: [provideZonelessChangeDetection()],
@@ -2007,7 +2000,10 @@ describe('CalendarYear planning outcome boundary', () => {
for (const [stage, expected] of [
['validation', 'Checking your inputs'],
['obligations', 'Satisfying obligations'],
['optimization:default-holiday-week-value', 'Applying “Semaines fériées”'],
[
'optimization:default-holiday-week-value',
'Applying “Semaines avec un jour férié”',
],
['preference:spring', 'Applying “Spring break”'],
['expiry', 'Using balances that expire first'],
['dates', 'Settling the final dates'],
@@ -2093,10 +2089,10 @@ describe('CalendarYear planning outcome boundary', () => {
at(20_000);
expect(text('.spinner-text')).toBe('95%');
expect(root.querySelector('.calculation-remaining')).toBeNull();
expect(text('.sr-only[role="status"]')).toBe('Calculating...');
expect(text('.sr-only[role="status"]')).toBe('Calculating…');
at(60_000);
expect(text('.calculation-remaining')).toBe('Taking longer than expected');
expect(text('.loading-overlay [role="status"]')).toBe('Calculating...');
expect(text('.loading-overlay [role="status"]')).toBe('Calculating…');
expect(text('.sr-only[role="status"]')).toBe('Taking longer than expected');
fixture.componentInstance['liveMessage'].set('');
at(120_000);
@@ -2165,7 +2161,7 @@ describe('CalendarYear planning outcome boundary', () => {
await new Promise<void>((resolve) => setTimeout(resolve, 0));
fixture.detectChanges();
expect(root.querySelector('.planning-status')?.textContent).toContain(
withIncumbent ? 'Calcul annulé — plan partiel' : 'Calcul annulé',
withIncumbent ? 'Calcul annulé — planning partiel' : 'Calcul annulé',
);
expect(root.querySelectorAll('button.selected')).toHaveLength(withIncumbent ? 2 : 0);
expect(root.querySelector('.loading-overlay')).toBeNull();
@@ -2553,8 +2549,10 @@ describe('CalendarYear planning outcome boundary', () => {
const root = fixture.nativeElement as HTMLElement;
expect(service.displayedPlan()).toBeDefined();
expect(
Array.from(root.querySelectorAll('.plan-summary dd')).map((e) => e.textContent?.trim()),
).toEqual(['2', '4', '6']);
Array.from(root.querySelectorAll('.plan-summary dd:not(.note)')).map(
(value) => text(value)?.split(' ')[0],
),
).toEqual(['2', '0', '6']);
service.start();
await settle();
@@ -2564,6 +2562,79 @@ describe('CalendarYear planning outcome boundary', () => {
expect(root.querySelectorAll('button.selected')).toHaveLength(0);
});
it.each([true, false])(
'calls out unplaced days, lost ones and weeks with one workday (lost days: %s)',
async (lost) => {
const remaining = (quantity: number, classification: 'at-risk' | 'deferred') => ({
id: classification,
type: 'cp' as const,
quantity,
availableFrom: '2024-01-01',
expiryDate: '2024-12-31',
classification,
reason: { code: 'all-dates-occupied' as const, message: '' },
earned: false,
});
const { calendar, creation } = calendarFor({
...plan,
// With Monday placed and Wednesday and Thursday public holidays, only Friday is worked.
declaredDays: lost ? [{ date: '2024-05-07', type: 'rtt' }] : [],
remainingBalances: [
remaining(3, 'deferred'),
...(lost ? [remaining(2, 'at-risk')] : []),
],
});
await TestBed.configureTestingModule({
imports: [CalendarYear],
providers: [
provideZonelessChangeDetection(),
{ provide: CalendarService, useValue: calendar },
],
}).compileComponents();
spyOnCreation().mockImplementation(creation);
TestBed.inject(TranslationService).setLanguage('en');
const fixture = TestBed.createComponent(CalendarYear);
fixture.detectChanges();
await fixture.whenStable();
await new Promise<void>((resolve) => setTimeout(resolve, 0));
fixture.detectChanges();
const root = fixture.nativeElement as HTMLElement;
expect(figures(root, '.plan-summary')).toEqual([
lost
? ['Leave days taken', '2 of 7', '5 days not taken 2 of them lost']
: ['Leave days taken', '2 of 5', '3 days not taken'],
['Total days off', '0', 'including 4 weekend days and public holidays'],
['Longest stretch without leave', '6 working days'],
]);
expect(root.querySelector('.lost')?.textContent?.trim()).toBe(
lost ? '2 of them lost' : undefined,
);
root.querySelector<HTMLButtonElement>('.statistics-button')!.click();
await fixture.whenStable();
const dialog = document.querySelector('[role="dialog"]')!;
expect(figures(dialog)[1]).toEqual(
lost
? [
'Leave days not taken',
'5',
'2 of them lost A lost day expires before it could be taken.',
]
: [
'Leave days not taken',
'3',
'Nothing is lost: expiry falls after the planning period.',
],
);
const warning = dialog.querySelector('.one-workday-weeks');
expect(warning ? text(warning) : undefined).toBe(
lost
? '1 week with a single working day Coming in for a single day in a whole week is rarely desirable. 6 May 2024 – 12 May 2024 Only working day · 10 May 2024'
: undefined,
);
},
);
it('keeps and summarizes a returned result', async () => {
const { calendar, creation } = calendarFor(plan, explanation);
await TestBed.configureTestingModule({
@@ -2583,9 +2654,276 @@ describe('CalendarYear planning outcome boundary', () => {
TestBed.inject(PlanningCalculationService).displayedPlan()?.remainingBalances,
).toEqual(plan.remainingBalances);
const summaryValues = Array.from(
fixture.nativeElement.querySelectorAll('.plan-summary dd') as NodeListOf<HTMLElement>,
).map((element) => element.textContent?.trim());
expect(summaryValues).toEqual(['2', '4', '6']);
fixture.nativeElement.querySelectorAll(
'.plan-summary dd:not(.note)',
) as NodeListOf<HTMLElement>,
).map((value) => text(value)?.split(' ')[0]);
expect(summaryValues).toEqual(['2', '0', '6']);
});
it('attaches the calculation date to the results heading and status', async () => {
const { calendar, creation } = calendarFor({ ...plan, calculationDate: '2024-05-01' });
await TestBed.configureTestingModule({
imports: [CalendarYear],
providers: [
provideZonelessChangeDetection(),
{ provide: CalendarService, useValue: calendar },
],
}).compileComponents();
spyOnCreation().mockImplementation(creation);
TestBed.inject(TranslationService).setLanguage('en');
const fixture = TestBed.createComponent(CalendarYear);
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
const meta = fixture.nativeElement.querySelector('.results-heading .calculation-date');
expect(meta?.textContent?.replace(/\s+/g, ' ').trim()).toBe(
`Calculation date : ${fixture.componentInstance['displayDate']('2024-05-01')}`,
);
expect(meta.previousElementSibling.classList).toContain('planning-status');
});
it.each([true, false])(
'groups the applied rules in one closed disclosure between the summary and the calendar (rules: %s)',
async (withRules) => {
const applied: PlanOutcome = {
...plan,
timeWindowContributions: [
{
ruleId: 'window',
label: 'Window rule',
requested: 2,
declaredDays: [{ date: '2024-05-02', type: 'cp' }],
placementDates: ['2024-05-03'],
},
],
ifThenContributions: [
{
ruleId: 'bridge',
label: 'Bridge rule',
occurrence: '2024-05-08',
requested: 1,
declaredDays: [],
placementDates: ['2024-05-06'],
},
],
timeOffPeriods: [
{
start: '2024-05-02',
end: '2024-05-05',
duration: 4,
placementDates: ['2024-05-03'],
declaredDates: ['2024-05-02'],
nonWorkingDates: ['2024-05-04', '2024-05-05'],
nonWorkingDayGain: 2,
},
],
};
const { calendar, creation } = calendarFor(withRules ? applied : plan, explanation);
await TestBed.configureTestingModule({
imports: [CalendarYear],
providers: [
provideZonelessChangeDetection(),
{ provide: CalendarService, useValue: calendar },
],
}).compileComponents();
spyOnCreation().mockImplementation(creation);
const translation = TestBed.inject(TranslationService);
translation.setLanguage('en');
const fixture = TestBed.createComponent(CalendarYear);
fixture.detectChanges();
await fixture.whenStable();
await new Promise<void>((resolve) => setTimeout(resolve, 0));
fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
const details = root.querySelector<HTMLDetailsElement>(
'.plan-insights > .applied-rules',
);
if (!withRules) {
expect(details).toBeNull();
expect(root.querySelector('.declared-rule, .declared-period')).toBeNull();
return;
}
expect(details!.open).toBe(false);
const summary = details!.querySelector<HTMLElement>('summary')!;
expect(summary.textContent?.replace(/\s+/g, ' ')).toContain('Rules applied');
expect(summary.textContent?.replace(/\s+/g, ' ')).toContain('Entries : 3');
expect(root.querySelectorAll('.declared-rule, .declared-period')).toHaveLength(3);
expect(
root.querySelectorAll(
'.applied-rules .declared-rule, .applied-rules .declared-period',
),
).toHaveLength(3);
const follows = (earlier: Element, later: Element) =>
Boolean(earlier.compareDocumentPosition(later) & Node.DOCUMENT_POSITION_FOLLOWING);
expect(follows(root.querySelector('.plan-summary')!, details!)).toBe(true);
expect(follows(root.querySelector('.plan-details')!, details!)).toBe(true);
expect(follows(details!, root.querySelector('.calendar-legend')!)).toBe(true);
expect(follows(details!, root.querySelector('.month-grid')!)).toBe(true);
for (const [language, copy] of Object.entries(translationsMap)) {
translation.setLanguage(language);
fixture.detectChanges();
expect(summary.textContent).toContain(copy.planning.appliedRules.title);
expect(summary.textContent).toContain(copy.planning.appliedRules.entries);
}
activateWithKeyboard(summary);
expect(details!.open).toBe(true);
},
);
describe('time-off period list', () => {
const periods: PlanOutcome = {
...plan,
timeOffPeriods: [
{
start: '2024-05-04',
end: '2024-05-08',
duration: 5,
placementDates: ['2024-05-06'],
nonWorkingDates: ['2024-05-04', '2024-05-05', '2024-05-07', '2024-05-08'],
nonWorkingDayGain: 4,
},
// Plain weekend: no leave placement and no declared day, so not listed.
{
start: '2024-05-11',
end: '2024-05-12',
duration: 2,
placementDates: [],
nonWorkingDates: ['2024-05-11', '2024-05-12'],
nonWorkingDayGain: 2,
},
{
start: '2024-05-02',
end: '2024-05-03',
duration: 2,
placementDates: ['2024-05-03'],
declaredDates: ['2024-05-02'],
nonWorkingDates: [],
nonWorkingDayGain: 0,
},
],
};
async function show(outcome: PlanningOutcome, explained?: PlanningExplanation) {
const { calendar, creation } = calendarFor(outcome, explained);
await TestBed.configureTestingModule({
imports: [CalendarYear],
providers: [
provideZonelessChangeDetection(),
{ provide: CalendarService, useValue: calendar },
],
}).compileComponents();
spyOnCreation().mockImplementation(creation);
TestBed.inject(TranslationService).setLanguage('en');
const fixture = TestBed.createComponent(CalendarYear);
fixture.detectChanges();
await fixture.whenStable();
await new Promise<void>((resolve) => setTimeout(resolve, 0));
fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
return {
fixture,
root,
details: root.querySelector<HTMLDetailsElement>(
'.plan-insights > .time-off-periods',
),
};
}
it('lists the periods with leave in a closed disclosure among the others', async () => {
const { fixture, root, details } = await show(periods, explanation);
expect(details!.open).toBe(false);
const summary = details!.querySelector('summary')!.textContent?.replace(/\s+/g, ' ');
expect(summary).toContain('Your time-off periods');
expect(summary).toContain('Periods : 2');
const translation = TestBed.inject(TranslationService);
for (const [language, copy] of Object.entries(translationsMap)) {
translation.setLanguage(language);
fixture.detectChanges();
const shown = details!.querySelector('summary')!.textContent;
expect(shown).toContain(copy.planning.timeOffPeriods.title);
expect(shown).toContain(copy.planning.timeOffPeriods.count);
expect(details!.querySelector('.help')!.textContent).toBe(
copy.planning.timeOffPeriods.help,
);
}
expect(
[...details!.querySelectorAll<HTMLElement>('li > button')].map(
(b) => b.dataset['start'],
),
).toEqual(['2024-05-02', '2024-05-04']);
const follows = (earlier: Element, later: Element) =>
Boolean(earlier.compareDocumentPosition(later) & Node.DOCUMENT_POSITION_FOLLOWING);
expect(follows(root.querySelector('.plan-summary')!, details!)).toBe(true);
expect(follows(root.querySelector('.plan-details')!, details!)).toBe(true);
expect(follows(details!, root.querySelector('.month-grid')!)).toBe(true);
});
it.each([
['without any period', plan],
[
'without a period with leave',
{ ...periods, timeOffPeriods: [periods.timeOffPeriods[1]] },
],
['without a plan', { kind: 'InvalidInput', reasons: [] } as PlanningOutcome],
])('is absent %s', async (_label, outcome) => {
const { root, details } = await show(outcome);
expect(details).toBeNull();
expect(root.querySelector('app-time-off-periods')).toBeNull();
});
it('follows the partial plan of an interrupted calculation', async () => {
const { details } = await show({
kind: 'PlanningIncomplete',
incumbent: periods,
completedStages: [],
reasons: [{ code: 'user-cancelled', message: 'Cancelled' }],
});
expect(details!.querySelectorAll('li > button')).toHaveLength(2);
});
describe.each([
[false, 'smooth'],
[true, 'auto'],
])('choosing a period (reduced motion: %s)', (reduced, behavior) => {
const scrollIntoView = vi.fn();
beforeEach(() => {
scrollIntoView.mockClear();
Element.prototype.scrollIntoView = scrollIntoView;
const base = window.matchMedia('(prefers-reduced-motion: reduce)');
vi.spyOn(window, 'matchMedia').mockImplementation((query) => ({
...base,
matches: reduced,
media: query,
}));
});
afterEach(() => {
vi.restoreAllMocks();
delete (Element.prototype as Partial<Element>).scrollIntoView;
});
it('scrolls to its first leave day and focuses it', async () => {
const { fixture, details } = await show(periods, explanation);
// A keyboard user opens the disclosure, then activates the second period.
activateWithKeyboard(details!.querySelector('summary')!);
const [, second] = details!.querySelectorAll<HTMLButtonElement>('li > button');
activateWithKeyboard(second);
fixture.detectChanges();
const day = fixture.nativeElement.querySelector('button[data-date="2024-05-06"]');
expect(document.activeElement).toBe(day);
expect(scrollIntoView).toHaveBeenCalledOnce();
expect(scrollIntoView.mock.contexts[0]).toBe(day);
expect(scrollIntoView).toHaveBeenCalledWith({ block: 'center', behavior });
});
it('prefers a declared day when it comes first', async () => {
const { fixture, details } = await show(periods, explanation);
activateWithKeyboard(details!.querySelector<HTMLButtonElement>('li > button')!);
expect(document.activeElement).toBe(
fixture.nativeElement.querySelector('button[data-date="2024-05-02"]'),
);
});
});
});
it('shows muted, disabled context dates in an adjacent year', async () => {
@@ -2643,9 +2981,7 @@ describe('CalendarYear planning outcome boundary', () => {
expect(contextDate.classList).toContain('explained-period');
expect(contextDate.getAttribute('aria-label')).toContain('Explained time-off period');
expect(root.querySelectorAll('button.explained-period')).toHaveLength(4);
expect(contextDate.getAttribute('aria-label')).toContain(
'Context date outside the planning horizon',
);
expect(contextDate.getAttribute('aria-label')).toContain('Outside the planning period');
expect(
root.querySelector<HTMLButtonElement>('button[data-date="2024-01-02"]')?.disabled,
).toBe(false);
@@ -2687,7 +3023,7 @@ describe('CalendarYear planning outcome boundary', () => {
{
kind: 'at-risk',
code: 'at-risk',
label: 'Protects leave at risk of expiry.',
label: 'This day prevents losing leave that expires within the planning period.',
},
{
kind: 'supporting',
@@ -2751,12 +3087,14 @@ describe('CalendarYear planning outcome boundary', () => {
expect(planDetails.open).toBe(true);
expect(root.querySelector('.plan-insights')!.firstElementChild).toBe(planDetails);
expect(root.querySelector('.leave-story')?.textContent).toContain('Spring rule');
expect(root.querySelector('.leave-story')?.textContent).toContain('Protects leave at risk');
expect(root.querySelector('.leave-story')?.textContent).toContain('could be saved');
expect(root.querySelector('.leave-story')?.textContent).toContain('prevents losing leave');
expect(root.querySelector('.leave-story')?.textContent).toContain(
'could have been kept for later',
);
expect(root.querySelector('.break-equation span:last-child strong')?.textContent).toBe('4');
expect(root.querySelector('.break-story')?.textContent).toContain('days off in a row');
expect(root.querySelector('.decisive-summary')?.textContent).toContain(
'Weekend & holiday days in your breaks',
'Weekend and public-holiday days in your time-off periods',
);
expect(root.querySelectorAll('button[data-date="2024-05-03"].selected')).toHaveLength(1);
expect(root.querySelectorAll('button[data-date="2024-05-06"].selected')).toHaveLength(1);
@@ -2811,7 +3149,7 @@ describe('CalendarYear planning outcome boundary', () => {
fixture.detectChanges();
expect(document.activeElement).toBe(date);
expect(date.getAttribute('aria-current')).toBe('date');
expect(date.getAttribute('aria-label')).toContain('Paid Leave');
expect(date.getAttribute('aria-label')).toContain('Paid leave');
});
it('shows a lost connection as a warning that keeps the plan, not as a planner error', async () => {
@@ -2881,10 +3219,10 @@ describe('CalendarYear planning outcome boundary', () => {
fixture.detectChanges();
const incumbent = fixture.nativeElement.querySelector('.incomplete-incumbent').textContent;
expect(incumbent).toContain('Completed stages: Use leave before it expires');
expect(incumbent).toContain('Holiday-week priority (points)');
expect(incumbent).toContain('Whole weeks taken around a public holiday (points)');
expect(incumbent).not.toContain('holiday-week-value');
expect(incumbent).toContain(
'Planning stopped at its time limit before all quality stages completed.',
'The calculation reached its time limit before completing all its stages.',
);
expect(incumbent).not.toContain('Planning stopped at the deadline.');
expect(fixture.nativeElement.querySelectorAll('button.selected')).toHaveLength(2);
@@ -2941,7 +3279,7 @@ describe('CalendarYear planning outcome boundary', () => {
expect(document.querySelector('[role="dialog"]')).not.toBeNull();
expect(root.querySelectorAll('button.selected')).toHaveLength(2);
expect(root.querySelectorAll('.status-marker, .hypothetical-marker')).toHaveLength(0);
expect(root.querySelector('.calendar-legend')?.textContent).not.toContain('Eligible');
expect(root.querySelector('.calendar-legend')?.textContent).not.toContain('Available');
expect(root.querySelector<HTMLButtonElement>('button.current')?.dataset['date']).toBe(
'2024-05-06',
);
@@ -3011,22 +3349,22 @@ describe('CalendarYear planning outcome boundary', () => {
const compare = root.querySelector<HTMLButtonElement>('.compare-dates-button')!;
activateWithKeyboard(compare);
fixture.detectChanges();
expect(live()).toContain('Analyzing every date');
expect(live()).toContain('Checking the other possible dates');
await fixture.whenStable();
fixture.detectChanges();
expect(live()).toBe('Date alternatives could not be calculated.');
expect(live()).toBe('The other dates could not be checked.');
expect(compare.textContent).toContain('Retry date analysis');
document.querySelector<HTMLButtonElement>('.comparison-done')!.click();
fixture.detectChanges();
expect(compare.textContent).toContain('Compare other dates');
await fixture.whenStable();
fixture.detectChanges();
expect(live()).toBe('Date alternatives are ready.');
expect(live()).toBe('You can now compare other dates.');
root.querySelector<HTMLButtonElement>('button[data-date="2024-05-08"]')!.click();
fixture.detectChanges();
expect(live()).toBe(
'2024-05-08. Date alternatives. Ineligible. This is already a day off (weekend or public holiday). No leave is needed.',
'2024-05-08. Compared date. Unavailable. This is already a day off (weekend or public holiday). No leave is needed.',
);
expect(document.querySelector('.unavailable-date')?.textContent).toContain(
'No leave is needed.',
@@ -3052,7 +3390,7 @@ describe('CalendarYear planning outcome boundary', () => {
details.open = false;
details.dispatchEvent(new Event('toggle'));
},
announced: 'Analyzing every date in the horizon… 3 May 2024',
announced: 'Checking the other possible dates… 3 May 2024',
},
])(
'closes a pending comparison and ignores its late result when $event',
@@ -3110,6 +3448,7 @@ describe('CalendarYear planning outcome boundary', () => {
{ id: 'preference:spring', direction: 'maximize', value: 1 },
{ id: 'non-working-day-gain', direction: 'maximize', value: 0 },
{ id: 'longest-work-sequence', direction: 'minimize', value: 12 },
{ id: 'optimization:gain', direction: 'maximize', value: 1 },
{ id: 'placement-date', direction: 'minimize', value: 'removed' },
],
};
@@ -3119,6 +3458,7 @@ describe('CalendarYear planning outcome boundary', () => {
{ id: 'preference:spring', direction: 'maximize', value: 2 },
{ id: 'non-working-day-gain', direction: 'maximize', value: 4 },
{ id: 'longest-work-sequence', direction: 'minimize', value: 6 },
{ id: 'optimization:gain', direction: 'maximize', value: 3 },
{ id: 'placement-date', direction: 'minimize', value: '2024-05-03' },
],
};
@@ -3155,6 +3495,13 @@ describe('CalendarYear planning outcome boundary', () => {
placeDays: 2,
placeType: 'cp',
},
{
id: 'gain',
name: 'Gain',
type: 'optimization',
force: 'preference',
configuration: OPTIMIZATION_PRESETS.nonWorkingDayGain,
},
];
await TestBed.configureTestingModule({
imports: [CalendarYear],
@@ -3178,31 +3525,43 @@ describe('CalendarYear planning outcome boundary', () => {
),
).toEqual(['2', '2', '4']);
expect(element.querySelector('.leave-story')?.textContent).toContain(
'This date uses 1 day from Paid leave.',
'This date uses 1 day from “Paid leave”.',
);
expect(
Array.from(element.querySelectorAll('.day-impact td'), (node) =>
node.textContent?.trim(),
),
).toEqual(['1', '0', '1', '2', '0', '4', '12', '6']);
).toEqual(['1', '0', '1', '2', '0', '4', '12', '6', '1', '3']);
const gainRow = Array.from(element.querySelectorAll('.day-impact tbody th')).find((row) =>
row.textContent?.includes('Gain — '),
)!;
expect(gainRow.textContent?.trim()).toBe(
'Gain — Attach leave to weekends and public holidays, to gain as many days off as possible without taking them as leave',
);
expect(gainRow.querySelector('small')).toBeNull();
expect(element.querySelector('.day-impact')?.textContent).toContain(
'Preference: Spring break',
);
expect(element.querySelector('.day-impact')?.textContent).toContain(
'Leave days in this preferred period.',
'Leave days within the requested period.',
);
expect(element.querySelector('.day-impact')?.textContent).not.toContain('placement-date');
const details = element.querySelector<HTMLDetailsElement>('.technical-details')!;
details.open = true;
expect(details.querySelectorAll('.criteria-table')).toHaveLength(1);
expect(details.querySelector('.decisive-row')?.textContent).toContain(
'Leave left at risk of expiry',
'Days that expire unbooked',
);
expect(details.querySelector('.decisive-label')?.textContent).toContain(
'Deciding criterion',
);
expect(details.querySelector('.decisive-label')?.textContent).toContain('First difference');
expect(details.querySelector('.balance-ledger')?.textContent).toContain(
'Unused days in the final plan',
'Days not booked on this balance',
);
expect(details.querySelectorAll('.criteria-table tbody tr')).toHaveLength(5);
expect(details.querySelector('.criteria-table')?.textContent).toContain(
'Maximize Sum: Weekend and public-holiday days included (calendar days) — Time-off periods.',
);
expect(details.querySelectorAll('.criteria-table tbody tr')).toHaveLength(4);
expect(details.querySelector('.criteria-detail')?.textContent).not.toContain('2024-05-03');
expect(details.querySelector('.tie-breaks')?.textContent).toContain('Earlier dates first');
expect(details.querySelector<HTMLDetailsElement>('.criterion-help')?.open).toBe(false);
@@ -3233,11 +3592,14 @@ describe('CalendarYear planning outcome boundary', () => {
await fixture.whenStable();
await new Promise<void>((resolve) => setTimeout(resolve, 0));
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.conflict-explanation').closest('details'),
).toBeNull();
expect(fixture.nativeElement.querySelector('.conflict-explanation').textContent).toContain(
'Required spring leave',
);
expect(fixture.nativeElement.querySelector('.conflict-explanation').textContent).toContain(
'The obligations require more leave of one type than is available.',
'Your obligations need more days of one leave type than your balances contain.',
);
});
@@ -70,6 +70,16 @@
<mat-icon aria-hidden="true">check_circle</mat-icon>
{{ outcomeLabel(planningOutcome()!) }}
</p>
} @else if (!isLoading() && nothingToPlan()) {
<p class="planning-status info">
<mat-icon aria-hidden="true">info</mat-icon>
{{ tr().planning.invitation }}
</p>
}
@if (displayedPlan()?.calculationDate; as calculationDate) {
<p class="calculation-date">
{{ tr().planning.calculationDate }} : {{ displayDate(calculationDate) }}
</p>
}
</div>
@if (displayedPlan()) {
@@ -138,102 +148,40 @@
}
}
@if (displayedPlan(); as plan) {
@if (statistics(); as stats) {
@let copy = tr().planning.statistics;
<dl class="plan-summary">
<div>
<dt>{{ tr().planning.daysPlaced }}</dt>
<dd>{{ plan.placements.length }}</dd>
<dt>{{ copy.leaveDays }}</dt>
<dd>
{{ formatStatistic(stats.placed) }} <small>{{ outOf(stats.available) }}</small>
</dd>
@if (stats.unplaced) {
<dd class="note">
{{ counted(copy.unplacedDays, stats.unplaced) }}
@if (stats.lost) {
<span class="lost">{{ counted(copy.lostDays, stats.lost) }}</span>
}
</dd>
}
</div>
<div>
<dt>{{ tr().planning.daysGained }}</dt>
<dd>{{ plan.metrics.nonWorkingDayGain }}</dd>
<dt>{{ copy.daysOff }}</dt>
<dd>{{ formatStatistic(stats.daysOff) }}</dd>
@if (stats.weekendAndHolidayDays) {
<dd class="note">
{{ counted(copy.weekendAndHolidayDays, stats.weekendAndHolidayDays) }}
</dd>
}
</div>
<div>
<dt>{{ tr().planning.longestWorkSequence }}</dt>
<dd>{{ plan.metrics.longestWorkSequence }}</dd>
<dt>{{ copy.longestWorkSequence }}</dt>
<dd>
{{ formatStatistic(stats.longestWorkSequence) }}
<small>{{ counted(copy.workedDays, stats.longestWorkSequence) }}</small>
</dd>
</div>
</dl>
@for (contribution of plan.timeWindowContributions ?? []; track contribution.ruleId) {
<section class="outcome-explanation declared-rule">
<h3>{{ contribution.label }}</h3>
<p>
{{ contribution.declaredDays.length }} {{ tr().bookedDays.booked }} +
{{ contribution.placementDates.length }}
{{ tr().planning.explanation.leaveDays }} =
<strong
>{{
contribution.declaredDays.length + contribution.placementDates.length
}}
/ {{ contribution.requested }}</strong
>
</p>
<p>
@for (day of contribution.declaredDays; track day.date) {
<span>{{ displayDate(day.date) }} · {{ tr().dayTypes[day.type] }} </span>
}
</p>
<p>{{ tr().bookedDays.fixed }}</p>
</section>
}
@if (plan.calculationDate) {
<p>{{ tr().planning.calculationDate }} : {{ displayDate(plan.calculationDate) }}</p>
}
@for (
contribution of plan.ifThenContributions ?? [];
track contribution.ruleId + contribution.occurrence
) {
<section class="outcome-explanation declared-rule">
<h3>{{ contribution.label }} · {{ displayDate(contribution.occurrence) }}</h3>
<p>
{{ contribution.declaredDays.length }} {{ tr().bookedDays.booked }} +
{{ contribution.placementDates.length }}
{{ tr().planning.explanation.leaveDays }} =
<strong>{{ contribution.requested }} / {{ contribution.requested }}</strong>
</p>
@for (day of contribution.declaredDays; track day.date) {
<span>{{ displayDate(day.date) }} · {{ tr().dayTypes[day.type] }} </span>
}
@if (contribution.declaredDays.length) {
<p>{{ tr().bookedDays.fixed }}</p>
}
@if (contribution.earnedEntitlement; as earned) {
<p>
{{
earned.added
? tr().planning.futureEntitlement
: tr().planning.includedEntitlement
}}
: {{ earned.quantity }} {{ tr().dayTypes[earned.type] }}
</p>
<p>
{{ tr().planning.details.available }}
{{ displayDate(earned.availableFrom) }} ·
{{ tr().planning.details.expires }} {{ displayDate(earned.expiryDate) }}
</p>
}
</section>
}
@for (period of plan.timeOffPeriods; track period.start) {
@if (period.declaredDates?.length) {
<section class="outcome-explanation declared-period">
<h3>
{{ tr().planning.explanation.breakTitle }} ·
{{ displayDate(period.start) }} – {{ displayDate(period.end) }}
</h3>
<p>
{{ period.declaredDates!.length }} {{ tr().bookedDays.booked }} +
{{ period.placementDates.length }}
{{ tr().planning.explanation.leaveDays }} +
{{ period.nonWorkingDates.length }}
{{ tr().planning.explanation.freeDays }} =
<strong
>{{ period.duration }} {{ tr().planning.explanation.daysOff }}</strong
>
</p>
<p>{{ tr().bookedDays.fixed }}</p>
</section>
}
}
}
<div class="plan-insights">
@@ -340,26 +288,42 @@
@if (period.declaredDates?.length) {
<span
><strong>{{ period.declaredDates!.length }}</strong
>{{ tr().bookedDays.booked }}</span
>{{
counted(
tr().planning.explanation.bookedDays,
period.declaredDates!.length
)
}}</span
>
<span>+</span>
}
<span
><strong>{{ period.placementDates.length }}</strong
>{{ tr().planning.explanation.leaveDays }}</span
>{{
counted(
tr().planning.explanation.leaveDays,
period.placementDates.length
)
}}</span
>
<span>+</span>
<span
><strong>{{ period.nonWorkingDates.length }}</strong
>{{ tr().planning.explanation.freeDays }}</span
>{{
counted(
tr().planning.explanation.freeDays,
period.nonWorkingDates.length
)
}}</span
>
<span>=</span>
<span
><strong>{{ period.duration }}</strong
>{{ tr().planning.explanation.daysOff }}</span
>{{
counted(tr().planning.explanation.daysOff, period.duration)
}}</span
>
</div>
<p>{{ tr().planning.explanation.wholeBreak }}</p>
</section>
}
<div class="leave-story">
@@ -432,7 +396,10 @@
@for (change of placementChanges(); track change.id) {
<tr [class.decisive-row]="change.id === decisiveObjective">
<th scope="row">
{{ change.label }}<small>{{ change.help }}</small>
{{ change.label }}
@if (change.help) {
<small>{{ change.help }}</small>
}
@if (change.id === decisiveObjective) {
<span class="decisive-label">{{
tr().planning.details.firstDifference
@@ -453,7 +420,6 @@
<details class="technical-details">
<summary>{{ tr().planning.technicalDetails }}</summary>
<div class="calculation-content">
<p class="calculation-intro">{{ tr().planning.details.intro }}</p>
<section class="balance-detail" aria-labelledby="detail-balance-title">
<h4 id="detail-balance-title">
{{ tr().planning.details.balance }} ·
@@ -516,6 +482,186 @@
{{ tr().planning.explanationError }} {{ reasonLabel(explanationError()!) }}
</p>
}
@if (displayedPlan(); as plan) {
@if (appliedRuleCount(); as count) {
<details class="applied-rules">
<summary>
<mat-icon aria-hidden="true">rule</mat-icon>
<span
>{{ tr().planning.appliedRules.title
}}<small
>{{ tr().planning.appliedRules.entries }} : {{ count }}</small
></span
>
<mat-icon class="disclosure-chevron" aria-hidden="true"
>expand_more</mat-icon
>
</summary>
<div class="applied-rules-content">
@for (
contribution of plan.timeWindowContributions ?? [];
track contribution.ruleId
) {
<section class="outcome-explanation declared-rule">
<h3>{{ contribution.label }}</h3>
<p>
{{ contribution.declaredDays.length }}
{{
counted(
tr().planning.explanation.bookedDays,
contribution.declaredDays.length
)
}}
+
{{ contribution.placementDates.length }}
{{
counted(
tr().planning.explanation.leaveDays,
contribution.placementDates.length
)
}}
=
<strong
>{{
contribution.declaredDays.length +
contribution.placementDates.length
}}
/ {{ contribution.requested }}</strong
>
</p>
<p>
@for (day of contribution.declaredDays; track day.date) {
<span
>{{ displayDate(day.date) }} ·
{{ tr().dayTypes[day.type] }}
</span>
}
</p>
<p>{{ tr().bookedDays.fixed }}</p>
</section>
}
@for (
contribution of plan.ifThenContributions ?? [];
track contribution.ruleId + contribution.occurrence
) {
<section class="outcome-explanation declared-rule">
<h3>
{{ contribution.label }} ·
{{ displayDate(contribution.occurrence) }}
</h3>
<p>
{{ contribution.declaredDays.length }}
{{
counted(
tr().planning.explanation.bookedDays,
contribution.declaredDays.length
)
}}
+
{{ contribution.placementDates.length }}
{{
counted(
tr().planning.explanation.leaveDays,
contribution.placementDates.length
)
}}
=
<strong
>{{ contribution.requested }} /
{{ contribution.requested }}</strong
>
</p>
@for (day of contribution.declaredDays; track day.date) {
<span
>{{ displayDate(day.date) }} · {{ tr().dayTypes[day.type] }}
</span>
}
@if (contribution.declaredDays.length) {
<p>{{ tr().bookedDays.fixed }}</p>
}
@if (contribution.earnedEntitlement; as earned) {
<p>
{{
earned.added
? tr().planning.futureEntitlement
: tr().planning.includedEntitlement
}}
: {{ earned.quantity }} {{ tr().dayTypes[earned.type] }}
</p>
<p>
{{ tr().planning.details.available }}
{{ displayDate(earned.availableFrom) }} ·
{{ tr().planning.details.expires }}
{{ displayDate(earned.expiryDate) }}
</p>
}
</section>
}
@for (period of declaredPeriods(); track period.start) {
<section class="outcome-explanation declared-period">
<h3>
{{ tr().planning.explanation.breakTitle }} ·
{{ displayDate(period.start) }} – {{ displayDate(period.end) }}
</h3>
<p>
{{ period.declaredDates!.length }}
{{
counted(
tr().planning.explanation.bookedDays,
period.declaredDates!.length
)
}}
+
{{ period.placementDates.length }}
{{
counted(
tr().planning.explanation.leaveDays,
period.placementDates.length
)
}}
+
{{ period.nonWorkingDates.length }}
{{
counted(
tr().planning.explanation.freeDays,
period.nonWorkingDates.length
)
}}
=
<strong
>{{ period.duration }}
{{
counted(
tr().planning.explanation.daysOff,
period.duration
)
}}</strong
>
</p>
<p>{{ tr().bookedDays.fixed }}</p>
</section>
}
</div>
</details>
}
@if (timeOffPeriodCount(); as count) {
<details class="time-off-periods">
<summary>
<mat-icon aria-hidden="true">date_range</mat-icon>
<span
>{{ tr().planning.timeOffPeriods.title
}}<small
>{{ tr().planning.timeOffPeriods.count }} : {{ count }}</small
></span
>
<mat-icon class="disclosure-chevron" aria-hidden="true"
>expand_more</mat-icon
>
</summary>
<app-time-off-periods [plan]="plan" (dateChosen)="showDate($event)" />
</details>
}
}
</div>
<p class="calendar-help">
@@ -600,89 +746,92 @@
<ng-template #planStatisticsDialog>
<h2 mat-dialog-title id="plan-statistics-title">{{ tr().planning.statistics.title }}</h2>
<mat-dialog-content class="statistics-content">
@if (displayedPlan(); as plan) {
@if (statistics(); as stats) {
@let copy = tr().planning.statistics;
@if (planningOutcome()?.kind === 'PlanningIncomplete') {
<p class="incomplete-incumbent">{{ tr().planning.statistics.partialPlan }}</p>
<p class="incomplete-incumbent">{{ copy.partialPlan }}</p>
}
<p id="plan-statistics-help">{{ tr().planning.statistics.help }}</p>
<p id="plan-statistics-help">{{ copy.help }}</p>
<dl class="plan-summary statistics-summary">
<div>
<dt>{{ tr().planning.statistics.leaveDays }}</dt>
<dd>{{ plan.placements.length }}</dd>
<dt>{{ copy.leaveDays }}</dt>
<dd>
{{ formatStatistic(stats.placed) }}
<small>{{ outOf(stats.available) }}</small>
</dd>
</div>
<div>
<dt>
{{ tr().planning.daysGained }} ({{ tr().planning.statistics.calendarDays }})
</dt>
<dd>{{ formatStatistic(plan.metrics.nonWorkingDayGain) }}</dd>
<dt>{{ copy.unplaced }}</dt>
<dd>{{ formatStatistic(stats.unplaced) }}</dd>
@if (stats.lost) {
<dd class="note">
<span class="lost">{{ counted(copy.lostDays, stats.lost) }}</span>
{{ copy.lostHelp }}
</dd>
} @else if (stats.unplaced) {
<dd class="note">{{ copy.keptHelp }}</dd>
}
</div>
<div>
<dt>
{{ tr().planning.statistics.averageWorkSequence }} ({{
tr().planning.statistics.workingDays
}})
</dt>
<dd>{{ formatStatistic(plan.metrics.averageWorkSequence) }}</dd>
<dt>{{ copy.daysOff }}</dt>
<dd>{{ formatStatistic(stats.daysOff) }}</dd>
@if (stats.weekendAndHolidayDays) {
<dd class="note">
{{ counted(copy.weekendAndHolidayDays, stats.weekendAndHolidayDays) }}
</dd>
}
</div>
<div>
<dt>
{{ tr().planning.longestWorkSequence }} ({{
tr().planning.statistics.workingDays
}})
</dt>
<dd>{{ formatStatistic(plan.metrics.longestWorkSequence) }}</dd>
<dt>{{ copy.periods }}</dt>
<dd>{{ formatStatistic(timeOffPeriodCount()) }}</dd>
@if (stats.longestTimeOffPeriod; as longest) {
<dd class="note">{{ counted(copy.longestPeriod, longest) }}</dd>
}
</div>
<div>
<dt>
{{ tr().planning.statistics.averageTimeOffPeriod }} ({{
tr().planning.statistics.calendarDays
}})
</dt>
<dd>{{ formatStatistic(plan.metrics.averageTimeOffPeriod) }}</dd>
<dt>{{ copy.longestWorkSequence }}</dt>
<dd>
{{ formatStatistic(stats.longestWorkSequence) }}
<small>{{ counted(copy.workedDays, stats.longestWorkSequence) }}</small>
</dd>
</div>
<div>
<dt>
{{ tr().planning.statistics.longestTimeOffPeriod }} ({{
tr().planning.statistics.calendarDays
}})
</dt>
<dd>{{ formatStatistic(plan.metrics.longestTimeOffPeriod) }}</dd>
<dt>{{ copy.bridgedHolidays }}</dt>
<dd>
{{ formatStatistic(stats.bridgedHolidays) }}
<small>{{ outOf(stats.weekdayHolidays) }}</small>
</dd>
</div>
<div>
<dt>
{{ tr().planning.statistics.weekendConnectedHolidays }} ({{
tr().planning.statistics.calendarDays
}})
</dt>
<dd>{{ formatStatistic(weekendConnectedHolidays()) }}</dd>
</div>
<div>
<dt>
{{ tr().planning.statistics.earnedLeave }} ({{
tr().planning.statistics.leaveDaysUnit
}})
</dt>
<dd>{{ formatStatistic(earnedLeave().total) }}</dd>
</div>
</dl>
@if (earnedLeave().contributions.length) {
<section aria-labelledby="earned-leave-title">
<h3 id="earned-leave-title">
{{ tr().planning.statistics.earnedLeaveByRule }} ({{
tr().planning.statistics.leaveDaysUnit
}})
</h3>
<dl class="earned-leave-breakdown">
@for (
contribution of earnedLeave().contributions;
track contribution.ruleId
) {
<div>
<dt>{{ contribution.label }}</dt>
<dd>{{ formatStatistic(contribution.quantity) }}</dd>
</div>
@if (stats.earned) {
<div>
<dt>{{ copy.earnedLeave }}</dt>
<dd>{{ formatStatistic(stats.earned) }}</dd>
@for (rule of stats.earnedRules; track rule.ruleId) {
<dd class="note">
{{ rule.label }}
@if (stats.earnedRules.length > 1) {
· {{ formatStatistic(rule.quantity) }}
}
</dd>
}
</dl>
</div>
}
</dl>
@if (stats.oneWorkdayWeeks.length) {
<section class="one-workday-weeks" aria-labelledby="one-workday-weeks-title">
<h3 id="one-workday-weeks-title">
{{ counted(copy.oneWorkdayWeeks, stats.oneWorkdayWeeks.length) }}
</h3>
<p>{{ copy.oneWorkdayHelp }}</p>
<ol>
@for (week of stats.oneWorkdayWeeks; track week.start) {
<li>
{{ displayDate(week.start) }} – {{ displayDate(week.end) }}
<br />
{{ copy.onlyWorkday }} · {{ displayDate(week.workday) }}
</li>
}
</ol>
</section>
}
}
@@ -31,8 +31,14 @@ code {
padding-block: 0.25rem 0.5rem;
}
.results-heading {
display: grid;
gap: 0.75rem;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 1rem;
}
.calculation-date {
color: var(--ui-text-secondary);
font-size: 0.8125rem;
}
.planning-status {
display: flex;
@@ -59,6 +65,10 @@ code {
background: var(--ui-error-bg);
color: var(--ui-error-text);
}
&.info {
background: var(--mat-sys-primary-container);
color: var(--mat-sys-on-primary-container);
}
}
.plan-summary {
@@ -69,8 +79,8 @@ code {
div {
display: flex;
flex-direction: column;
gap: 0.375rem;
padding: 1.25rem;
gap: 0.25rem;
padding: 0.875rem 1.25rem;
border: 1px solid var(--ui-border);
border-radius: var(--ui-radius-md);
background: var(--ui-card-bg);
@@ -88,11 +98,31 @@ code {
font-variant-numeric: tabular-nums;
line-height: 1.1;
}
dd small {
font-size: 0.875rem;
font-weight: 500;
}
.note {
order: 1;
color: var(--ui-text-secondary);
font-size: 0.75rem;
font-weight: 400;
line-height: 1.4;
}
.lost {
display: inline-block;
padding: 0 0.375rem;
border-radius: var(--ui-radius-sm);
background: var(--ui-warning-bg);
color: var(--ui-warning-text);
font-weight: 600;
}
div:first-child {
background: var(--mat-sys-primary);
color: var(--mat-sys-on-primary);
border-color: transparent;
dt {
dt,
.note {
color: inherit;
}
}
@@ -100,10 +130,12 @@ code {
.plan-insights {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
// Closed disclosures share a row (three on a wide screen); an open one takes the full row.
grid-template-columns: repeat(auto-fit, minmax(min(100%, 17rem), 1fr));
align-items: start;
gap: 0.75rem;
> details {
container-type: inline-size;
min-width: 0;
border: 1px solid var(--ui-border);
border-radius: var(--ui-radius-md);
@@ -141,6 +173,20 @@ code {
font-weight: 400;
}
}
// Three disclosures share a wide row: drop the decorative icon to keep the row as low as two.
@container (max-width: 20rem) {
> summary {
gap: 0.5rem;
padding: 0.625rem 0.875rem;
min-height: 0;
> mat-icon:first-child {
display: none;
}
small {
margin-top: 0.125rem;
}
}
}
&[open] {
grid-column: 1 / -1;
> summary {
@@ -154,33 +200,25 @@ code {
}
}
.applied-rules-content {
display: grid;
gap: 0.75rem;
padding: 1rem;
}
.statistics-content {
display: grid;
gap: 1rem;
}
.statistics-summary {
grid-template-columns: minmax(0, 1fr);
}
.earned-leave-breakdown {
display: grid;
gap: 0.75rem;
margin: 0;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr));
div {
display: flex;
justify-content: space-between;
gap: 1rem;
}
dt {
min-width: 0;
overflow-wrap: anywhere;
padding: 0.875rem 1rem;
}
dd {
margin: 0;
font-weight: 600;
font-variant-numeric: tabular-nums;
font-size: 1.75rem;
}
}
.placement-explanation,
.outcome-explanation {
display: grid;
@@ -276,7 +314,8 @@ output {
background: var(--ui-panel-bg);
}
.incomplete-explanation,
.incomplete-incumbent {
.incomplete-incumbent,
.one-workday-weeks {
padding: 1rem;
border-inline-start: 4px solid var(--ui-warning-text);
background: var(--ui-warning-bg);
@@ -425,6 +464,10 @@ output {
dd {
font-size: 1.75rem;
}
dd small {
display: block;
line-height: 1.4;
}
dt {
font-size: 0.75rem;
}
@@ -27,10 +27,12 @@ import {
import { CalendarMonth, DeclarationPreview } from '../calendar-month/calendar-month';
import { DateComparison } from '../date-comparison/date-comparison';
import { PlanningCriteria } from '../planning-criteria/planning-criteria';
import { TimeOffPeriods, timeOffPeriodRows } from '../time-off-periods/time-off-periods';
import { planStatistics } from './plan-statistics';
import { addPlanningDays } from '../../services/planning-date';
import { isWorkingPlanningDate } from '../../services/declared-non-working-days';
import { CalendarService, SelectedDates } from '../../services/calendar-service';
import { TranslationService } from '../../services/translation-service';
import { PluralForms, TranslationService } from '../../services/translation-service';
import { UserInputService } from '../../services/user-input-service';
import { CalendarSettingsService } from '../../services/calendar-settings-service';
import { PlanningDurationService } from '../../services/planning-duration.service';
@@ -58,6 +60,7 @@ type PlacementExplanation = PlanExplanation['placements'][number];
CalendarMonth,
DateComparison,
PlanningCriteria,
TimeOffPeriods,
MatCardContent,
MatProgressSpinner,
MatIcon,
@@ -109,6 +112,7 @@ export class CalendarYear {
protected readonly liveMessage = signal('');
protected readonly planningHorizon = this.calculations.displayedHorizon;
protected readonly declarationEntry = this.userInput.declarationEntrySignal;
protected readonly nothingToPlan = this.userInput.nothingToPlan;
private readonly monthGrid = viewChild<ElementRef<HTMLElement>>('monthGrid');
private readonly declarationDrag = signal<{
pointerId: number;
@@ -132,11 +136,15 @@ export class CalendarYear {
}
return { dates, type: this.userInput.declaredTypeSignal() };
});
/** Without a calculation to display, the calendar shows the current inputs, as during declaration entry. */
private readonly showsInputs = computed(
() => this.declarationEntry() || !this.planningHorizon(),
);
protected readonly calendarHorizon = computed(() =>
this.declarationEntry() ? this.settings.planningHorizon() : this.planningHorizon(),
this.showsInputs() ? this.settings.planningHorizon() : this.planningHorizon(),
);
protected readonly calendarDeclaredDays = computed<Readonly<Record<string, LeaveType>>>(() => {
const days = this.declarationEntry()
const days = this.showsInputs()
? this.userInput.declaredDaysSignal()
: (this.calculations.accepted()?.declaredDays ?? []);
return Object.fromEntries(days.map(({ date, type }) => [date, type]));
@@ -154,38 +162,26 @@ export class CalendarYear {
}
protected readonly displayedPlan = this.calculations.displayedPlan;
protected readonly weekendConnectedHolidays = computed(() => {
const isWeekend = (date: string) => {
const day = new Date(`${date}T00:00:00Z`).getUTCDay();
return day === 0 || day === 6;
};
// Weekday natural non-working dates are public holidays; declarations are separate.
return new Set(
(this.displayedPlan()?.timeOffPeriods ?? []).flatMap(({ nonWorkingDates }) =>
nonWorkingDates.some(isWeekend)
? nonWorkingDates.filter((date) => !isWeekend(date))
: [],
),
).size;
protected readonly declaredPeriods = computed(() =>
(this.displayedPlan()?.timeOffPeriods ?? []).filter(
({ declaredDates }) => declaredDates?.length,
),
);
protected readonly appliedRuleCount = computed(() => {
const plan = this.displayedPlan();
return (
(plan?.timeWindowContributions?.length ?? 0) +
(plan?.ifThenContributions?.length ?? 0) +
this.declaredPeriods().length
);
});
protected readonly earnedLeave = computed(() => {
const byRule = new Map<string, { ruleId: string; label: string; quantity: number }>();
for (const contribution of this.displayedPlan()?.ifThenContributions ?? []) {
const entitlement = contribution.earnedEntitlement;
if (!entitlement?.added || entitlement.quantity <= 0) continue;
const entry = byRule.get(contribution.ruleId) ?? {
ruleId: contribution.ruleId,
label: contribution.label,
quantity: 0,
};
entry.quantity += entitlement.quantity;
byRule.set(entry.ruleId, entry);
}
const contributions = [...byRule.values()];
return {
total: contributions.reduce((total, contribution) => total + contribution.quantity, 0),
contributions,
};
protected readonly timeOffPeriodCount = computed(() => {
const plan = this.displayedPlan();
return plan ? timeOffPeriodRows(plan).length : 0;
});
protected readonly statistics = computed(() => {
const plan = this.displayedPlan();
return plan && planStatistics(plan);
});
protected readonly planExplanation = computed(() => {
@@ -210,7 +206,7 @@ export class CalendarYear {
protected readonly calendarProjection = computed(() => {
const horizon = this.calendarHorizon();
if (!horizon) return undefined;
if (this.declarationEntry())
if (this.showsInputs())
return this.calendarService.project(
{ placements: [], horizon, declaredDays: this.userInput.declaredDaysSignal() },
{ fixedMonths: true },
@@ -318,7 +314,7 @@ export class CalendarYear {
),
);
});
this.calculations.start();
if (!this.nothingToPlan()) this.calculations.start();
}
protected cancelCalculation(): void {
@@ -328,7 +324,19 @@ export class CalendarYear {
}
protected formatStatistic(value: number | null): string {
return value === null ? '—' : value.toLocaleString(this.translationService.locale());
return value === null
? '—'
: value.toLocaleString(this.translationService.locale(), { maximumFractionDigits: 1 });
}
/** A counted phrase or unit, in the form that suits its number. */
protected counted(forms: PluralForms, count: number): string {
const one = new Intl.PluralRules(this.translationService.locale()).select(count) === 'one';
return (one ? forms.one : forms.other).replace('{count}', this.formatStatistic(count));
}
protected outOf(total: number): string {
return this.tr().planning.statistics.outOf.replace('{total}', this.formatStatistic(total));
}
protected openStatistics(): void {
@@ -470,8 +478,11 @@ export class CalendarYear {
this.declarationScrollFrame = undefined;
const pointer = this.declarationPointer;
if (!pointer || !this.declarationDrag()) return;
const direction =
pointer.clientY < 48 ? -1 : pointer.clientY > window.innerHeight - 48 ? 1 : 0;
// The document's scroll padding is the part of the viewport covered by the app's bottom bar.
const bottom =
window.innerHeight -
(parseFloat(getComputedStyle(document.documentElement).scrollPaddingBottom) || 0);
const direction = pointer.clientY < 48 ? -1 : pointer.clientY > bottom - 48 ? 1 : 0;
if (!direction || pointer.clientX < 0 || pointer.clientX > window.innerWidth) return;
const before = window.scrollY;
window.scrollBy(0, direction * (lastFrame ? Math.min(now - lastFrame, 32) : 16) * 0.5);
@@ -551,6 +562,17 @@ export class CalendarYear {
}
}
/** Brings a date of the calendar into view and moves focus to its day button. */
protected showDate(date: string): void {
const day = this.monthGrid()?.nativeElement.querySelector<HTMLElement>(
`[data-date="${date}"]`,
);
if (!day) return;
const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
day.scrollIntoView({ block: 'center', behavior: reduced ? 'auto' : 'smooth' });
day.focus({ preventScroll: true });
}
protected selectCalendarDate(date: string): void {
if (this.declarationEntry()) {
const horizon = this.calendarHorizon();
@@ -0,0 +1,188 @@
import type { PlanOutcome } from '../../services/leave-planner.service';
import { planStatistics } from './plan-statistics';
const planOf = (parts: Partial<PlanOutcome>): PlanOutcome => ({
kind: 'Plan',
horizon: { start: '2024-06-03', end: '2024-06-17' },
placements: [],
timeOffPeriods: [],
preferences: [],
remainingBalances: [],
metrics: {
unplacedAtRisk: 0,
holidayWeekValue: 0,
nonWorkingDayGain: 0,
longestWorkSequence: 0,
averageWorkSequence: null,
averageTimeOffPeriod: null,
longestTimeOffPeriod: null,
shortSequenceDeficit: 0,
supportingPlacements: 0,
preferenceSatisfaction: [],
},
completedStages: [],
lastCompletedStage: '',
...parts,
});
const placed = (...dates: string[]): PlanOutcome['placements'] =>
dates.map((date) => ({ date, balanceId: 'cp', type: 'cp', ruleIds: [], supporting: false }));
const remaining = (
quantity: number,
classification: 'at-risk' | 'deferred' | 'unavoidable-expiry',
) =>
({
id: classification,
type: 'cp',
quantity,
availableFrom: '2024-01-01',
expiryDate: '2024-12-31',
classification,
reason: { code: 'all-dates-occupied', message: '' },
earned: false,
}) as PlanOutcome['remainingBalances'][number];
const period = (
duration: number,
nonWorkingDates: string[],
): PlanOutcome['timeOffPeriods'][number] => ({
start: '',
end: '',
duration,
placementDates: [],
nonWorkingDates,
nonWorkingDayGain: nonWorkingDates.length,
});
describe('planStatistics', () => {
it('counts a balance kept for later as unplaced but not lost', () => {
const statistics = planStatistics(
planOf({
placements: placed('2024-06-03', '2024-06-04'),
remainingBalances: [
remaining(3, 'at-risk'),
remaining(2, 'deferred'),
remaining(1, 'unavoidable-expiry'),
],
}),
);
expect(statistics).toMatchObject({ placed: 2, unplaced: 6, lost: 4, available: 8 });
});
it('loses nothing when every leave day is placed', () => {
expect(planStatistics(planOf({ placements: placed('2024-06-03') }))).toMatchObject({
placed: 1,
unplaced: 0,
lost: 0,
available: 1,
});
});
it('totals the days of the time-off periods', () => {
const plan = planOf({ timeOffPeriods: [period(5, []), period(4, [])] });
plan.metrics.nonWorkingDayGain = 6;
expect(planStatistics(plan)).toMatchObject({ daysOff: 9, weekendAndHolidayDays: 6 });
});
it.each([
{
label: 'two weekday holidays joined to a weekend, out of the two of the horizon',
horizon: { start: '2024-05-06', end: '2024-05-13' },
nonWorkingDates: ['2024-05-08', '2024-05-09', '2024-05-11', '2024-05-12'],
expected: { bridgedHolidays: 2, weekdayHolidays: 2 },
},
{
label: 'a break that reaches no weekend',
horizon: { start: '2024-05-06', end: '2024-05-11' },
nonWorkingDates: ['2024-05-08', '2024-05-09'],
expected: { bridgedHolidays: 0, weekdayHolidays: 2 },
},
{
label: 'a bridged holiday just after the horizon, which still counts as possible',
horizon: { start: '2024-05-17', end: '2024-05-18' },
nonWorkingDates: ['2024-05-18', '2024-05-19', '2024-05-20'],
expected: { bridgedHolidays: 1, weekdayHolidays: 1 },
},
])('counts bridged public holidays: $label', ({ horizon, nonWorkingDates, expected }) => {
const plan = planOf({ horizon, timeOffPeriods: [period(0, [...nonWorkingDates])] });
expect(planStatistics(plan)).toMatchObject(expected);
});
it('adds up earned leave by rule and ignores entitlements that add nothing', () => {
const earned = (ruleId: string, quantity: number, added = true) => ({
ruleId,
label: `Rule ${ruleId}`,
occurrence: '2024-06-08',
requested: 1,
declaredDays: [],
placementDates: [],
earnedEntitlement: {
id: ruleId,
type: 'other' as const,
quantity,
availableFrom: '2024-06-10',
expiryDate: '2025-06-10',
added,
},
});
const statistics = planStatistics(
planOf({
ifThenContributions: [
earned('a', 1),
earned('a', 2),
earned('b', 4),
earned('c', 5, false),
],
}),
);
expect(statistics.earned).toBe(7);
expect(statistics.earnedRules).toEqual([
{ ruleId: 'a', label: 'Rule a', quantity: 3 },
{ ruleId: 'b', label: 'Rule b', quantity: 4 },
]);
});
it.each([
{
label: 'four leave days leave one workday; three declared days leave two',
plan: planOf({
placements: placed('2024-06-03', '2024-06-04', '2024-06-05', '2024-06-06'),
declaredDays: ['2024-06-10', '2024-06-11', '2024-06-12'].map((date) => ({
date,
type: 'other' as const,
})),
}),
weeks: [{ start: '2024-06-03', end: '2024-06-09', workday: '2024-06-07' }],
},
{
label: 'public holidays count as days off',
plan: planOf({
horizon: { start: '2024-05-06', end: '2024-05-11' },
placements: placed('2024-05-06', '2024-05-07'),
}),
weeks: [{ start: '2024-05-06', end: '2024-05-12', workday: '2024-05-10' }],
},
{
label: 'a week clipped by the horizon never qualifies',
plan: planOf({
horizon: { start: '2024-06-04', end: '2024-06-08' },
placements: placed('2024-06-04', '2024-06-05', '2024-06-06'),
}),
weeks: [],
},
{
label: 'a week with every workday off has no lone workday',
plan: planOf({
horizon: { start: '2024-06-03', end: '2024-06-08' },
placements: placed(
'2024-06-03',
'2024-06-04',
'2024-06-05',
'2024-06-06',
'2024-06-07',
),
}),
weeks: [],
},
])('finds weeks with one workday: $label', ({ plan, weeks }) => {
expect(planStatistics(plan).oneWorkdayWeeks).toEqual(weeks);
});
});
@@ -0,0 +1,81 @@
import type { PlanOutcome } from '../../services/leave-planner.service';
import { isWorkingPlanningDate } from '../../services/declared-non-working-days';
import { addPlanningDays } from '../../services/planning-date';
const weekday = (date: string) => new Date(`${date}T00:00:00Z`).getUTCDay();
const isWeekend = (date: string) => weekday(date) % 6 === 0;
const isWeekdayHoliday = (date: string) => !isWeekend(date) && !isWorkingPlanningDate(date);
const sum = (values: readonly number[]) => values.reduce((total, value) => total + value, 0);
/** The figures of the summary tiles and the statistics dialog, as defined in docs/statistics.md. */
export function planStatistics(plan: PlanOutcome) {
const placed = plan.placements.length;
const unplaced = sum(plan.remainingBalances.map(({ quantity }) => quantity));
// A deferred balance expires after the planning horizon: it is kept for later, not lost.
const lost = sum(
plan.remainingBalances
.filter(({ classification }) => classification !== 'deferred')
.map(({ quantity }) => quantity),
);
// Weekday natural non-working dates are public holidays; declarations are separate.
const bridged = new Set(
plan.timeOffPeriods.flatMap(({ nonWorkingDates }) =>
nonWorkingDates.some(isWeekend)
? nonWorkingDates.filter((date) => !isWeekend(date))
: [],
),
);
// A bridged holiday next to the horizon counts too, so that the part never exceeds the whole.
const weekdayHolidays = new Set(bridged);
for (let date = plan.horizon.start; date < plan.horizon.end; date = addPlanningDays(date, 1))
if (isWeekdayHoliday(date)) weekdayHolidays.add(date);
const earnedByRule = new Map<string, { ruleId: string; label: string; quantity: number }>();
for (const { ruleId, label, earnedEntitlement } of plan.ifThenContributions ?? []) {
if (!earnedEntitlement?.added || earnedEntitlement.quantity <= 0) continue;
const entry = earnedByRule.get(ruleId) ?? { ruleId, label, quantity: 0 };
entry.quantity += earnedEntitlement.quantity;
earnedByRule.set(ruleId, entry);
}
const earnedRules = [...earnedByRule.values()];
const timeOff = new Set([
...plan.placements.map(({ date }) => date),
...(plan.declaredDays ?? []).map(({ date }) => date),
]);
const oneWorkdayWeeks: { start: string; end: string; workday: string }[] = [];
// Only weeks whose five weekdays lie inside the half-open horizon can qualify.
for (
let monday = addPlanningDays(plan.horizon.start, (8 - weekday(plan.horizon.start)) % 7);
addPlanningDays(monday, 4) < plan.horizon.end;
monday = addPlanningDays(monday, 7)
) {
const workdays = Array.from({ length: 5 }, (_, day) => addPlanningDays(monday, day)).filter(
(date) => isWorkingPlanningDate(date) && !timeOff.has(date),
);
if (workdays.length === 1)
oneWorkdayWeeks.push({
start: monday,
end: addPlanningDays(monday, 6),
workday: workdays[0],
});
}
return {
placed,
unplaced,
lost,
/** The leave days the plan could use: those it placed and those it left. */
available: placed + unplaced,
daysOff: sum(plan.timeOffPeriods.map(({ duration }) => duration)),
weekendAndHolidayDays: plan.metrics.nonWorkingDayGain,
longestTimeOffPeriod: plan.metrics.longestTimeOffPeriod,
longestWorkSequence: plan.metrics.longestWorkSequence,
bridgedHolidays: bridged.size,
weekdayHolidays: weekdayHolidays.size,
earned: sum(earnedRules.map(({ quantity }) => quantity)),
earnedRules,
oneWorkdayWeeks,
};
}
@@ -107,7 +107,7 @@ async function flushMicrotasks() {
for (let tick = 0; tick < 20; tick++) await Promise.resolve();
}
const loading = 'Analyzing every date in the horizon… 3 May 2024';
const loading = 'Checking the other possible dates… 3 May 2024';
describe('DateComparison', () => {
beforeEach(() => localStorage.clear());
@@ -124,13 +124,13 @@ describe('DateComparison', () => {
'Compare dates',
);
expect(document.getElementById('comparison-intro')?.textContent?.trim()).toBe(
'Try moving this one day. All other leave dates stay the same.',
'Try another date for this day. Other leave days do not move.',
);
await vi.waitFor(() =>
expect(document.activeElement).toBe(document.getElementById('counterfactual-title')),
);
expect(document.querySelector('.comparison-loading[role="status"]')?.textContent).toContain(
'Analyzing every date in the horizon…',
'Checking the other possible dates…',
);
expect(announcements).toEqual([loading]);
@@ -154,8 +154,8 @@ describe('DateComparison', () => {
expect(document.querySelector('.comparison-loading')).toBeNull();
expect(announcements).toEqual([
loading,
'2024-05-02. Date alternatives. Eligible',
'Date alternatives are ready.',
'2024-05-02. Compared date. Available',
'You can now compare other dates.',
]);
expect(
Array.from(
@@ -320,7 +320,7 @@ describe('DateComparison', () => {
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(element.querySelector('.counterfactual-result')?.textContent).toContain(
'These totals are unchanged.',
'No total changes.',
);
expect(element.querySelector('.counterfactual-result > .impact-table')).toBeNull();
input.value = '04/05/2024';
@@ -377,7 +377,7 @@ describe('DateComparison', () => {
expect(comparison.selectDate('2024-05-04')).toBe(true);
fixture.detectChanges();
expect(announcements.at(-1)).toBe(
'2024-05-04. Date alternatives. Ineligible. This is already a day off (weekend or public holiday). No leave is needed.',
'2024-05-04. Compared date. Unavailable. This is already a day off (weekend or public holiday). No leave is needed.',
);
expect(document.querySelector('.unavailable-date')?.textContent).toContain(
'No leave is needed.',
@@ -412,7 +412,7 @@ describe('DateComparison', () => {
expect(
document.querySelector('.counterfactual-panel .counterfactual-inline-error')
?.textContent,
).toContain('Date alternatives could not be calculated.');
).toContain('The other dates could not be checked.');
expect(document.querySelector('.comparison-done')).not.toBeNull();
document.querySelector<HTMLButtonElement>('.comparison-close')!.click();
await fixture.whenStable();
@@ -424,9 +424,9 @@ describe('DateComparison', () => {
comparison.compareDates();
fixture.detectChanges();
expect(document.querySelector('.comparison-loading')?.textContent).toContain(
'Analyzing every date',
'Checking the other possible dates',
);
expect(announcements.at(-1)).toContain('Analyzing every date');
expect(announcements.at(-1)).toContain('Checking the other possible dates');
(await job(1)).emit({ type: 'error', message: 'worker unavailable' });
await flushMicrotasks();
fixture.detectChanges();
@@ -434,12 +434,12 @@ describe('DateComparison', () => {
document.querySelector(
'.counterfactual-panel .counterfactual-inline-error[role="alert"]',
)?.textContent,
).toContain('Date alternatives could not be calculated.');
).toContain('The other dates could not be checked.');
expect(
document.querySelector('.counterfactual-panel .counterfactual-inline-error')
?.textContent,
).not.toContain('worker unavailable');
expect(announcements.at(-1)).toBe('Date alternatives could not be calculated.');
expect(announcements.at(-1)).toBe('The other dates could not be checked.');
expect(fixture.nativeElement.querySelector('.counterfactual-inline-error')).toBeNull();
expect(comparison.failed()).toBe(true);
@@ -447,6 +447,10 @@ describe('DateComparison', () => {
fixture.detectChanges();
expect(document.querySelector('.comparison-loading')).not.toBeNull();
expect(comparison.failed()).toBe(false);
// The dialog focuses its title only after its opening animation; let that settle first.
await vi.waitFor(() =>
expect(document.activeElement).toBe(document.getElementById('counterfactual-title')),
);
const focusedBeforeResult = document.activeElement;
(await job(2)).emit({
type: 'counterfactual-result',
@@ -458,7 +462,7 @@ describe('DateComparison', () => {
await flushMicrotasks();
fixture.detectChanges();
expect(document.querySelector('.counterfactual-result')).not.toBeNull();
expect(announcements.at(-1)).toContain('Date alternatives are ready.');
expect(announcements.at(-1)).toContain('You can now compare other dates.');
expect(document.activeElement).toBe(focusedBeforeResult);
});
@@ -516,9 +520,9 @@ describe('DateComparison', () => {
expect(document.querySelector('.original-date strong')?.textContent).toBe('6 May 2024');
expect(announcements).toEqual([
loading,
'Analyzing every date in the horizon… 6 May 2024',
'2024-05-06. Date alternatives. Eligible',
'Date alternatives are ready.',
'Checking the other possible dates… 6 May 2024',
'2024-05-06. Compared date. Available',
'You can now compare other dates.',
]);
});
@@ -563,7 +567,7 @@ describe('DateComparison', () => {
// Before change detection the result is stored and announced, but not yet rendered.
expect(comparison['counterfactual']()).not.toBeNull();
expect(document.querySelector('.comparison-date-pair')).toBeNull();
expect(announcements.at(-1)).toBe('Date alternatives are ready.');
expect(announcements.at(-1)).toBe('You can now compare other dates.');
fixture.detectChanges();
expect(comparison['counterfactual']()).toBeNull();
await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')).toBeNull());
@@ -0,0 +1,40 @@
<button
mat-button
type="button"
class="declaration-entry-toggle"
[attr.aria-pressed]="declarationEntry()"
(click)="declarationEntry.set(!declarationEntry())"
>
<mat-icon aria-hidden="true">{{
declarationEntry() ? 'check_circle' : 'edit_calendar'
}}</mat-icon>
{{ tr().bookedDays.enter }}
</button>
@if (declarationEntry()) {
<div class="declaration-types" role="group" [attr.aria-label]="tr().userInput.type">
@for (type of declaredTypes; track type) {
<button
mat-stroked-button
type="button"
[attr.data-declared-type]="type"
[attr.aria-pressed]="declaredType() === type"
(click)="declaredType.set(type)"
>
<mat-icon class="declaration-type-check" aria-hidden="true">check</mat-icon>
{{ type === 'cp' ? 'CP' : translationService.getDayTypeLabel(type) }}
</button>
}
<button
mat-stroked-button
type="button"
data-declaration-erase
[attr.aria-pressed]="declaredType() === null"
(click)="declaredType.set(null)"
>
<mat-icon aria-hidden="true">{{
declaredType() === null ? 'check' : 'backspace'
}}</mat-icon>
{{ tr().bookedDays.erase }}
</button>
</div>
}
@@ -0,0 +1,80 @@
:host {
display: grid;
container: declaration-controls / inline-size;
grid-column: 1 / -1;
border: 1px solid var(--ui-border);
border-radius: var(--ui-radius-sm);
background: var(--ui-panel-bg);
&.is-active {
border-color: var(--mat-sys-primary);
}
}
.declaration-entry-toggle {
justify-content: flex-start;
width: 100%;
height: auto;
min-height: 3.25rem;
padding: 0.75rem 1rem;
border-radius: calc(var(--ui-radius-sm) - 1px);
text-align: start;
line-height: 1.5;
transition:
background-color 150ms ease-out,
color 150ms ease-out;
&[aria-pressed='true'] {
background: var(--mat-sys-primary-container);
color: var(--mat-sys-on-primary-container);
}
}
.declaration-types {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 0.5rem;
padding: 0.75rem;
button {
min-height: 2.75rem;
height: auto;
padding: 0.5rem;
border-radius: calc(var(--ui-radius-sm) - 1px);
background-color: var(--ui-card-bg);
color: var(--number-color);
line-height: 1.5;
&[data-declared-type='cp'] {
background-color: var(--cp-bg);
}
&[data-declared-type='rtt'] {
background-color: var(--rtt-bg);
}
&[data-declared-type='other'] {
background-color: var(--other-bg);
}
&[aria-pressed='true'] {
border-color: currentColor;
box-shadow: inset 0 0 0 1px currentColor;
}
&[data-declared-type][aria-pressed='true'] {
background-image: var(--declared-day-pattern);
}
&[aria-pressed='false'] .declaration-type-check {
visibility: hidden;
}
}
}
@container declaration-controls (min-width: 18rem) {
.declaration-types {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@container declaration-controls (min-width: 34rem) {
.declaration-types {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
}
@@ -0,0 +1,24 @@
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { MatButton } from '@angular/material/button';
import { MatIcon } from '@angular/material/icon';
import type { LeaveType } from '../../services/leave-planner.service';
import { TranslationService } from '../../services/translation-service';
import { UserInputService } from '../../services/user-input-service';
/** Starts and ends declared non-working day entry, and chooses the type a calendar tap applies. */
@Component({
selector: 'app-declaration-controls',
imports: [MatButton, MatIcon],
templateUrl: './declaration-controls.html',
styleUrl: './declaration-controls.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
host: { '[class.is-active]': 'declarationEntry()' },
})
export class DeclarationControls {
private readonly userInput = inject(UserInputService);
protected readonly declarationEntry = this.userInput.declarationEntrySignal;
protected readonly declaredType = this.userInput.declaredTypeSignal;
protected readonly declaredTypes: readonly LeaveType[] = ['cp', 'rtt', 'other'];
protected readonly translationService = inject(TranslationService);
protected readonly tr = this.translationService.tr;
}
@@ -30,13 +30,17 @@ export class PlanningCriteria {
}
protected objectiveRows(before: PlanningObjectiveVector, after: PlanningObjectiveVector) {
return after.objectives.map((objective) => ({
...objective,
label: labels.objectiveLabel(this.tr(), this.snapshot(), objective),
help: labels.objectiveCopy(this.tr(), this.snapshot(), objective.id)?.help,
before: before.objectives.find((item) => item.id === objective.id)?.value,
numeric: typeof objective.value === 'number',
}));
return after.objectives.map((objective) => {
const copy = labels.objectiveCopy(this.tr(), this.snapshot(), objective.id);
return {
...objective,
label: labels.objectiveLabel(this.tr(), this.snapshot(), objective),
// The calculation details keep an optimization rule's technical composition.
help: copy?.technical ?? copy?.help,
before: before.objectives.find((item) => item.id === objective.id)?.value,
numeric: typeof objective.value === 'number',
};
});
}
protected hasTieBreaks(vector: PlanningObjectiveVector): boolean {
@@ -0,0 +1,32 @@
<ng-template #importDialog>
<h2 mat-dialog-title>{{ tr().rules.import.title }}</h2>
@if (incoming(); as rules) {
<mat-dialog-content>
<ol class="incoming-rules">
@for (rule of rules; track rule.id) {
<li>
<span class="incoming-rule-name">{{ rule.name }}</span>
<span class="incoming-rule-marks"
>{{ tr().rules[rule.force ?? 'preference']
}}{{ rule.enabled ? '' : ' · ' + tr().rules.import.disabled }}</span
>
</li>
}
</ol>
<p>{{ replaceStatement() }}</p>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button type="button" mat-dialog-close>{{ tr().rules.cancel }}</button>
<button mat-flat-button type="button" [mat-dialog-close]="true">
{{ tr().rules.import.accept }}
</button>
</mat-dialog-actions>
} @else {
<mat-dialog-content>
<p>{{ tr().rules.import.invalidLink }}</p>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button type="button" mat-dialog-close>{{ tr().settings.close }}</button>
</mat-dialog-actions>
}
</ng-template>
+29
View File
@@ -0,0 +1,29 @@
// Only the dialog is displayed, in an overlay.
:host {
display: none;
}
.incoming-rules {
margin: 0 0 1rem;
padding-inline-start: 1.5rem;
li + li {
margin-top: 0.5rem;
}
}
.incoming-rule-name {
display: block;
font-weight: 600;
// A long unbroken name wraps instead of widening the dialog.
overflow-wrap: anywhere;
}
.incoming-rule-marks {
color: var(--ui-text-secondary);
font-size: 0.875rem;
}
p {
margin: 0;
}
@@ -0,0 +1,273 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { vi } from '../../../testing/vitest-compat';
import de from '../../../i18n/de.json';
import en from '../../../i18n/en.json';
import es from '../../../i18n/es.json';
import fr from '../../../i18n/fr.json';
import { SelectableDayType } from '../../services/calendar-service';
import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives';
import { RuleService, RuleType, type VacationRule } from '../../services/rule-service';
import { encodeRuleSetLink } from '../../services/rule-set-link';
import { TranslationService } from '../../services/translation-service';
import { RuleSetImport } from './rule-set-import';
const shared = (): VacationRule[] => [
{
id: 'bridge',
name: 'Samedi Malin',
type: RuleType.IF_THEN,
enabled: true,
force: 'obligation',
dayOfWeek: 6,
placeDays: 2,
placeType: SelectableDayType.CP,
placement: 'auto',
rewardDays: 1,
rewardType: SelectableDayType.OTHER,
},
{
id: 'christmas',
name: '<b>Noël</b> <img src="x" onerror="alert(1)">',
type: RuleType.TIME_WINDOW,
enabled: false,
force: 'preference',
startDate: new Date(2026, 11, 20),
endDate: new Date(2027, 0, 3),
placeDays: 5,
placeType: SelectableDayType.ANY,
},
{
id: 'deficit',
name: 'Déficit des reprises',
type: RuleType.OPTIMIZATION,
enabled: true,
force: 'preference',
configuration: structuredClone(OPTIMIZATION_PRESETS.shortSequenceDeficit),
},
];
/** The fragment of the share link of these rules. */
async function fragmentOf(rules: VacationRule[]): Promise<string> {
const result = await encodeRuleSetLink(rules);
if (!('link' in result)) throw new Error('The rule set was refused.');
return new URL(result.link).hash;
}
const dialogs = () => Array.from(document.querySelectorAll<HTMLElement>('mat-dialog-container'));
const address = () => location.pathname + location.search + location.hash;
const savedRules = () => localStorage.getItem('vacationRules');
function button(text: string): HTMLButtonElement {
const found = Array.from(dialogs().at(-1)!.querySelectorAll('button')).find(
(candidate) => candidate.textContent?.trim() === text,
);
if (!found) throw new Error(`Missing dialog button: ${text}`);
return found;
}
describe('RuleSetImport', () => {
let fixture: ComponentFixture<RuleSetImport>;
let rules: RuleService;
/** Opens the planner page at this address, with the default rule set saved. */
async function start(url: string) {
history.replaceState({ navigationId: 1 }, '', url);
await TestBed.configureTestingModule({
imports: [RuleSetImport],
providers: [provideZonelessChangeDetection()],
}).compileComponents();
TestBed.inject(TranslationService).setLanguage('en');
rules = TestBed.inject(RuleService);
fixture = TestBed.createComponent(RuleSetImport);
fixture.detectChanges();
await fixture.whenStable();
}
async function opened(): Promise<HTMLElement> {
await expect.poll(() => dialogs().length).toBe(1);
await fixture.whenStable();
return dialogs()[0];
}
const closed = () => expect.poll(() => dialogs().length).toBe(0);
beforeEach(() => localStorage.clear());
afterEach(() => {
history.replaceState(null, '', '/');
localStorage.clear();
});
it('previews the rules of a link opened with the app, in order, and states how many rules they replace', async () => {
await start(`/${await fragmentOf(shared())}`);
const dialog = await opened();
expect(dialog.querySelector('h2')?.textContent?.trim()).toBe('Shared rules');
expect(
Array.from(dialog.querySelectorAll('ol > li'), (rule) =>
Array.from(rule.children, (part) => part.textContent?.trim()),
),
).toEqual([
['Samedi Malin', 'Obligation'],
['<b>Noël</b> <img src="x" onerror="alert(1)">', 'Preference · Disabled'],
['Déficit des reprises', 'Preference'],
]);
// A rule name is text, never markup.
expect(dialog.querySelector('b, img')).toBeNull();
expect(dialog.querySelector('p')?.textContent?.trim()).toBe(
'These rules will replace all your current rules (8). Your leave balances, already booked days and planning period stay as they are.',
);
expect(
Array.from(dialog.querySelectorAll('button'), (action) => action.textContent?.trim()),
).toEqual(['Cancel', 'Replace my rules']);
await vi.waitFor(() => expect(document.activeElement).toBe(button('Cancel')));
});
it('shows the same dialog for a link pasted while the app is open', async () => {
await start('/');
expect(dialogs()).toEqual([]);
location.hash = await fragmentOf(shared());
const dialog = await opened();
expect(dialog.querySelectorAll('ol > li')).toHaveLength(3);
expect(button('Replace my rules')).toBeTruthy();
});
it('replaces the whole rule set on Replace my rules, keeps it after a reload and removes the link from the address', async () => {
await start(`/?from=mail${await fragmentOf(shared())}`);
await opened();
button('Replace my rules').click();
await closed();
expect(rules.rules).toEqual(shared());
expect(address()).toBe('/?from=mail');
expect(history.state).toEqual({ navigationId: 1 });
// A reload: the saved rule set is the shared one, and nothing asks again.
TestBed.resetTestingModule();
await start(address());
expect(rules.rules).toEqual(shared());
expect(dialogs()).toEqual([]);
});
it('saves the accepted rule set and a later edit when the saved rules were unreadable at startup', async () => {
localStorage.setItem('vacationRules', 'not a rule list');
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
await start(`/${await fragmentOf(shared())}`);
await opened();
button('Replace my rules').click();
await closed();
rules.toggleRule('deficit');
const edited = shared();
edited[2].enabled = false;
TestBed.resetTestingModule();
await start('/');
expect(rules.rules).toEqual(edited);
} finally {
warn.mockRestore();
}
});
it.each(['Cancel', 'Escape', 'a backdrop click'])(
'leaves the rule set and its saved copy unchanged on %s, and removes the link from the address',
async (way) => {
await start(`/${await fragmentOf(shared())}`);
const before = rules.rules;
const saved = savedRules();
const dialog = await opened();
if (way === 'Cancel') button('Cancel').click();
else if (way === 'Escape')
dialog.dispatchEvent(
new KeyboardEvent('keydown', {
key: 'Escape',
code: 'Escape',
keyCode: 27,
bubbles: true,
}),
);
else document.querySelector<HTMLElement>('.cdk-overlay-backdrop')!.click();
await closed();
expect(rules.rules).toEqual(before);
expect(savedRules()).toBe(saved);
expect(address()).toBe('/');
},
);
it('reports an invalid link with Close and changes nothing', async () => {
const fragment = await fragmentOf(shared());
await start(`/${fragment.slice(0, -8)}`);
const before = rules.rules;
const saved = savedRules();
const dialog = await opened();
expect(dialog.querySelector('h2')?.textContent?.trim()).toBe('Shared rules');
expect(dialog.querySelector('p')?.textContent?.trim()).toBe(
'This share link is invalid or incomplete. Your rules have not changed.',
);
expect(dialog.querySelector('ol')).toBeNull();
expect(
Array.from(dialog.querySelectorAll('button'), (action) => action.textContent?.trim()),
).toEqual(['Close']);
button('Close').click();
await closed();
expect(rules.rules).toEqual(before);
expect(savedRules()).toBe(saved);
expect(address()).toBe('/');
});
it('replaces the open dialog when a second link arrives, as a cancel of the first', async () => {
const second = shared().slice(2);
await start(`/${await fragmentOf(shared())}`);
const before = rules.rules;
const first = await opened();
location.hash = await fragmentOf(second);
await expect.poll(() => dialogs().length === 1 && dialogs()[0] !== first).toBe(true);
await fixture.whenStable();
expect(rules.rules).toEqual(before);
expect(
Array.from(dialogs()[0].querySelectorAll('.incoming-rule-name'), (name) =>
name.textContent?.trim(),
),
).toEqual(['Déficit des reprises']);
button('Replace my rules').click();
await closed();
expect(rules.rules).toEqual(second);
expect(address()).toBe('/');
});
it('uses the wording of the ticket in every language', () => {
expect(fr.rules.import).toEqual({
title: 'Règles partagées',
replaceStatement:
'Ces règles remplaceront toutes vos règles actuelles ({count}). Vos soldes, vos jours déjà posés et votre période à planifier ne changent pas.',
accept: 'Remplacer mes règles',
disabled: 'Désactivée',
invalidLink:
'Ce lien de partage est invalide ou incomplet. Vos règles n’ont pas changé.',
});
expect(en.rules.import).toEqual({
title: 'Shared rules',
replaceStatement:
'These rules will replace all your current rules ({count}). Your leave balances, already booked days and planning period stay as they are.',
accept: 'Replace my rules',
disabled: 'Disabled',
invalidLink: 'This share link is invalid or incomplete. Your rules have not changed.',
});
expect(de.rules.import).toEqual({
title: 'Geteilte Regeln',
replaceStatement:
'Diese Regeln ersetzen alle Ihre aktuellen Regeln ({count}). Ihre Urlaubskonten, Ihre bereits gebuchten Tage und Ihr Planungszeitraum bleiben unverändert.',
accept: 'Meine Regeln ersetzen',
disabled: 'Deaktiviert',
invalidLink:
'Dieser Freigabelink ist ungültig oder unvollständig. Ihre Regeln wurden nicht geändert.',
});
expect(es.rules.import).toEqual({
title: 'Reglas compartidas',
replaceStatement:
'Estas reglas reemplazarán todas tus reglas actuales ({count}). Tus saldos, tus días ya reservados y tu período de planificación no cambian.',
accept: 'Reemplazar mis reglas',
disabled: 'Desactivada',
invalidLink:
'Este enlace compartido no es válido o está incompleto. Tus reglas no han cambiado.',
});
});
});
@@ -0,0 +1,88 @@
import {
afterNextRender,
ChangeDetectionStrategy,
Component,
computed,
DestroyRef,
inject,
signal,
TemplateRef,
viewChild,
} from '@angular/core';
import { MatButton } from '@angular/material/button';
import {
MatDialog,
MatDialogActions,
MatDialogClose,
MatDialogContent,
MatDialogTitle,
} from '@angular/material/dialog';
import { RuleService, type VacationRule } from '../../services/rule-service';
import { decodeRuleSetLink } from '../../services/rule-set-link';
import { TranslationService } from '../../services/translation-service';
/** The `rules` fragment parameter of the address: the rule set a share link carries. */
const rulesFragment = (): string | null => new URLSearchParams(location.hash.slice(1)).get('rules');
/**
* Offers to replace the person's rule set with the one a share link carries (ADR 0014), when the
* planner page starts with such a link or receives one later.
*/
@Component({
selector: 'app-rule-set-import',
imports: [MatButton, MatDialogActions, MatDialogClose, MatDialogContent, MatDialogTitle],
templateUrl: './rule-set-import.html',
styleUrl: './rule-set-import.scss',
host: { '(window:hashchange)': 'offerSharedRuleSet()' },
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RuleSetImport {
private readonly dialog = inject(MatDialog);
private readonly ruleService = inject(RuleService);
private readonly template = viewChild.required<TemplateRef<unknown>>('importDialog');
/** Counts the addresses offered, so that only the latest one opens a dialog. */
private offers = 0;
protected readonly tr = inject(TranslationService).tr;
/** The rule set on offer, or null when its link is invalid. */
protected readonly incoming = signal<VacationRule[] | null>(null);
protected readonly replaceStatement = computed(() =>
this.tr().rules.import.replaceStatement.replace(
'{count}',
String(this.ruleService.rules.length),
),
);
constructor() {
afterNextRender(() => void this.offerSharedRuleSet());
inject(DestroyRef).onDestroy(() => this.offers++);
}
protected async offerSharedRuleSet(): Promise<void> {
// Any change of the address, even one without a link, cancels the link being decoded.
const offer = ++this.offers;
const value = rulesFragment();
if (value === null) return;
const rules = await decodeRuleSetLink(value);
// A newer address, or leaving the planner page, cancels this one.
if (offer !== this.offers) return;
this.incoming.set(rules);
// Material has already closed, as a cancel, the dialog that was open when the address changed.
this.dialog
.open<unknown, unknown, boolean>(this.template(), {
width: '32rem',
maxWidth: 'calc(100vw - 2rem)',
maxHeight: 'calc(100dvh - 2rem)',
// Cancel, or Close for an invalid link.
autoFocus: 'mat-dialog-actions button',
})
.afterClosed()
.subscribe((accepted) => {
if (accepted && rules) this.ruleService.replaceRuleSet(rules);
// The link leaves the address without a Router navigation, so that a reload does not
// ask again. A newer link stays: the dialog that offers it removes it.
if (rulesFragment() === value)
history.replaceState(history.state, '', location.pathname + location.search);
});
}
}
@@ -10,6 +10,13 @@ import {
type OptimizationConfiguration,
} from '../../services/planning-objectives';
import { calculatePlanningInternal } from '../../services/leave-planner.core';
import {
chooseInDialog,
clickDialogButton,
dialogField,
ruleDialog,
typeInDialog,
} from '../../../testing/rule-dialog';
describe('calendar rule editing and persistence', () => {
let fixture: ComponentFixture<RulesPanel>;
@@ -40,28 +47,15 @@ describe('calendar rule editing and persistence', () => {
});
afterEach(() => localStorage.clear());
const closed = () => expect.poll(() => ruleDialog()).toBeNull();
async function select(label: string, value: string) {
const fields: HTMLElement[] = Array.from(
fixture.nativeElement.querySelectorAll('mat-form-field'),
);
const field = fields.find(
(candidate) => candidate.querySelector('mat-label')?.textContent?.trim() === label,
);
const control = field?.querySelector<HTMLElement>('mat-select');
if (!control) throw new Error(`Missing labelled control: ${label}`);
const control = dialogField(label).querySelector<HTMLElement>('mat-select')!;
const labels = (control.getAttribute('aria-labelledby') ?? '')
.split(/\s+/)
.map((id) => document.getElementById(id)?.textContent?.trim());
expect(labels).toContain(label);
control.click();
await fixture.whenStable();
const option = Array.from(document.querySelectorAll<HTMLElement>('mat-option')).find(
(candidate) => candidate.textContent?.trim() === value,
);
if (!option) throw new Error(`Missing translated option: ${value}`);
option.click();
document.querySelector<HTMLElement>('.cdk-overlay-backdrop')?.click();
await fixture.whenStable();
await chooseInDialog(fixture, label, value);
fixture.detectChanges();
}
@@ -72,10 +66,7 @@ describe('calendar rule editing and persistence', () => {
);
buttons.find((button) => button.textContent?.includes(tr.optimization.newRule))!.click();
await fixture.whenStable();
const nameInput: HTMLInputElement =
fixture.nativeElement.querySelector('.rule-editor input');
nameInput.value = name;
nameInput.dispatchEvent(new Event('input', { bubbles: true }));
await typeInDialog(fixture, tr.ruleName, name);
await select(
tr.optimization.elementsLabel,
tr.optimization.elements[configuration.elements],
@@ -90,11 +81,8 @@ describe('calendar rule editing and persistence', () => {
tr.optimization.directionLabel,
tr.optimization.directions[configuration.direction],
);
const actions: HTMLButtonElement[] = Array.from(
fixture.nativeElement.querySelectorAll('.editor-actions button'),
);
actions.find((button) => button.textContent?.trim() === tr.add)!.click();
await fixture.whenStable();
await clickDialogButton(fixture, tr.add);
await closed();
fixture.detectChanges();
}
@@ -154,8 +142,8 @@ describe('calendar rule editing and persistence', () => {
translations.tr().rules.optimization.aggregationLabel,
translations.tr().rules.optimization.aggregations.count,
);
fixture.componentInstance.saveEdit();
await fixture.whenStable();
await clickDialogButton(fixture, translations.tr().rules.save);
await closed();
await expect
.poll(
() =>
@@ -201,11 +189,9 @@ describe('calendar rule editing and persistence', () => {
fixture.componentInstance.startEdit(service.rules[0], new Event('click'));
await fixture.whenStable();
const input: HTMLInputElement = fixture.nativeElement.querySelector('.rule-editor input');
input.value = 'Mes jours conservés';
input.dispatchEvent(new Event('input', { bubbles: true }));
fixture.componentInstance.saveEdit();
await fixture.whenStable();
await typeInDialog(fixture, translations.tr().rules.ruleName, 'Mes jours conservés');
await clickDialogButton(fixture, translations.tr().rules.save);
await closed();
const toggle: HTMLButtonElement = fixture.nativeElement
.querySelector('.rule-item')
.querySelector('button[role="switch"]');
@@ -0,0 +1,216 @@
<h2 mat-dialog-title>{{ isNew ? tr().rules.addRule : tr().rules.editRule }}</h2>
<mat-dialog-content>
<div class="rule-editor">
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.ruleName }}</mat-label>
<input matInput [(ngModel)]="$any(editBuffer).name" required />
</mat-form-field>
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.force }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).force">
@for (option of forceOptions; track option.value) {
<mat-option [value]="option.value">{{ option.label() }}</mat-option>
}
</mat-select>
</mat-form-field>
@if ($any(editBuffer).type === RuleType.IF_THEN) {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.holidayFalls }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).dayOfWeek">
@for (day of daysOfWeek; track day.value) {
<mat-option [value]="day.value">{{ day.label }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.place }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).placeDays"
min="1"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placeType">
@for (type of placeDayTypes; track type) {
<mat-option [value]="type">{{ getDayTypeLabel(type) }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.position }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placement">
@for (opt of placementOptions; track opt.value) {
<mat-option [value]="opt.value">{{ opt.label }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.getBonus }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).rewardDays"
min="0"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).rewardType">
@for (type of rewardDayTypes; track type) {
<mat-option [value]="type">{{ getDayTypeLabel(type) }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
} @else if ($any(editBuffer).type === RuleType.OPTIMIZATION) {
@if (optimizationConfiguration; as configuration) {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.optimization.elementsLabel }}</mat-label>
<mat-select
[ngModel]="configuration.elements"
(ngModelChange)="changeOptimizationElements($event)"
>
@for (elements of optimizationElements; track elements) {
<mat-option [value]="elements">{{
tr().rules.optimization.elements[elements]
}}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.optimization.measureLabel }}</mat-label>
<mat-select
[ngModel]="configuration.measure"
(ngModelChange)="changeOptimizationMeasure($event)"
>
@for (row of optimizationMeasures; track row.measure) {
<mat-option [value]="row.measure">{{
tr().rules.optimization.measures[row.measure]
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
@if (optimizationConditions.length) {
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.optimization.conditionsLabel }}</mat-label>
<mat-select multiple [(ngModel)]="configuration.conditions">
@for (condition of optimizationConditions; track condition) {
<mat-option [value]="condition">{{
tr().rules.optimization.conditions[condition]
}}</mat-option>
}
</mat-select>
</mat-form-field>
}
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.optimization.aggregationLabel }}</mat-label>
<mat-select [(ngModel)]="configuration.aggregation">
@for (aggregation of optimizationAggregations; track aggregation) {
<mat-option [value]="aggregation">{{
tr().rules.optimization.aggregations[aggregation]
}}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.optimization.directionLabel }}</mat-label>
<mat-select [(ngModel)]="configuration.direction">
@for (direction of optimizationDirections; track direction) {
<mat-option [value]="direction">{{
tr().rules.optimization.directions[direction]
}}</mat-option>
}
</mat-select>
</mat-form-field>
@if (configuration.measure === 'work-sequence-deficit') {
<mat-form-field class="wide-label">
<mat-label>{{ tr().rules.optimization.thresholdLabel }}</mat-label>
<input
matInput
type="number"
min="1"
step="1"
required
[(ngModel)]="configuration.thresholdDays"
/>
</mat-form-field>
}
</div>
}
} @else {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.startDate }}</mat-label>
<input
matInput
[matDatepicker]="startPicker"
[(ngModel)]="$any(editBuffer).startDate"
/>
<mat-datepicker-toggle matSuffix [for]="startPicker"></mat-datepicker-toggle>
<mat-datepicker #startPicker></mat-datepicker>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.endDate }}</mat-label>
<input
matInput
[matDatepicker]="endPicker"
[(ngModel)]="$any(editBuffer).endDate"
/>
<mat-datepicker-toggle matSuffix [for]="endPicker"></mat-datepicker-toggle>
<mat-datepicker #endPicker></mat-datepicker>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.place }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).placeDays"
min="1"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placeType">
@for (type of placeDayTypes; track type) {
<mat-option [value]="type">{{ getDayTypeLabel(type) }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
}
</div>
</mat-dialog-content>
@if (validationError()) {
<p role="alert">{{ validationError() }}</p>
}
<mat-dialog-actions align="end">
<button mat-button type="button" mat-dialog-close>{{ tr().rules.cancel }}</button>
<button mat-flat-button type="button" color="primary" (click)="save()">
{{ isNew ? tr().rules.add : tr().rules.save }}
</button>
</mat-dialog-actions>
@@ -0,0 +1,55 @@
:host {
display: block;
}
.rule-editor {
display: flex;
flex-direction: column;
gap: 16px;
// Room for the floating label of the first field, which the scrolling content would clip.
padding-top: 0.5rem;
.editor-row {
display: flex;
flex-wrap: wrap;
gap: 16px;
align-items: center;
.action-text {
flex-basis: 100%;
font-weight: 500;
}
mat-form-field {
flex: 1 1 11rem;
min-width: 0;
max-width: 100%;
}
.small-input {
flex: 0 1 6.25rem;
}
// Its label is long: take a row of its own once the others leave no room for it.
.wide-label {
flex-basis: 16rem;
}
}
mat-form-field ::ng-deep .mat-mdc-form-field-subscript-wrapper {
display: none;
}
.full-width {
width: 100%;
min-width: 0;
}
}
[role='alert'] {
margin: 1rem 1.5rem 0;
padding: 0.75rem;
border-radius: var(--ui-radius-sm, 0.5rem);
color: var(--ui-error-text);
background: var(--ui-error-bg);
}
@@ -0,0 +1,237 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { By } from '@angular/platform-browser';
import { MatExpansionPanel } from '@angular/material/expansion';
import { RulesPanel } from './rules-panel';
import { RuleService, RuleType } from '../../services/rule-service';
import { TranslationService } from '../../services/translation-service';
import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives';
import { vi } from '../../../testing/vitest-compat';
import {
chooseInDialog,
clickDialogButton,
dialogButton,
dialogField,
ruleDialog,
typeInDialog,
} from '../../../testing/rule-dialog';
describe('rule dialog', () => {
let fixture: ComponentFixture<RulesPanel>;
let component: RulesPanel;
const addButton = (index: number) =>
fixture.nativeElement.querySelectorAll('.add-buttons button')[index] as HTMLButtonElement;
const editButton = (index: number) =>
fixture.nativeElement
.querySelectorAll('.rule-item')
[index].querySelector('[aria-label="Modifier la règle"]') as HTMLButtonElement;
const nameInput = () => dialogField('Nom de la règle').querySelector('input')!;
const title = () => ruleDialog()!.querySelector('h2')!.textContent!.trim();
const closed = () => expect.poll(() => ruleDialog()).toBeNull();
beforeEach(async () => {
localStorage.clear();
vi.setSystemTime(new Date('2024-01-01T12:00:00Z'));
await TestBed.configureTestingModule({
imports: [RulesPanel],
providers: [provideZonelessChangeDetection(), RuleService],
}).compileComponents();
TestBed.inject(TranslationService).setLanguage('fr');
fixture = TestBed.createComponent(RulesPanel);
component = fixture.componentInstance;
fixture.detectChanges();
fixture.debugElement.query(By.directive(MatExpansionPanel)).componentInstance.open();
await fixture.whenStable();
});
afterEach(() => {
localStorage.clear();
vi.useRealTimers();
});
it.each([
[0, 'Nouvelle règle'],
[1, 'Nouvelle période'],
[2, 'Éviter de perdre des jours'],
])('opens one dialog to add a rule of kind %i with its defaults', async (index, name) => {
addButton(index).focus();
addButton(index).click();
await fixture.whenStable();
expect(document.querySelectorAll('mat-dialog-container')).toHaveLength(1);
expect(title()).toBe('Ajouter une règle');
expect(nameInput().value).toBe(name);
await expect.poll(() => ruleDialog()!.contains(document.activeElement)).toBe(true);
expect(dialogButton('Ajouter')).toBeTruthy();
expect(ruleDialog()!.querySelector('[role="alert"]')).toBeNull();
});
it.each([
[1, 'Samedi Malin', 'Si un jour férié tombe un'],
[2, 'Vacances de Noël', 'Date de début'],
[5, 'Éviter les longues périodes sans congé', 'Éléments du planning'],
])(
'opens the same dialog to edit rule %i, filled with the saved rule',
async (index, name, field) => {
editButton(index).focus();
editButton(index).click();
await fixture.whenStable();
expect(title()).toBe('Modifier la règle');
expect(nameInput().value).toBe(name);
expect(dialogField(field)).toBeTruthy();
expect(dialogButton('Enregistrer')).toBeTruthy();
},
);
it('keeps the list as it is while a rule is being added or edited', async () => {
const list = () => fixture.nativeElement.querySelector('.rules-list').innerHTML;
const before = list();
editButton(1).click();
await fixture.whenStable();
nameInput().value = 'Pas encore enregistrée';
nameInput().dispatchEvent(new Event('input', { bubbles: true }));
await fixture.whenStable();
expect(list()).toBe(before);
expect(fixture.nativeElement.querySelector('.rule-editor')).toBeNull();
expect(fixture.nativeElement.querySelector('.add-buttons').classList).not.toContain(
'hidden',
);
});
it('adds a rule once Add is chosen and returns focus to the add button', async () => {
const count = component.rules.length;
addButton(0).focus();
addButton(0).click();
await fixture.whenStable();
await typeInDialog(fixture, 'Nom de la règle', 'Ma règle');
await chooseInDialog(fixture, 'Force de la règle', 'Obligation');
await chooseInDialog(fixture, 'Si un jour férié tombe un', 'Vendredi');
await clickDialogButton(fixture, 'Ajouter');
await closed();
expect(component.rules).toHaveLength(count + 1);
expect(component.rules.at(-1)).toEqual({
name: 'Ma règle',
type: RuleType.IF_THEN,
force: 'obligation',
dayOfWeek: 5,
placeDays: 2,
placeType: 'cp',
placement: 'auto',
rewardDays: 1,
rewardType: 'other',
id: expect.any(String),
enabled: true,
});
expect(document.activeElement).toBe(addButton(0));
});
it('adds an imposed period with the dates it was given', async () => {
addButton(1).click();
await fixture.whenStable();
await typeInDialog(fixture, 'Date de début', '21/12/2024');
await typeInDialog(fixture, 'Date de fin', '31/12/2024');
await typeInDialog(fixture, 'Jours', '4');
await clickDialogButton(fixture, 'Ajouter');
await closed();
const rule = component.rules.at(-1)!;
if (rule.type !== RuleType.TIME_WINDOW) throw new Error('Expected a time window');
expect(rule).toMatchObject({ name: 'Nouvelle période', force: 'preference', placeDays: 4 });
expect(new Date(rule.startDate)).toEqual(new Date(2024, 11, 21));
expect(new Date(rule.endDate)).toEqual(new Date(2024, 11, 31));
});
it('replaces the saved rule with the edited one and returns focus to the edit button', async () => {
const ifThen = component.rules[1];
const optimization = component.rules[5];
editButton(1).focus();
editButton(1).click();
await fixture.whenStable();
await typeInDialog(fixture, 'Nom de la règle', 'Samedi modifié');
await chooseInDialog(fixture, 'Position', 'Avant');
await clickDialogButton(fixture, 'Enregistrer');
await closed();
expect(component.rules[1]).toEqual({
...ifThen,
name: 'Samedi modifié',
placement: 'before',
});
expect(document.activeElement).toBe(editButton(1));
editButton(5).click();
await fixture.whenStable();
await chooseInDialog(fixture, 'Objectif', 'Maximiser');
await clickDialogButton(fixture, 'Enregistrer');
await closed();
expect(component.rules[5]).toEqual({
...optimization,
configuration: { ...OPTIMIZATION_PRESETS.longestWorkSequence, direction: 'maximize' },
});
expect(component.rules).toHaveLength(8);
});
it.each(['Annuler', 'Escape'])(
'%s closes the dialog without saving and returns focus to the control that opened it',
async (way) => {
const before = structuredClone(component.rules);
editButton(2).focus();
editButton(2).click();
await fixture.whenStable();
await typeInDialog(fixture, 'Nom de la règle', 'Ne pas enregistrer');
if (way === 'Escape') {
ruleDialog()!.dispatchEvent(
new KeyboardEvent('keydown', {
key: 'Escape',
code: 'Escape',
keyCode: 27,
bubbles: true,
}),
);
await fixture.whenStable();
} else await clickDialogButton(fixture, way);
await closed();
expect(component.rules).toEqual(before);
expect(document.activeElement).toBe(editButton(2));
addButton(2).focus();
addButton(2).click();
await fixture.whenStable();
await clickDialogButton(fixture, way === 'Escape' ? 'Annuler' : way);
await closed();
expect(component.rules).toEqual(before);
expect(document.activeElement).toBe(addButton(2));
},
);
it('keeps the dialog open and shows the error beside the form until the rule is valid', async () => {
addButton(0).click();
await fixture.whenStable();
await typeInDialog(fixture, 'Nom de la règle', ' ');
await clickDialogButton(fixture, 'Ajouter');
expect(ruleDialog()).not.toBeNull();
expect(ruleDialog()!.querySelector('[role="alert"]')!.textContent).toContain(
'Saisissez un nom de règle.',
);
expect(component.rules).toHaveLength(8);
await typeInDialog(fixture, 'Nom de la règle', 'Règle valide');
await clickDialogButton(fixture, 'Ajouter');
await closed();
expect(component.rules.at(-1)!.name).toBe('Règle valide');
});
it('shows the optimization error without changing the saved rule', async () => {
editButton(6).click();
await fixture.whenStable();
await typeInDialog(fixture, 'Seuil en jours ouvrés', '0');
await clickDialogButton(fixture, 'Enregistrer');
expect(ruleDialog()!.querySelector('[role="alert"]')!.textContent).toContain(
'doit être un entier positif',
);
expect(component.rules[6]).toMatchObject({
configuration: OPTIMIZATION_PRESETS.shortSequenceDeficit,
});
});
});
@@ -0,0 +1,225 @@
import { ChangeDetectionStrategy, Component, effect, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { DateAdapter } from '@angular/material/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import {
MAT_DIALOG_DATA,
MatDialogActions,
MatDialogClose,
MatDialogContent,
MatDialogRef,
MatDialogTitle,
} from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { SelectableDayType } from '../../services/calendar-service';
import {
IfThenRule,
OptimizationRule,
PlacementStrategy,
RuleType,
TimeWindowRule,
VacationRule,
} from '../../services/rule-service';
import {
OPTIMIZATION_CATALOG,
OPTIMIZATION_PRESETS,
validateOptimizationConfiguration,
type OptimizationElements,
type OptimizationMeasure,
} from '../../services/planning-objectives';
import { TranslationService } from '../../services/translation-service';
import { DAY_FIRST_DATE_PROVIDERS } from '../../shared/day-first-date-adapter';
/** The rule to edit, or the kind of rule to create. */
export type RuleDialogData = { rule: VacationRule } | { type: RuleType };
/** Adds or edits one planning rule; closes with the saved rule, or with nothing when cancelled. */
@Component({
selector: 'app-rule-dialog',
imports: [
MatButtonModule,
MatDatepickerModule,
MatDialogActions,
MatDialogClose,
MatDialogContent,
MatDialogTitle,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
FormsModule,
],
templateUrl: './rule-dialog.html',
styleUrl: './rule-dialog.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: DAY_FIRST_DATE_PROVIDERS,
})
export class RuleDialog {
private readonly data = inject<RuleDialogData>(MAT_DIALOG_DATA);
private readonly dialogRef = inject<MatDialogRef<RuleDialog, VacationRule>>(MatDialogRef);
protected readonly translationService = inject(TranslationService);
private readonly dateAdapter = inject(DateAdapter);
get tr() {
return this.translationService.tr;
}
constructor() {
effect(() => {
this.dateAdapter.setLocale(this.translationService.locale());
});
}
protected readonly RuleType = RuleType;
protected readonly isNew = !('rule' in this.data);
protected readonly placeDayTypes = Object.values(SelectableDayType);
protected readonly rewardDayTypes = Object.values(SelectableDayType).filter(
(t) => t !== SelectableDayType.ANY,
);
protected get forceOptions() {
const preference = {
value: 'preference' as const,
label: () => this.tr().rules.preference,
};
return this.editBuffer.type === RuleType.OPTIMIZATION
? [preference]
: [
{ value: 'obligation' as const, label: () => this.tr().rules.obligation },
preference,
];
}
protected readonly optimizationElements = [
...new Set(OPTIMIZATION_CATALOG.map((row) => row.elements)),
];
protected get optimizationConfiguration() {
return this.editBuffer.type === RuleType.OPTIMIZATION
? this.editBuffer.configuration
: undefined;
}
protected get optimizationMeasures() {
return OPTIMIZATION_CATALOG.filter(
(row) => row.elements === this.optimizationConfiguration?.elements,
);
}
protected get optimizationConditions() {
return (
this.optimizationMeasures.find(
(row) => row.measure === this.optimizationConfiguration?.measure,
)?.conditions ?? []
);
}
protected readonly optimizationAggregations = ['sum', 'count', 'maximum'] as const;
protected readonly optimizationDirections = ['minimize', 'maximize'] as const;
protected validationError = signal('');
public changeOptimizationElements(elements: OptimizationElements) {
this.changeOptimizationMeasure(
OPTIMIZATION_CATALOG.find((row) => row.elements === elements)!.measure,
);
}
public changeOptimizationMeasure(measure: OptimizationMeasure) {
if (this.editBuffer.type !== RuleType.OPTIMIZATION) return;
const row = OPTIMIZATION_CATALOG.find((item) => item.measure === measure)!;
const previous = this.editBuffer.configuration;
const conditions: readonly string[] = row.conditions;
this.editBuffer.configuration = {
elements: row.elements,
conditions:
previous?.conditions.filter((condition) => conditions.includes(condition)) ?? [],
aggregation: previous?.aggregation ?? 'sum',
direction: previous?.direction ?? 'minimize',
...(measure === 'work-sequence-deficit'
? {
measure,
thresholdDays: previous?.measure === measure ? previous.thresholdDays : 5,
}
: { measure }),
};
}
protected get daysOfWeek() {
const tr = this.tr();
return [
{ value: 1, label: tr.rules.daysOfWeek[1] },
{ value: 2, label: tr.rules.daysOfWeek[2] },
{ value: 3, label: tr.rules.daysOfWeek[3] },
{ value: 4, label: tr.rules.daysOfWeek[4] },
{ value: 5, label: tr.rules.daysOfWeek[5] },
{ value: 6, label: tr.rules.daysOfWeek[6] },
{ value: 0, label: tr.rules.daysOfWeek[0] },
];
}
protected get placementOptions(): { value: PlacementStrategy; label: string }[] {
const tr = this.tr();
return [
{ value: 'before', label: tr.rules.placement.before },
{ value: 'after', label: tr.rules.placement.after },
{ value: 'around', label: tr.rules.placement.around },
{ value: 'auto', label: tr.rules.placement.auto },
];
}
protected editBuffer: Partial<VacationRule> =
'rule' in this.data ? structuredClone(this.data.rule) : this.newRule(this.data.type);
private newRule(type: RuleType): Partial<VacationRule> {
if (type === RuleType.IF_THEN) {
return {
name: this.tr().rules.defaultNewRuleName,
type: RuleType.IF_THEN,
force: 'preference',
dayOfWeek: 6,
placeDays: 2,
placeType: SelectableDayType.CP,
placement: 'auto',
rewardDays: 1,
rewardType: SelectableDayType.OTHER,
} as Partial<IfThenRule>;
}
if (type === RuleType.OPTIMIZATION) {
return {
name: this.tr().rules.optimization.defaultName,
type,
force: 'preference',
configuration: structuredClone(OPTIMIZATION_PRESETS.unplacedAtRisk),
} satisfies Partial<OptimizationRule>;
}
return {
name: this.tr().rules.defaultNewPeriodName,
type: RuleType.TIME_WINDOW,
force: 'preference',
startDate: new Date(),
endDate: new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000),
placeDays: 5,
placeType: SelectableDayType.CP,
} as Partial<TimeWindowRule>;
}
protected getDayTypeLabel(type: string | undefined | null): string {
if (!type) return '';
return this.translationService.getDayTypeLabel(type);
}
protected save() {
if (!this.editBuffer.name?.trim()) {
this.validationError.set(this.tr().rules.optimization.nameRequired);
return;
}
if (this.editBuffer.type === RuleType.OPTIMIZATION) {
if (!validateOptimizationConfiguration(this.editBuffer.configuration).valid) {
this.validationError.set(this.tr().rules.optimization.invalidConfiguration);
return;
}
this.editBuffer.force = 'preference';
}
this.dialogRef.close(
(this.isNew
? { ...this.editBuffer, id: crypto.randomUUID(), enabled: true }
: this.editBuffer) as VacationRule,
);
}
}
+66 -465
View File
@@ -3,7 +3,7 @@
<mat-panel-title>
<mat-icon aria-hidden="true">rule</mat-icon>
<span>{{ tr().rules.title }}</span>
<span class="rule-count">{{ activeRuleCount }} {{ tr().rules.active }}</span>
<span class="rule-count">{{ activeRules }}</span>
</mat-panel-title>
<mat-panel-description> {{ tr().rules.subtitle }} </mat-panel-description>
</mat-expansion-panel-header>
@@ -20,401 +20,75 @@
cdkDrag
cdkDragLockAxis="y"
[cdkDragStartDelay]="{ touch: 180, mouse: 0 }"
[cdkDragDisabled]="editingRuleId() === rule.id"
[class.editing]="editingRuleId() === rule.id"
>
@if (editingRuleId() !== rule.id) {
<div class="rule-display">
<div class="rule-header">
<div
class="rule-drag-grip"
cdkDragHandle
[title]="tr().rules.dragRule"
aria-hidden="true"
>
<mat-icon>drag_indicator</mat-icon>
</div>
<mat-slide-toggle
[checked]="rule.enabled"
(change)="toggleRule(rule.id)"
color="primary"
>
<span class="rule-name"
><span class="rule-number">{{ i + 1 }}.</span>
{{ rule.name }}</span
>
</mat-slide-toggle>
<div class="rule-display">
<div class="rule-header">
<div
class="rule-drag-grip"
cdkDragHandle
[title]="tr().rules.dragRule"
aria-hidden="true"
>
<mat-icon>drag_indicator</mat-icon>
</div>
<div class="rule-summary">
<span
class="rule-force"
[class.obligation]="rule.force === 'obligation'"
<mat-slide-toggle
[checked]="rule.enabled"
(change)="toggleRule(rule.id)"
color="primary"
>
<span class="rule-name"
><span class="rule-number">{{ i + 1 }}.</span> {{ rule.name }}</span
>
{{
rule.force === 'obligation'
? tr().rules.obligation
: tr().rules.preference
}}
</span>
<span [innerHTML]="getRuleSummary(rule)"></span>
</div>
<div class="rule-actions">
<button
mat-icon-button
[disabled]="i === 0"
[aria-label]="tr().rules.moveRuleUp"
(click)="moveRule(i, -1, $event)"
>
<mat-icon aria-hidden="true">keyboard_arrow_up</mat-icon>
</button>
<button
mat-icon-button
[disabled]="i === rules.length - 1"
[aria-label]="tr().rules.moveRuleDown"
(click)="moveRule(i, 1, $event)"
>
<mat-icon aria-hidden="true">keyboard_arrow_down</mat-icon>
</button>
<button
mat-icon-button
[aria-label]="tr().rules.editRule"
(click)="startEdit(rule, $event)"
>
<mat-icon>edit</mat-icon>
</button>
<button
mat-icon-button
color="warn"
[aria-label]="tr().rules.deleteRule"
(click)="deleteRule(rule.id, $event)"
>
<mat-icon>delete</mat-icon>
</button>
</div>
</mat-slide-toggle>
</div>
} @else {
<div class="rule-editor">
<h4>{{ tr().rules.editRule }}</h4>
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.ruleName }}</mat-label>
<input matInput [(ngModel)]="$any(editBuffer).name" required />
</mat-form-field>
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.force }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).force">
@for (option of forceOptions; track option.value) {
<mat-option [value]="option.value">{{
option.label()
}}</mat-option>
}
</mat-select>
</mat-form-field>
@if ($any(editBuffer).type === RuleType.IF_THEN) {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.holidayFalls }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).dayOfWeek">
@for (day of daysOfWeek; track day.value) {
<mat-option [value]="day.value">{{
day.label
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.place }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).placeDays"
min="1"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placeType">
@for (type of placeDayTypes; track type) {
<mat-option [value]="type">{{
getDayTypeLabel(type)
}}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.position }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placement">
@for (opt of placementOptions; track opt.value) {
<mat-option [value]="opt.value">{{
opt.label
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.getBonus }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).rewardDays"
min="0"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).rewardType">
@for (type of rewardDayTypes; track type) {
<mat-option [value]="type">{{
getDayTypeLabel(type)
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
} @else if ($any(editBuffer).type === RuleType.OPTIMIZATION) {
<ng-container [ngTemplateOutlet]="optimizationEditor" />
} @else {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.startDate }}</mat-label>
<input
matInput
[matDatepicker]="startPicker"
[(ngModel)]="$any(editBuffer).startDate"
/>
<mat-datepicker-toggle
matSuffix
[for]="startPicker"
></mat-datepicker-toggle>
<mat-datepicker #startPicker></mat-datepicker>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.endDate }}</mat-label>
<input
matInput
[matDatepicker]="endPicker"
[(ngModel)]="$any(editBuffer).endDate"
/>
<mat-datepicker-toggle
matSuffix
[for]="endPicker"
></mat-datepicker-toggle>
<mat-datepicker #endPicker></mat-datepicker>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.place }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).placeDays"
min="1"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placeType">
@for (type of placeDayTypes; track type) {
<mat-option [value]="type">{{
getDayTypeLabel(type)
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
}
@if (validationError()) {
<p role="alert">{{ validationError() }}</p>
}
<div class="editor-actions">
<button mat-button (click)="cancelEdit()">
{{ tr().rules.cancel }}
</button>
<button mat-flat-button color="primary" (click)="saveEdit()">
{{ tr().rules.save }}
</button>
</div>
<div class="rule-summary">
<span class="rule-force" [class.obligation]="rule.force === 'obligation'">
{{
rule.force === 'obligation'
? tr().rules.obligation
: tr().rules.preference
}}
</span>
<span [innerHTML]="getRuleSummary(rule)"></span>
</div>
}
</div>
}
@if (isAddingNew()) {
<div class="rule-item editing">
<div class="rule-editor">
<h4>{{ tr().rules.addRule }}</h4>
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.ruleName }}</mat-label>
<input matInput [(ngModel)]="$any(editBuffer).name" required />
</mat-form-field>
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.force }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).force">
@for (option of forceOptions; track option.value) {
<mat-option [value]="option.value">{{ option.label() }}</mat-option>
}
</mat-select>
</mat-form-field>
@if (newRuleType() === RuleType.IF_THEN) {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.holidayFalls }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).dayOfWeek">
@for (day of daysOfWeek; track day.value) {
<mat-option [value]="day.value">{{ day.label }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.place }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).placeDays"
min="1"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placeType">
@for (type of placeDayTypes; track type) {
<mat-option [value]="type">{{
getDayTypeLabel(type)
}}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.position }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placement">
@for (opt of placementOptions; track opt.value) {
<mat-option [value]="opt.value">{{ opt.label }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.getBonus }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).rewardDays"
min="0"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).rewardType">
@for (type of rewardDayTypes; track type) {
<mat-option [value]="type">{{
getDayTypeLabel(type)
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
} @else if ($any(editBuffer).type === RuleType.OPTIMIZATION) {
<ng-container [ngTemplateOutlet]="optimizationEditor" />
} @else {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.startDate }}</mat-label>
<input
matInput
[matDatepicker]="startPicker"
[(ngModel)]="$any(editBuffer).startDate"
/>
<mat-datepicker-toggle
matSuffix
[for]="startPicker"
></mat-datepicker-toggle>
<mat-datepicker #startPicker></mat-datepicker>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.endDate }}</mat-label>
<input
matInput
[matDatepicker]="endPicker"
[(ngModel)]="$any(editBuffer).endDate"
/>
<mat-datepicker-toggle
matSuffix
[for]="endPicker"
></mat-datepicker-toggle>
<mat-datepicker #endPicker></mat-datepicker>
</mat-form-field>
</div>
<div class="editor-row">
<span class="action-text">{{ tr().rules.place }}</span>
<mat-form-field class="small-input">
<mat-label>{{ tr().rules.days }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).placeDays"
min="1"
/>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.type }}</mat-label>
<mat-select [(ngModel)]="$any(editBuffer).placeType">
@for (type of placeDayTypes; track type) {
<mat-option [value]="type">{{
getDayTypeLabel(type)
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
}
@if (validationError()) {
<p role="alert">{{ validationError() }}</p>
}
<div class="editor-actions">
<button mat-button (click)="cancelEdit()">{{ tr().rules.cancel }}</button>
<button mat-flat-button color="primary" (click)="saveEdit()">
{{ tr().rules.add }}
<div class="rule-actions">
<button
mat-icon-button
[disabled]="i === 0"
[aria-label]="tr().rules.moveRuleUp"
(click)="moveRule(i, -1, $event)"
>
<mat-icon aria-hidden="true">keyboard_arrow_up</mat-icon>
</button>
<button
mat-icon-button
[disabled]="i === rules.length - 1"
[aria-label]="tr().rules.moveRuleDown"
(click)="moveRule(i, 1, $event)"
>
<mat-icon aria-hidden="true">keyboard_arrow_down</mat-icon>
</button>
<button
mat-icon-button
[aria-label]="tr().rules.editRule"
(click)="startEdit(rule, $event)"
>
<mat-icon>edit</mat-icon>
</button>
<button
mat-icon-button
color="warn"
[aria-label]="tr().rules.deleteRule"
(click)="deleteRule(rule.id, $event)"
>
<mat-icon>delete</mat-icon>
</button>
</div>
</div>
</div>
}
<div class="add-buttons" [class.hidden]="isAddingNew() || editingRuleId()">
<div class="add-buttons">
<button mat-stroked-button (click)="startAddNew(RuleType.IF_THEN)">
<mat-icon>add</mat-icon> {{ tr().rules.newIfThenRule }}
</button>
@@ -424,86 +98,13 @@
<button mat-stroked-button (click)="startAddNew(RuleType.OPTIMIZATION)">
<mat-icon aria-hidden="true">add</mat-icon> {{ tr().rules.optimization.newRule }}
</button>
<button mat-stroked-button [disabled]="!shareResult()" (click)="share()">
<mat-icon aria-hidden="true">share</mat-icon>
{{ tr().rules.share[copyOutcome() ?? 'action'] }}
</button>
@if (shareAlert(); as alert) {
<p class="share-alert" role="alert">{{ alert }}</p>
}
</div>
</div>
</mat-expansion-panel>
<ng-template #optimizationEditor>
@if (optimizationConfiguration; as configuration) {
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.optimization.elementsLabel }}</mat-label>
<mat-select
[ngModel]="configuration.elements"
(ngModelChange)="changeOptimizationElements($event)"
>
@for (elements of optimizationElements; track elements) {
<mat-option [value]="elements">{{
tr().rules.optimization.elements[elements]
}}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.optimization.measureLabel }}</mat-label>
<mat-select
[ngModel]="configuration.measure"
(ngModelChange)="changeOptimizationMeasure($event)"
>
@for (row of optimizationMeasures; track row.measure) {
<mat-option [value]="row.measure">{{
tr().rules.optimization.measures[row.measure]
}}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
@if (optimizationConditions.length) {
<mat-form-field class="full-width">
<mat-label>{{ tr().rules.optimization.conditionsLabel }}</mat-label>
<mat-select multiple [(ngModel)]="configuration.conditions">
@for (condition of optimizationConditions; track condition) {
<mat-option [value]="condition">{{
tr().rules.optimization.conditions[condition]
}}</mat-option>
}
</mat-select>
</mat-form-field>
}
<div class="editor-row">
<mat-form-field>
<mat-label>{{ tr().rules.optimization.aggregationLabel }}</mat-label>
<mat-select [(ngModel)]="configuration.aggregation">
@for (aggregation of optimizationAggregations; track aggregation) {
<mat-option [value]="aggregation">{{
tr().rules.optimization.aggregations[aggregation]
}}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>{{ tr().rules.optimization.directionLabel }}</mat-label>
<mat-select [(ngModel)]="configuration.direction">
@for (direction of optimizationDirections; track direction) {
<mat-option [value]="direction">{{
tr().rules.optimization.directions[direction]
}}</mat-option>
}
</mat-select>
</mat-form-field>
@if (configuration.measure === 'work-sequence-deficit') {
<mat-form-field>
<mat-label>{{ tr().rules.optimization.thresholdLabel }}</mat-label>
<input
matInput
type="number"
min="1"
step="1"
required
[(ngModel)]="configuration.thresholdDays"
/>
</mat-form-field>
}
</div>
}
</ng-template>
@@ -71,13 +71,9 @@
background: var(--ui-panel-bg);
color: var(--mat-sys-on-surface);
&:hover:not(.editing) {
&:hover {
border-color: var(--mat-sys-outline, #777680);
}
&.editing {
border: 1px solid var(--mat-sys-primary, #005cbb);
}
}
.cdk-drag-preview {
@@ -213,59 +209,6 @@
}
}
.rule-editor {
padding: clamp(0.75rem, 3cqi, 1.25rem);
display: flex;
flex-direction: column;
gap: 16px;
background: var(--mat-sys-surface-container-high, #e9e9ee);
border-radius: var(--ui-radius-sm, 0.5rem);
h4 {
margin: 0;
font-size: 1.1rem;
font-weight: 500;
}
.editor-row {
display: flex;
flex-wrap: wrap;
gap: 16px;
align-items: center;
.action-text {
flex-basis: 100%;
font-weight: 500;
}
mat-form-field {
flex: 1 1 11rem;
min-width: 0;
max-width: 100%;
::ng-deep .mat-mdc-form-field-subscript-wrapper {
display: none;
}
}
.small-input {
flex: 0 1 6.25rem;
}
}
.full-width {
width: 100%;
min-width: 0;
}
.editor-actions {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 12px;
margin-top: 8px;
}
}
.add-buttons {
display: flex;
flex-wrap: wrap;
@@ -273,10 +216,6 @@
gap: 8px;
margin-top: 8px;
&.hidden {
display: none;
}
button {
border-radius: var(--ui-radius-sm);
min-height: 2.75rem;
@@ -284,6 +223,14 @@
padding-block: 0.625rem;
width: 100%;
}
.share-alert {
margin: 0;
padding: 0.75rem;
border-radius: var(--ui-radius-sm);
background: var(--ui-error-bg);
color: var(--ui-error-text);
}
}
@container rule-item (max-width: 18rem) {
@@ -1,7 +1,13 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { RulesPanel } from './rules-panel';
import { RuleService, RuleType } from '../../services/rule-service';
import { RuleService, RuleType, type VacationRule } from '../../services/rule-service';
import { SelectableDayType } from '../../services/calendar-service';
import { RuleSetImport } from '../rule-set-import/rule-set-import';
import de from '../../../i18n/de.json';
import en from '../../../i18n/en.json';
import es from '../../../i18n/es.json';
import fr from '../../../i18n/fr.json';
import { TranslationService } from '../../services/translation-service';
import { By } from '@angular/platform-browser';
import { CdkDragDrop, CdkDropList } from '@angular/cdk/drag-drop';
@@ -9,10 +15,18 @@ import { LiveAnnouncer } from '@angular/cdk/a11y';
import { vi } from '../../../testing/vitest-compat';
import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives';
import { MatExpansionPanel } from '@angular/material/expansion';
import {
chooseInDialog,
clickDialogButton,
dialogField,
ruleDialog,
typeInDialog,
} from '../../../testing/rule-dialog';
describe('RulesPanel', () => {
let component: RulesPanel;
let fixture: ComponentFixture<RulesPanel>;
const closed = () => expect.poll(() => ruleDialog()).toBeNull();
beforeEach(async () => {
// Clear localStorage before testing
@@ -41,55 +55,48 @@ describe('RulesPanel', () => {
expect(component.rules.length).toBe(8);
});
it('should start adding new If-Then rule', () => {
component.startAddNew(RuleType.IF_THEN);
expect(component['isAddingNew']()).toBe(true);
expect(component['newRuleType']()).toBe(RuleType.IF_THEN);
expect(component['editBuffer'].type).toBe(RuleType.IF_THEN);
expect(component['editBuffer'].name).toBe('Nouvelle Règle');
it('describes the supplied rules in plain words in every language', () => {
const summaries = () => component.rules.map((rule) => component.getRuleSummary(rule));
expect(summaries()).toEqual([
'Poser les jours qui expirent pendant la période planifiée, pour en perdre le moins possible.',
'Si un jour férié tombe un <strong>samedi</strong>, poser <strong>2 jours de congés payés</strong> au meilleur moment autour de ce jour et gagner <strong>1 jour de type Autre</strong>.',
expect.stringMatching(
/^Poser <strong>5 jours de congé de tout type<\/strong> entre le <strong>20\/12\/\d{4}<\/strong> et le <strong>03\/01\/\d{4}<\/strong>\.$/,
),
'Prendre la semaine entière quand elle contient un jour férié, surtout s’il tombe en milieu de semaine.',
'Coller les congés aux week-ends et aux jours fériés, pour gagner un maximum de jours de repos sans les poser.',
'Répartir les congés pour raccourcir la plus longue période de travail sans congé.',
'Éviter de reprendre le travail pour moins de 5 jours ouvrés entre deux périodes de repos.',
'Poser le moins possible de jours qui n’expirent qu’après la période planifiée, afin de les garder pour plus tard.',
]);
const translations = TestBed.inject(TranslationService);
for (const language of translations.availableLanguages) {
translations.setLanguage(language);
for (const summary of summaries()) expect(summary).not.toMatch(/[{}]|\(s\)/);
}
translations.setLanguage('en');
expect(summaries()[1]).toBe(
'If a public holiday falls on a <strong>Saturday</strong>, take <strong>2 days of paid leave</strong> around it where it helps most and earn <strong>1 day of Other leave</strong>.',
);
translations.setLanguage('de');
expect(summaries()[1]).toBe(
'Wenn ein Feiertag auf einen <strong>Samstag</strong> fällt, <strong>2 Tage bezahlten Urlaub</strong> bestmöglich rund um den Feiertag nehmen und <strong>1 Tag der Art „Andere“</strong> erwerben.',
);
});
it('should start adding new Time Window rule', () => {
component.startAddNew(RuleType.TIME_WINDOW);
expect(component['isAddingNew']()).toBe(true);
expect(component['newRuleType']()).toBe(RuleType.TIME_WINDOW);
expect(component['editBuffer'].type).toBe(RuleType.TIME_WINDOW);
expect(component['editBuffer'].name).toBe('Nouvelle Période');
});
it('should cancel edit', () => {
component.startAddNew(RuleType.IF_THEN);
component.cancelEdit();
expect(component['isAddingNew']()).toBe(false);
expect(component['editingRuleId']()).toBeNull();
expect(Object.keys(component['editBuffer']).length).toBe(0);
});
it('should save a new rule', () => {
const initialCount = component.rules.length;
component.startAddNew(RuleType.IF_THEN);
component['editBuffer'].name = 'Custom Test Rule';
component.saveEdit();
expect(component.rules.length).toBe(initialCount + 1);
expect(component.rules.some((r) => r.name === 'Custom Test Rule')).toBe(true);
});
it('should update an existing rule', () => {
const targetRule = component.rules[0];
// Create a mock event with stopPropagation
const mockEvent = { stopPropagation: () => {} } as Event;
component.startEdit(targetRule, mockEvent);
component['editBuffer'].name = 'Updated Name';
component.saveEdit();
expect(component.rules.find((r) => r.id === targetRule.id)?.name).toBe('Updated Name');
it('leaves out zero earned days and counts a single day in the singular', () => {
const samediMalin = component.rules[1];
if (samediMalin.type !== RuleType.IF_THEN) throw new Error('Expected an IF_THEN rule');
expect(
component.getRuleSummary({
...samediMalin,
placeDays: 1,
rewardDays: 0,
placement: 'before',
}),
).toBe(
'Si un jour férié tombe un <strong>samedi</strong>, poser <strong>1 jour de congés payés</strong> juste avant.',
);
});
it('should delete a rule', () => {
@@ -121,11 +128,20 @@ describe('RulesPanel', () => {
it('creates, edits and moves an optimization using the keyboard controls with preference-only mode', async () => {
fixture.debugElement.query(By.directive(MatExpansionPanel)).componentInstance.open();
component.startAddNew(RuleType.OPTIMIZATION);
fixture.detectChanges();
expect(component['forceOptions'].map((option) => option.value)).toEqual(['preference']);
expect(fixture.nativeElement.textContent).toContain('Éléments du planning');
component['editBuffer'].name = 'Mes pertes';
component.saveEdit();
await fixture.whenStable();
dialogField('Force de la règle').querySelector<HTMLElement>('mat-select')!.click();
await fixture.whenStable();
expect(
Array.from(document.querySelectorAll('mat-option')).map((option) =>
option.textContent?.trim(),
),
).toEqual(['Préférence']);
document.querySelector<HTMLElement>('.cdk-overlay-transparent-backdrop')!.click();
await fixture.whenStable();
expect(ruleDialog()!.textContent).toContain('Éléments du planning');
await typeInDialog(fixture, 'Nom de la règle', 'Mes pertes');
await clickDialogButton(fixture, 'Ajouter');
await closed();
await fixture.whenStable();
const rule = component.rules.at(-1)!;
expect(rule).toMatchObject({
@@ -134,7 +150,9 @@ describe('RulesPanel', () => {
force: 'preference',
configuration: OPTIMIZATION_PRESETS.unplacedAtRisk,
});
expect(component.getRuleSummary(rule)).toContain('Quantité non placée');
expect(component.getRuleSummary(rule)).toBe(
'Poser les jours qui expirent pendant la période planifiée, pour en perdre le moins possible.',
);
const announce = vi.spyOn(TestBed.inject(LiveAnnouncer), 'announce').mockResolvedValue();
const buttons = fixture.nativeElement.querySelectorAll('.rule-item');
const moveUp: HTMLButtonElement =
@@ -146,8 +164,10 @@ describe('RulesPanel', () => {
expect(document.activeElement).toBe(moveUp);
expect(announce).toHaveBeenCalledWith('Mes pertes : position 8 sur 9.');
component.startEdit(rule, new Event('click'));
component['editBuffer'].name = 'Pertes modifiées';
component.saveEdit();
await fixture.whenStable();
await typeInDialog(fixture, 'Nom de la règle', 'Pertes modifiées');
await clickDialogButton(fixture, 'Enregistrer');
await closed();
expect(component.rules[7].name).toBe('Pertes modifiées');
component.toggleRule(rule.id);
expect(component.rules[7].enabled).toBe(false);
@@ -155,26 +175,32 @@ describe('RulesPanel', () => {
expect(component.rules.some((candidate) => candidate.id === rule.id)).toBe(false);
});
it('keeps saved optimization parameters when an edit is cancelled and reports invalid parameters', () => {
it('keeps saved optimization parameters when an edit is cancelled and reports invalid parameters', async () => {
component.startAddNew(RuleType.OPTIMIZATION);
component.saveEdit();
await fixture.whenStable();
await clickDialogButton(fixture, 'Ajouter');
await closed();
const rule = component.rules.at(-1)!;
component.startEdit(rule, new Event('click'));
const configuration = component['optimizationConfiguration']!;
configuration.conditions = [];
component.cancelEdit();
await fixture.whenStable();
await chooseInDialog(
fixture,
'Conditions (toutes doivent être vérifiées)',
'Expirant pendant la période planifiée',
);
await clickDialogButton(fixture, 'Annuler');
await closed();
expect(component.rules.at(-1)).toMatchObject({
configuration: OPTIMIZATION_PRESETS.unplacedAtRisk,
});
component.startEdit(rule, new Event('click'));
component.changeOptimizationMeasure('work-sequence-deficit');
const invalid = component['optimizationConfiguration'];
if (invalid?.measure !== 'work-sequence-deficit') throw new Error('Expected deficit');
invalid.thresholdDays = 0;
component.saveEdit();
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('[role="alert"]').textContent).toContain(
'seuil entier positif',
await fixture.whenStable();
await chooseInDialog(fixture, 'Éléments du planning', 'Périodes de travail');
await chooseInDialog(fixture, 'Mesure', 'Jours manquants pour atteindre le seuil');
await typeInDialog(fixture, 'Seuil en jours ouvrés', '0');
await clickDialogButton(fixture, 'Enregistrer');
expect(ruleDialog()!.querySelector('[role="alert"]')!.textContent).toContain(
'doit être un entier positif',
);
expect(component.rules.at(-1)).toMatchObject({
configuration: OPTIMIZATION_PRESETS.unplacedAtRisk,
@@ -211,4 +237,239 @@ describe('RulesPanel', () => {
);
expect(fixture.nativeElement.querySelectorAll('.rule-number')[1].textContent).toBe('2.');
});
describe('Share my rules', () => {
const shareButton = (): HTMLButtonElement =>
fixture.nativeElement.querySelector('.add-buttons button:last-of-type');
const shareLabel = () =>
shareButton().querySelector('.mdc-button__label')!.textContent!.trim();
const shareAlert = (): HTMLElement | null =>
fixture.nativeElement.querySelector('.add-buttons [role="alert"]');
const ready = () => expect.poll(() => shareButton().disabled).toBe(false);
/** Lets the promises of a share or a copy settle, then renders. */
const settled = async () => {
await new Promise<void>((resolve) => setImmediate(resolve));
fixture.detectChanges();
};
const link = () => expect.stringMatching(/^http:\/\/localhost:3000\/#rules=[\w-]+$/);
const done = () => Promise.resolve();
function stubShare(outcome: () => Promise<void>) {
const share = vi.fn((data: ShareData) => (void data, outcome()));
Object.defineProperty(navigator, 'share', { configurable: true, value: share });
return share;
}
function stubClipboard(outcome: () => Promise<void>) {
const writeText = vi.fn((text: string) => (void text, outcome()));
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText },
});
return writeText;
}
const reversedWindow: VacationRule = {
id: 'reversed',
name: 'Fenêtre inversée',
type: RuleType.TIME_WINDOW,
enabled: false,
force: 'preference',
startDate: new Date(2027, 0, 3),
endDate: new Date(2026, 11, 20),
placeDays: 5,
placeType: SelectableDayType.ANY,
};
afterEach(() => {
vi.useRealTimers();
Reflect.deleteProperty(navigator, 'share');
Reflect.deleteProperty(navigator, 'clipboard');
history.replaceState(null, '', '/');
});
it('is disabled while the link of the rule set is being computed, again after every change of the rule set', async () => {
const share = stubShare(done);
expect(shareLabel()).toBe('Partager mes règles');
expect(shareButton().disabled).toBe(true);
await ready();
component.toggleRule(component.rules[0].id);
fixture.detectChanges();
expect(shareButton().disabled).toBe(true);
shareButton().click();
expect(share).not.toHaveBeenCalled();
await ready();
});
it('opens the share sheet inside the click with the share title and a link that offers the same rules to import', async () => {
const share = stubShare(done);
const writeText = stubClipboard(done);
const sharedRules = component.rules;
await ready();
shareButton().click();
// No await since the click: the share sheet opened inside it.
expect(share.mock.calls).toEqual([
[{ title: 'Mes règles de planification VacOptimizer', url: link() }],
]);
await settled();
expect(writeText).not.toHaveBeenCalled();
expect(shareLabel()).toBe('Partager mes règles');
expect(shareAlert()).toBeNull();
// The recipient: other rules, and the app opened with the link.
component.ruleService.replaceRuleSet([]);
history.replaceState(null, '', share.mock.calls[0][0].url);
TestBed.createComponent(RuleSetImport).detectChanges();
const dialog = () => document.querySelector<HTMLElement>('mat-dialog-container');
await expect.poll(() => dialog()).not.toBeNull();
await fixture.whenStable();
expect(
Array.from(dialog()!.querySelectorAll('.incoming-rule-name'), (name) =>
name.textContent?.trim(),
),
).toEqual(sharedRules.map((rule) => rule.name));
Array.from(dialog()!.querySelectorAll('button'))
.find((action) => action.textContent?.trim() === 'Remplacer mes règles')!
.click();
await expect.poll(() => dialog()).toBeNull();
expect(component.rules).toEqual(sharedRules);
});
it('shows nothing and copies nothing when the share sheet is dismissed', async () => {
stubShare(() => Promise.reject(new DOMException('Share canceled', 'AbortError')));
const writeText = stubClipboard(done);
await ready();
shareButton().click();
await settled();
expect(writeText).not.toHaveBeenCalled();
expect(shareLabel()).toBe('Partager mes règles');
expect(shareAlert()).toBeNull();
});
it('copies the link when the share sheet fails for another reason', async () => {
const share = stubShare(() =>
Promise.reject(new DOMException('Permission denied', 'NotAllowedError')),
);
const writeText = stubClipboard(done);
await ready();
shareButton().click();
await settled();
expect(writeText.mock.calls).toEqual([[share.mock.calls[0][0].url]]);
expect(shareLabel()).toBe('Lien copié');
});
it.each([
['Lien copié', 'succeeds', done],
['Copie impossible', 'fails', () => Promise.reject(new Error('Denied'))],
])(
'copies the link inside the click without a share sheet, and reads "%s" for about two seconds when the copy %s',
async (label, _, outcome) => {
const writeText = stubClipboard(outcome);
const announce = vi
.spyOn(TestBed.inject(LiveAnnouncer), 'announce')
.mockResolvedValue();
await ready();
vi.useFakeTimers();
shareButton().click();
// No await since the click: the copy started inside it.
expect(writeText.mock.calls).toEqual([[link()]]);
await settled();
expect(shareLabel()).toBe(label);
expect(announce).toHaveBeenCalledWith(label);
await vi.advanceTimersByTimeAsync(1900);
fixture.detectChanges();
expect(shareLabel()).toBe(label);
await vi.advanceTimersByTimeAsync(200);
fixture.detectChanges();
expect(shareLabel()).toBe('Partager mes règles');
},
);
it('restarts the two seconds of "Lien copié" on a second copy', async () => {
stubClipboard(done);
await ready();
vi.useFakeTimers();
shareButton().click();
await settled();
await vi.advanceTimersByTimeAsync(1500);
shareButton().click();
await settled();
await vi.advanceTimersByTimeAsync(1900);
fixture.detectChanges();
expect(shareLabel()).toBe('Lien copié');
await vi.advanceTimersByTimeAsync(200);
fixture.detectChanges();
expect(shareLabel()).toBe('Partager mes règles');
});
it('reads "Copie impossible" where there is neither a share sheet nor a clipboard', async () => {
await ready();
shareButton().click();
await settled();
expect(shareLabel()).toBe('Copie impossible');
});
it('names the rule to fix instead of sharing or copying, until the rule set can be shared again', async () => {
const share = stubShare(done);
const writeText = stubClipboard(done);
component.ruleService.addRule(reversedWindow);
fixture.detectChanges();
await ready();
expect(shareAlert()).toBeNull();
shareButton().click();
await settled();
expect(shareAlert()!.textContent!.trim()).toBe(
'Corrigez la règle « Fenêtre inversée » pour partager vos règles.',
);
expect(share).not.toHaveBeenCalled();
expect(writeText).not.toHaveBeenCalled();
// Another edit that leaves the rule as it is keeps the alert.
component.toggleRule(component.rules[0].id);
fixture.detectChanges();
await ready();
expect(shareAlert()).not.toBeNull();
component.ruleService.updateRule({ ...reversedWindow, endDate: new Date(2027, 0, 10) });
fixture.detectChanges();
await ready();
expect(shareAlert()).toBeNull();
shareButton().click();
expect(share).toHaveBeenCalledTimes(1);
});
it('uses the wording of the ticket in every language', () => {
expect(fr.rules.share).toEqual({
action: 'Partager mes règles',
title: 'Mes règles de planification VacOptimizer',
copied: 'Lien copié',
copyFailed: 'Copie impossible',
invalidRule: 'Corrigez la règle « {rule} » pour partager vos règles.',
});
expect(en.rules.share).toEqual({
action: 'Share my rules',
title: 'My VacOptimizer planning rules',
copied: 'Link copied',
copyFailed: 'Copy failed',
invalidRule: 'Fix the rule “{rule}” to share your rules.',
});
expect(de.rules.share).toEqual({
action: 'Meine Regeln teilen',
title: 'Meine VacOptimizer-Planungsregeln',
copied: 'Link kopiert',
copyFailed: 'Kopieren fehlgeschlagen',
invalidRule: 'Korrigieren Sie die Regel „{rule}“, um Ihre Regeln zu teilen.',
});
expect(es.rules.share).toEqual({
action: 'Compartir mis reglas',
title: 'Mis reglas de planificación de VacOptimizer',
copied: 'Enlace copiado',
copyFailed: 'No se pudo copiar',
invalidRule: 'Corrige la regla «{rule}» para compartir tus reglas.',
});
});
});
});
+127 -247
View File
@@ -2,42 +2,24 @@ import {
Component,
ChangeDetectionStrategy,
ChangeDetectorRef,
computed,
DestroyRef,
effect,
inject,
signal,
effect,
} from '@angular/core';
import {
RuleService,
RuleType,
IfThenRule,
TimeWindowRule,
OptimizationRule,
VacationRule,
PlacementStrategy,
} from '../../services/rule-service';
import { RuleService, RuleType, VacationRule } from '../../services/rule-service';
import { encodeRuleSetLink, type RuleSetLink } from '../../services/rule-set-link';
import { SelectableDayType } from '../../services/calendar-service';
import { TranslationService } from '../../services/translation-service';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { FormsModule } from '@angular/forms';
import { NgTemplateOutlet } from '@angular/common';
import { MatDialog } from '@angular/material/dialog';
import { LiveAnnouncer } from '@angular/cdk/a11y';
import {
OPTIMIZATION_CATALOG,
OPTIMIZATION_PRESETS,
validateOptimizationConfiguration,
type OptimizationElements,
type OptimizationMeasure,
} from '../../services/planning-objectives';
import { DateAdapter } from '@angular/material/core';
import { DAY_FIRST_DATE_PROVIDERS } from '../../shared/day-first-date-adapter';
import * as labels from '../../services/planner-labels';
import { RuleDialog, type RuleDialogData } from './rule-dialog';
import { CdkDragDrop, CdkDropList, CdkDrag, CdkDragHandle } from '@angular/cdk/drag-drop';
@Component({
@@ -47,12 +29,6 @@ import { CdkDragDrop, CdkDropList, CdkDrag, CdkDragHandle } from '@angular/cdk/d
MatIconModule,
MatButtonModule,
MatSlideToggleModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
MatDatepickerModule,
FormsModule,
NgTemplateOutlet,
CdkDropList,
CdkDrag,
CdkDragHandle,
@@ -60,12 +36,11 @@ import { CdkDragDrop, CdkDropList, CdkDrag, CdkDragHandle } from '@angular/cdk/d
templateUrl: './rules-panel.html',
styleUrl: './rules-panel.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: DAY_FIRST_DATE_PROVIDERS,
})
export class RulesPanel {
public ruleService = inject(RuleService);
protected readonly translationService = inject(TranslationService);
private readonly dateAdapter = inject(DateAdapter);
private readonly dialog = inject(MatDialog);
private readonly liveAnnouncer = inject(LiveAnnouncer);
private readonly changeDetector = inject(ChangeDetectorRef);
@@ -73,115 +48,80 @@ export class RulesPanel {
return this.translationService.tr;
}
constructor() {
effect(() => {
this.dateAdapter.setLocale(this.translationService.locale());
});
}
protected readonly RuleType = RuleType;
protected readonly placeDayTypes = Object.values(SelectableDayType);
protected readonly rewardDayTypes = Object.values(SelectableDayType).filter(
(t) => t !== SelectableDayType.ANY,
);
protected get forceOptions() {
const preference = {
value: 'preference' as const,
label: () => this.tr().rules.preference,
};
return this.editBuffer.type === RuleType.OPTIMIZATION
? [preference]
: [
{ value: 'obligation' as const, label: () => this.tr().rules.obligation },
preference,
];
}
protected readonly optimizationElements = [
...new Set(OPTIMIZATION_CATALOG.map((row) => row.elements)),
];
protected get optimizationConfiguration() {
return this.editBuffer.type === RuleType.OPTIMIZATION
? this.editBuffer.configuration
: undefined;
}
protected get optimizationMeasures() {
return OPTIMIZATION_CATALOG.filter(
(row) => row.elements === this.optimizationConfiguration?.elements,
);
}
protected get optimizationConditions() {
return (
this.optimizationMeasures.find(
(row) => row.measure === this.optimizationConfiguration?.measure,
)?.conditions ?? []
);
}
protected readonly optimizationAggregations = ['sum', 'count', 'maximum'] as const;
protected readonly optimizationDirections = ['minimize', 'maximize'] as const;
protected validationError = signal('');
public changeOptimizationElements(elements: OptimizationElements) {
this.changeOptimizationMeasure(
OPTIMIZATION_CATALOG.find((row) => row.elements === elements)!.measure,
);
}
public changeOptimizationMeasure(measure: OptimizationMeasure) {
if (this.editBuffer.type !== RuleType.OPTIMIZATION) return;
const row = OPTIMIZATION_CATALOG.find((item) => item.measure === measure)!;
const previous = this.editBuffer.configuration;
const conditions: readonly string[] = row.conditions;
this.editBuffer.configuration = {
elements: row.elements,
conditions:
previous?.conditions.filter((condition) => conditions.includes(condition)) ?? [],
aggregation: previous?.aggregation ?? 'sum',
direction: previous?.direction ?? 'minimize',
...(measure === 'work-sequence-deficit'
? {
measure,
thresholdDays: previous?.measure === measure ? previous.thresholdDays : 5,
}
: { measure }),
};
}
protected get daysOfWeek() {
const tr = this.tr();
return [
{ value: 1, label: tr.rules.daysOfWeek[1] },
{ value: 2, label: tr.rules.daysOfWeek[2] },
{ value: 3, label: tr.rules.daysOfWeek[3] },
{ value: 4, label: tr.rules.daysOfWeek[4] },
{ value: 5, label: tr.rules.daysOfWeek[5] },
{ value: 6, label: tr.rules.daysOfWeek[6] },
{ value: 0, label: tr.rules.daysOfWeek[0] },
];
}
protected get placementOptions(): { value: PlacementStrategy; label: string }[] {
const tr = this.tr();
return [
{ value: 'before', label: tr.rules.placement.before },
{ value: 'after', label: tr.rules.placement.after },
{ value: 'around', label: tr.rules.placement.around },
{ value: 'auto', label: tr.rules.placement.auto },
];
}
protected editingRuleId = signal<string | null>(null);
protected isAddingNew = signal(false);
protected newRuleType = signal<RuleType>(RuleType.IF_THEN);
protected editBuffer: Partial<VacationRule> = {};
public get rules() {
return this.ruleService.rules;
}
protected get activeRuleCount(): number {
return this.rules.filter((rule) => rule.enabled).length;
protected get activeRules(): string {
const tr = this.tr();
return labels.plural(tr, tr.rules.active, this.rules.filter((rule) => rule.enabled).length);
}
/**
* The share link of the current rule set, or the rule that prevents sharing it; null while it
* is computed. It is kept ready because browsers only open the share sheet or write to the
* clipboard inside the click, which awaiting the compression would leave (ADR 0014).
*/
protected readonly shareResult = signal<RuleSetLink | null>(null);
/** What the share button reads for about two seconds after a copy. */
protected readonly copyOutcome = signal<'copied' | 'copyFailed' | null>(null);
private copyTimer?: ReturnType<typeof setTimeout>;
/** The name of the rule to fix, once a share was refused. */
private readonly unshareableRule = signal<string | null>(null);
protected readonly shareAlert = computed(() => {
const name = this.unshareableRule();
// A function, so that a "$" in the rule name stays a "$".
return name === null
? null
: this.tr().rules.share.invalidRule.replace('{rule}', () => name);
});
constructor() {
inject(DestroyRef).onDestroy(() => clearTimeout(this.copyTimer));
effect((onCleanup) => {
const rules = this.rules;
let current = true;
onCleanup(() => (current = false));
this.shareResult.set(null);
void encodeRuleSetLink(rules).then((result) => {
if (!current) return;
this.shareResult.set(result);
// The alert follows the rule set: it names the rule to fix now, and leaves once none is left.
if (this.unshareableRule() !== null)
this.unshareableRule.set('link' in result ? null : result.unshareableRule.name);
});
});
}
protected async share(): Promise<void> {
const result = this.shareResult();
if (!result) return;
if ('unshareableRule' in result) {
this.unshareableRule.set(result.unshareableRule.name);
return;
}
if (navigator.share) {
try {
await navigator.share({ title: this.tr().rules.share.title, url: result.link });
return;
} catch (error) {
// Dismissing the share sheet is a choice; any other failure still leaves the link to paste.
if ((error as Partial<Error> | null)?.name === 'AbortError') return;
}
}
let outcome: 'copied' | 'copyFailed' = 'copied';
try {
// A context without a clipboard throws here, and is a failed copy too.
await navigator.clipboard.writeText(result.link);
} catch {
outcome = 'copyFailed';
}
this.copyOutcome.set(outcome);
void this.liveAnnouncer.announce(this.tr().rules.share[outcome]);
// A second copy restarts the two seconds.
clearTimeout(this.copyTimer);
this.copyTimer = setTimeout(() => this.copyOutcome.set(null), 2000);
}
public drop(event: CdkDragDrop<VacationRule[]>) {
@@ -228,41 +168,27 @@ export class RulesPanel {
public startEdit(rule: VacationRule, event: Event) {
event.stopPropagation();
this.editingRuleId.set(rule.id);
this.isAddingNew.set(false);
this.editBuffer = structuredClone(rule);
this.validationError.set('');
this.openRuleDialog({ rule });
}
public cancelEdit() {
this.editingRuleId.set(null);
this.isAddingNew.set(false);
this.editBuffer = {};
this.validationError.set('');
public startAddNew(type: RuleType) {
this.openRuleDialog({ type });
}
public saveEdit() {
if (!this.editBuffer.name?.trim()) {
this.validationError.set(this.tr().rules.optimization.nameRequired);
return;
}
if (this.editBuffer.type === RuleType.OPTIMIZATION) {
if (!validateOptimizationConfiguration(this.editBuffer.configuration).valid) {
this.validationError.set(this.tr().rules.optimization.invalidConfiguration);
return;
}
this.editBuffer.force = 'preference';
}
if (this.editBuffer.id) {
this.ruleService.updateRule(this.editBuffer as VacationRule);
} else {
this.ruleService.addRule({
...this.editBuffer,
id: crypto.randomUUID(),
enabled: true,
} as VacationRule);
}
this.cancelEdit();
private openRuleDialog(data: RuleDialogData) {
this.dialog
.open<RuleDialog, RuleDialogData, VacationRule>(RuleDialog, {
data,
width: '40rem',
maxWidth: 'calc(100vw - 2rem)',
maxHeight: 'calc(100dvh - 2rem)',
})
.afterClosed()
.subscribe((rule) => {
if (!rule) return;
if ('rule' in data) this.ruleService.updateRule(rule);
else this.ruleService.addRule(rule);
});
}
public deleteRule(id: string, event: Event) {
@@ -270,86 +196,40 @@ export class RulesPanel {
this.ruleService.deleteRule(id);
}
public startAddNew(type: RuleType) {
this.isAddingNew.set(true);
this.editingRuleId.set(null);
this.newRuleType.set(type);
this.validationError.set('');
if (type === RuleType.IF_THEN) {
this.editBuffer = {
name: this.tr().rules.defaultNewRuleName,
type: RuleType.IF_THEN,
force: 'preference',
dayOfWeek: 6,
placeDays: 2,
placeType: SelectableDayType.CP,
placement: 'auto',
rewardDays: 1,
rewardType: SelectableDayType.OTHER,
} as Partial<IfThenRule>;
} else if (type === RuleType.OPTIMIZATION) {
this.editBuffer = {
name: this.tr().rules.optimization.defaultName,
type,
force: 'preference',
configuration: structuredClone(OPTIMIZATION_PRESETS.unplacedAtRisk),
} satisfies Partial<OptimizationRule>;
} else {
this.editBuffer = {
name: this.tr().rules.defaultNewPeriodName,
type: RuleType.TIME_WINDOW,
force: 'preference',
startDate: new Date(),
endDate: new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000),
placeDays: 5,
placeType: SelectableDayType.CP,
} as Partial<TimeWindowRule>;
}
}
protected getDayTypeLabel(type: string | undefined | null): string {
if (!type) return '';
return this.translationService.getDayTypeLabel(type);
}
public getRuleSummary(rule: VacationRule): string {
const tr = this.tr();
if (rule.type === RuleType.OPTIMIZATION)
return this.translationService.optimizationSummary(rule.configuration);
if (rule.type === RuleType.IF_THEN) {
const ifThen = rule as IfThenRule;
const dayLabel = this.daysOfWeek.find((d) => d.value === ifThen.dayOfWeek)?.label ?? '';
const placeTypeLabel = this.getDayTypeLabel(ifThen.placeType);
const placementLabel = (
this.placementOptions.find((p) => p.value === ifThen.placement)?.label ?? ''
)
.trim()
.toLowerCase();
const rewardTypeLabel = this.getDayTypeLabel(ifThen.rewardType);
return tr.rules.ifThenTemplate
.replace('{day}', dayLabel)
.replace('{placeDays}', String(ifThen.placeDays))
.replace('{placeType}', placeTypeLabel)
.replace('{placement}', placementLabel)
.replace('{rewardDays}', String(ifThen.rewardDays))
.replace('{rewardType}', rewardTypeLabel);
} else {
const timeWindow = rule as TimeWindowRule;
const placeTypeLabel = this.getDayTypeLabel(timeWindow.placeType);
const startDateStr = new Date(timeWindow.startDate).toLocaleDateString(
this.translationService.locale(),
);
const endDateStr = new Date(timeWindow.endDate).toLocaleDateString(
this.translationService.locale(),
);
return tr.rules.timeWindowTemplate
.replace('{placeDays}', String(timeWindow.placeDays))
.replace('{placeType}', placeTypeLabel)
.replace('{startDate}', startDateStr)
.replace('{endDate}', endDateStr);
if (rule.type === RuleType.OPTIMIZATION) {
const goal = labels.optimizationGoal(tr, rule.configuration);
return goal ? `${goal}.` : tr.rules.optimization.invalidConfiguration;
}
const locale = this.translationService.locale();
const days = (count: number, type: SelectableDayType) =>
labels
.plural(tr, tr.rules.dayCount, count)
.replace('{type}', tr.rules.summaryTypes[type]);
if (rule.type === RuleType.IF_THEN) {
// 1 January 2023 is a Sunday, the day numbered 0; Intl gives each language its own casing.
const day = new Intl.DateTimeFormat(locale, {
weekday: 'long',
timeZone: 'UTC',
}).format(Date.UTC(2023, 0, 1 + rule.dayOfWeek));
return tr.rules.ifThenTemplate
.replace('{day}', day)
.replace('{placeDays}', days(rule.placeDays, rule.placeType))
.replace('{placement}', tr.rules.summaryPlacement[rule.placement])
.replace(
'{earned}',
rule.rewardDays > 0
? tr.rules.ifThenEarned.replace(
'{earnedDays}',
days(rule.rewardDays, rule.rewardType),
)
: '',
);
}
return tr.rules.timeWindowTemplate
.replace('{placeDays}', days(rule.placeDays, rule.placeType))
.replace('{startDate}', new Date(rule.startDate).toLocaleDateString(locale))
.replace('{endDate}', new Date(rule.endDate).toLocaleDateString(locale));
}
}
@@ -7,38 +7,23 @@ import { RuleService, RuleType } from '../../services/rule-service';
import { TranslationService } from '../../services/translation-service';
import { calculatePlanningInternal } from '../../services/leave-planner.core';
import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives';
import { optimizationSummary } from '../../services/planner-labels';
import {
chooseInDialog,
clickDialogButton,
dialogField,
ruleDialog,
typeInDialog,
} from '../../../testing/rule-dialog';
import { RulesPanel } from './rules-panel';
describe('work-sequence rule editor and reload', () => {
let fixture: ComponentFixture<RulesPanel>;
let component: RulesPanel;
async function choose(label: string, text: string) {
const fields: HTMLElement[] = Array.from(
fixture.nativeElement.querySelectorAll('mat-form-field'),
);
const select = fields
.find((field) => field.querySelector('mat-label')?.textContent?.trim() === label)
?.querySelector<HTMLElement>('mat-select');
if (!select) throw new Error(`Missing select ${label}`);
select.click();
await fixture.whenStable();
const option = Array.from(document.querySelectorAll<HTMLElement>('mat-option')).find(
(candidate) => candidate.textContent?.trim() === text,
);
if (!option) throw new Error(`Missing option ${text}`);
option.click();
await fixture.whenStable();
document.querySelector<HTMLElement>('.cdk-overlay-backdrop')?.click();
await fixture.whenStable();
}
async function setInput(selector: string, value: string) {
const input: HTMLInputElement = fixture.nativeElement.querySelector(selector);
input.value = value;
input.dispatchEvent(new Event('input'));
await fixture.whenStable();
}
const closed = () => expect.poll(() => ruleDialog()).toBeNull();
const choose = (label: string, text: string) => chooseInDialog(fixture, label, text);
const threshold = () => dialogField('Seuil en jours ouvrés').querySelector('input')!;
beforeEach(async () => {
localStorage.clear();
@@ -62,23 +47,20 @@ describe('work-sequence rule editor and reload', () => {
it('creates threshold five, edits it to three, and restores its effect, order and activation after reload', async () => {
component.startAddNew(RuleType.OPTIMIZATION);
await fixture.whenStable();
await setInput('input:not([type="number"])', 'Mes reprises');
await choose('Éléments du planning', 'Séquences de travail');
await choose('Mesure', 'Déficit des séquences de travail');
await choose('Conditions (toutes doivent être vérifiées)', 'Internes');
await choose('Conditions (toutes doivent être vérifiées)', 'Non vides');
const threshold: HTMLInputElement =
fixture.nativeElement.querySelector('input[type="number"]');
expect(threshold.value).toBe('5');
expect(threshold.min).toBe('1');
expect(threshold.step).toBe('1');
expect(fixture.nativeElement.textContent).toContain('Seuil de préférence en jours ouvrés');
component.saveEdit();
await fixture.whenStable();
await typeInDialog(fixture, 'Nom de la règle', 'Mes reprises');
await choose('Éléments du planning', 'Périodes de travail');
await choose('Mesure', 'Jours manquants pour atteindre le seuil');
await choose('Conditions (toutes doivent être vérifiées)', 'Entre deux périodes de repos');
await choose('Conditions (toutes doivent être vérifiées)', 'D’au moins un jour ouvré');
expect(threshold().value).toBe('5');
expect(threshold().min).toBe('1');
expect(threshold().step).toBe('1');
await clickDialogButton(fixture, 'Ajouter');
await closed();
const rule = component.rules[0];
expect(rule).toMatchObject({ configuration: OPTIMIZATION_PRESETS.shortSequenceDeficit });
expect(component.getRuleSummary(rule)).toContain(
'Déficit des séquences de travail (jours ouvrés)',
expect(component.getRuleSummary(rule)).toBe(
'Éviter de reprendre le travail pour moins de 5 jours ouvrés entre deux périodes de repos.',
);
const request = {
horizon: { start: '2024-01-08', end: '2024-01-13' },
@@ -91,11 +73,11 @@ describe('work-sequence rule editor and reload', () => {
});
component.startEdit(rule, new Event('click'));
await fixture.whenStable();
await setInput('input[type="number"]', '3');
component.saveEdit();
await fixture.whenStable();
await typeInDialog(fixture, 'Seuil en jours ouvrés', '3');
await clickDialogButton(fixture, 'Enregistrer');
await closed();
expect(component.getRuleSummary(component.rules[0])).toContain(
'seuil de préférence : 3 jours ouvrés',
'pour moins de 3 jours ouvrés',
);
expect(calculatePlanningInternal({ ...request, rules: component.rules })).toMatchObject({
kind: 'Plan',
@@ -104,11 +86,11 @@ describe('work-sequence rule editor and reload', () => {
component.startAddNew(RuleType.OPTIMIZATION);
await fixture.whenStable();
await setInput('input:not([type="number"])', 'Ma séquence maximale');
await choose('Éléments du planning', 'Séquences de travail');
await choose('Agrégation', 'Maximum');
component.saveEdit();
await fixture.whenStable();
await typeInDialog(fixture, 'Nom de la règle', 'Ma séquence maximale');
await choose('Éléments du planning', 'Périodes de travail');
await choose('Mode de calcul', 'Maximum');
await clickDialogButton(fixture, 'Ajouter');
await closed();
const maximum = component.rules[1];
expect(maximum).toMatchObject({ configuration: OPTIMIZATION_PRESETS.longestWorkSequence });
component.toggleRule(maximum.id);
@@ -139,34 +121,30 @@ describe('work-sequence rule editor and reload', () => {
it('keeps the saved threshold and shows an accessible error for fractional input', async () => {
component.startAddNew(RuleType.OPTIMIZATION);
component.changeOptimizationMeasure('work-sequence-deficit');
await fixture.whenStable();
await setInput('input[type="number"]', '1.5');
component.saveEdit();
await fixture.whenStable();
await choose('Éléments du planning', 'Périodes de travail');
await choose('Mesure', 'Jours manquants pour atteindre le seuil');
await typeInDialog(fixture, 'Seuil en jours ouvrés', '1.5');
await clickDialogButton(fixture, 'Ajouter');
expect(component.rules).toEqual([]);
expect(fixture.nativeElement.querySelector('[role="alert"]').textContent).toContain(
'seuil entier positif',
expect(ruleDialog()!.querySelector('[role="alert"]')!.textContent).toContain(
'doit être un entier positif',
);
expect(fixture.nativeElement.querySelector('input[type="number"]').value).toBe('1.5');
expect(threshold().value).toBe('1.5');
});
it('distinguishes aggregation units from the working-day threshold', () => {
const translations = TestBed.inject(TranslationService);
expect(
translations.optimizationSummary(OPTIMIZATION_PRESETS.longestWorkSequence),
).toContain('Longueur des séquences de travail (jours ouvrés)');
expect(
translations.optimizationSummary({
...OPTIMIZATION_PRESETS.shortSequenceDeficit,
aggregation: 'count',
}),
).toContain('Déficit des séquences de travail (Nombre)');
expect(
translations.optimizationSummary({
...OPTIMIZATION_PRESETS.shortSequenceDeficit,
aggregation: 'count',
}),
).toContain('seuil de préférence : 5 jours ouvrés');
const tr = TestBed.inject(TranslationService).tr();
expect(optimizationSummary(tr, OPTIMIZATION_PRESETS.longestWorkSequence)).toContain(
'Jours travaillés d’affilée (jours ouvrés)',
);
const count = {
...OPTIMIZATION_PRESETS.shortSequenceDeficit,
aggregation: 'count' as const,
};
expect(optimizationSummary(tr, count)).toContain(
'Jours manquants pour atteindre le seuil (Nombre)',
);
expect(optimizationSummary(tr, count)).toContain('seuil : 5 jours ouvrés');
});
});
@@ -0,0 +1,31 @@
<p class="help">{{ tr().planning.timeOffPeriods.help }}</p>
<ul class="periods">
@for (row of rows(); track row.start) {
<li>
<button
type="button"
[attr.data-start]="row.start"
(click)="dateChosen.emit(row.firstDate)"
>
<span class="range">{{ range(row) }}</span>
<span class="counts">
@for (leave of row.leave; track leave.type) {
<span class="count">
<span class="swatch" [class]="leave.type" aria-hidden="true"></span>
{{ typeLabel(leave.type) }} : <strong>{{ leave.days }}</strong>
</span>
}
@if (row.declared) {
<span class="count">
<span class="swatch declared" aria-hidden="true"></span>
{{ tr().bookedDays.booked }} : <strong>{{ row.declared }}</strong>
</span>
}
</span>
<span class="duration">
<strong>{{ row.duration }}</strong> {{ daysOff(row.duration) }}
</span>
</button>
</li>
}
</ul>
@@ -0,0 +1,99 @@
:host {
display: block;
min-width: 0;
}
.help {
margin: 0;
padding: 0.75rem 1rem 0;
color: var(--ui-text-secondary);
font-size: 0.875rem;
}
// A long plan scrolls here instead of pushing the calendar down.
.periods {
max-height: min(22rem, 60dvh);
margin: 0;
padding: 0.5rem;
overflow-y: auto;
list-style: none;
}
li + li {
border-top: 1px solid var(--ui-border);
}
button {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.375rem 1rem;
width: 100%;
min-height: 2.75rem;
padding: 0.5rem 0.75rem;
border: 0;
border-radius: var(--ui-radius-sm);
background: transparent;
color: inherit;
font: inherit;
text-align: start;
cursor: pointer;
transition: background-color 150ms ease;
&:hover {
background: var(--ui-panel-bg);
}
}
.range {
flex: 1 1 11rem;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.counts {
display: flex;
flex-wrap: wrap;
gap: 0.375rem 0.75rem;
font-size: 0.8125rem;
}
.count {
display: inline-flex;
align-items: center;
gap: 0.375rem;
color: var(--ui-text-secondary);
strong {
color: var(--mat-sys-on-surface);
font-variant-numeric: tabular-nums;
}
}
.duration {
flex: 0 0 auto;
min-width: 9rem;
color: var(--ui-text-secondary);
font-size: 0.8125rem;
text-align: end;
strong {
color: var(--mat-sys-on-surface);
font-size: 1rem;
font-variant-numeric: tabular-nums;
}
}
.swatch {
flex-shrink: 0;
width: 1rem;
height: 1rem;
border-radius: 0.25rem;
&.cp {
background: var(--cp-bg);
}
&.rtt {
background: var(--rtt-bg);
}
&.other {
background: var(--other-bg);
}
&.declared {
background-image: var(--declared-day-pattern);
border: 1px solid var(--ui-border);
}
}
@@ -0,0 +1,132 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import type { LeavePlacement, PlanOutcome } from '../../services/leave-planner.service';
import { TranslationService } from '../../services/translation-service';
import { TimeOffPeriods, timeOffPeriodRows } from './time-off-periods';
const placement = (date: string, type: LeavePlacement['type']): LeavePlacement => ({
date,
balanceId: type,
type,
ruleIds: [],
supporting: false,
});
// Deliberately out of order, with a plain public-holiday weekend between the two listed periods.
const plan: Pick<PlanOutcome, 'placements' | 'timeOffPeriods'> = {
placements: [
placement('2024-05-06', 'rtt'),
placement('2024-05-07', 'cp'),
placement('2024-05-03', 'cp'),
placement('2024-05-08', 'cp'),
],
timeOffPeriods: [
{
start: '2024-05-04',
end: '2024-05-12',
duration: 9,
placementDates: ['2024-05-06', '2024-05-07', '2024-05-08'],
nonWorkingDates: ['2024-05-04', '2024-05-05', '2024-05-09', '2024-05-10'],
nonWorkingDayGain: 4,
},
{
start: '2024-05-25',
end: '2024-05-26',
duration: 2,
placementDates: [],
nonWorkingDates: ['2024-05-25', '2024-05-26'],
nonWorkingDayGain: 2,
},
{
start: '2024-05-01',
end: '2024-05-05',
duration: 5,
placementDates: ['2024-05-03'],
declaredDates: ['2024-05-02'],
nonWorkingDates: ['2024-05-01', '2024-05-04', '2024-05-05'],
nonWorkingDayGain: 3,
},
],
};
describe('timeOffPeriodRows', () => {
it('lists chronologically the periods with leave or a declared day, with their leave by type', () => {
expect(timeOffPeriodRows(plan)).toEqual([
{
start: '2024-05-01',
end: '2024-05-05',
duration: 5,
leave: [{ type: 'cp', days: 1 }],
declared: 1,
firstDate: '2024-05-02',
},
{
start: '2024-05-04',
end: '2024-05-12',
duration: 9,
leave: [
{ type: 'cp', days: 2 },
{ type: 'rtt', days: 1 },
],
declared: 0,
firstDate: '2024-05-06',
},
]);
});
it('lists nothing for a plan without leave', () => {
expect(
timeOffPeriodRows({ placements: [], timeOffPeriods: [plan.timeOffPeriods[1]] }),
).toEqual([]);
});
});
describe('TimeOffPeriods', () => {
async function render(language: string) {
await TestBed.configureTestingModule({
imports: [TimeOffPeriods],
providers: [provideZonelessChangeDetection()],
}).compileComponents();
TestBed.inject(TranslationService).setLanguage(language);
const fixture = TestBed.createComponent(TimeOffPeriods);
fixture.componentRef.setInput('plan', plan);
fixture.detectChanges();
return { fixture, root: fixture.nativeElement as HTMLElement };
}
const text = (element: Element) => element.textContent?.replace(/\s+/g, ' ').trim();
it('shows the range, the leave days per type, the declared days and the duration of each period', async () => {
const { root } = await render('en');
const buttons = [...root.querySelectorAll<HTMLButtonElement>('li > button')];
expect(buttons.map((button) => button.dataset['start'])).toEqual([
'2024-05-01',
'2024-05-04',
]);
const range = (start: string, end: string) =>
new Intl.DateTimeFormat(TestBed.inject(TranslationService).locale(), {
dateStyle: 'medium',
timeZone: 'UTC',
}).formatRange(new Date(start), new Date(end));
expect(text(buttons[0])).toBe(
`${range('2024-05-01', '2024-05-05')} Paid leave : 1 Already booked : 1 5 days off in a row`,
);
expect(text(buttons[1])).toBe(
`${range('2024-05-04', '2024-05-12')} Paid leave : 2 RTT : 1 9 days off in a row`,
);
expect(buttons[1].querySelector('.swatch.rtt')).not.toBeNull();
});
it('shows dates in the active locale', async () => {
const { root } = await render('de');
expect(root.querySelector('.range')?.textContent).toContain('01.–05.05.2024');
});
it('chooses the first leave placement or declared day of a period', async () => {
const { fixture, root } = await render('en');
const chosen: string[] = [];
fixture.componentInstance.dateChosen.subscribe((date) => chosen.push(date));
for (const button of root.querySelectorAll<HTMLButtonElement>('li > button'))
button.click();
expect(chosen).toEqual(['2024-05-02', '2024-05-06']);
});
});
@@ -0,0 +1,77 @@
import { ChangeDetectionStrategy, Component, computed, inject, input, output } from '@angular/core';
import type { LeaveType, PlanOutcome, TimeOffPeriod } from '../../services/leave-planner.service';
import { plural } from '../../services/planner-labels';
import { TranslationService } from '../../services/translation-service';
const LEAVE_TYPES: readonly LeaveType[] = ['cp', 'rtt', 'other'];
export interface TimeOffPeriodRow extends Pick<TimeOffPeriod, 'start' | 'end' | 'duration'> {
/** Leave days to place in the period, by leave type; types without a day are left out. */
leave: readonly { type: LeaveType; days: number }[];
declared: number;
/** The first leave placement or declared non-working day of the period. */
firstDate: string;
}
/** The periods of a plan worth reading dates from, in chronological order: those with leave or a declared day. */
export function timeOffPeriodRows(
plan: Pick<PlanOutcome, 'placements' | 'timeOffPeriods'>,
): TimeOffPeriodRow[] {
const typeOf = new Map(plan.placements.map(({ date, type }) => [date, type]));
return plan.timeOffPeriods
.filter(
({ placementDates, declaredDates }) => placementDates.length || declaredDates?.length,
)
.map(({ start, end, duration, placementDates, declaredDates = [] }) => ({
start,
end,
duration,
leave: LEAVE_TYPES.map((type) => ({
type,
days: placementDates.filter((date) => typeOf.get(date) === type).length,
})).filter(({ days }) => days),
declared: declaredDates.length,
firstDate: [...placementDates, ...declaredDates].sort()[0],
}))
.sort((a, b) => a.start.localeCompare(b.start));
}
/** The time-off periods of a plan, each a button that asks for its first leave day to be shown. */
@Component({
selector: 'app-time-off-periods',
templateUrl: './time-off-periods.html',
styleUrl: './time-off-periods.scss',
// A button's name is read from its content: keep the spaces between its parts.
preserveWhitespaces: true,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TimeOffPeriods {
readonly plan = input.required<Pick<PlanOutcome, 'placements' | 'timeOffPeriods'>>();
/** The first leave placement or declared day of the chosen period. */
readonly dateChosen = output<string>();
private readonly translationService = inject(TranslationService);
protected readonly rows = computed(() => timeOffPeriodRows(this.plan()));
private readonly dateFormat = computed(
() =>
new Intl.DateTimeFormat(this.translationService.locale(), {
dateStyle: 'medium',
timeZone: 'UTC',
}),
);
get tr() {
return this.translationService.tr;
}
protected range({ start, end }: TimeOffPeriodRow): string {
return this.dateFormat().formatRange(new Date(start), new Date(end));
}
protected daysOff(duration: number): string {
return plural(this.tr(), this.tr().planning.explanation.daysOff, duration);
}
protected typeLabel(type: LeaveType): string {
return this.translationService.getDayTypeLabel(type);
}
}
+13 -66
View File
@@ -2,9 +2,6 @@
<header class="section-heading">
<h2 id="leave-settings-title">{{ tr().userInput.title }}</h2>
<p>{{ tr().userInput.description }}</p>
<a class="jump-to-plan" href="#planning-results-title"
>{{ tr().app.skipToPlan }} <mat-icon aria-hidden="true">arrow_downward</mat-icon></a
>
</header>
<fieldset class="planning-dates">
@@ -62,6 +59,12 @@
</fieldset>
<div class="listOfDays">
@if (!daysOff.length) {
<p id="leave-balances-empty" class="empty-balances">
<mat-icon aria-hidden="true">event_available</mat-icon>
{{ tr().userInput.emptyBalances }}
</p>
}
@for (day of daysOff; track day.id) {
<div class="day-input-wrapper" animate.enter="day-enter" animate.leave="day-leave">
<app-day-input
@@ -75,73 +78,17 @@
<mat-icon aria-hidden="true">add</mat-icon>
{{ tr().userInput.addVacationDay }}
</button>
<div class="declaration-controls" [class.is-active]="declarationEntry()">
<button
mat-button
type="button"
class="declaration-entry-toggle"
[attr.aria-pressed]="declarationEntry()"
(click)="declarationEntry.set(!declarationEntry())"
>
<mat-icon aria-hidden="true">{{
declarationEntry() ? 'check_circle' : 'edit_calendar'
}}</mat-icon>
{{ tr().bookedDays.enter }}
</button>
@if (declarationEntry()) {
<div class="declaration-types" role="group" [attr.aria-label]="tr().userInput.type">
@for (type of declaredTypes; track type) {
<button
mat-stroked-button
type="button"
[attr.data-declared-type]="type"
[attr.aria-pressed]="declaredType() === type"
(click)="declaredType.set(type)"
>
<mat-icon class="declaration-type-check" aria-hidden="true"
>check</mat-icon
>
{{ type === 'cp' ? 'CP' : translationService.getDayTypeLabel(type) }}
</button>
}
<button
mat-stroked-button
type="button"
data-declaration-erase
[attr.aria-pressed]="declaredType() === null"
(click)="declaredType.set(null)"
>
<mat-icon aria-hidden="true">{{
declaredType() === null ? 'check' : 'backspace'
}}</mat-icon>
{{ tr().bookedDays.erase }}
</button>
</div>
}
</div>
<app-declaration-controls></app-declaration-controls>
</div>
<app-rules-panel></app-rules-panel>
@if (duration.estimate()) {
<p id="planning-duration-estimate" class="duration-estimate">{{ durationLabel() }}</p>
}
<button
mat-flat-button
class="calculate-button"
color="primary"
type="button"
[disabled]="!!calendarSettings.planningHorizonError()"
[attr.aria-describedby]="
calendarSettings.planningHorizonError()
? 'planning-dates-error'
: 'planning-duration-estimate'
"
(click)="triggerComputation()"
>
<mat-icon aria-hidden="true">auto_awesome</mat-icon>
{{ tr().userInput.calculate }}
</button>
<div class="calculate-bar">
@if (duration.estimate() && !nothingToPlan()) {
<p id="planning-duration-estimate" class="duration-estimate">{{ durationLabel() }}</p>
}
<app-calculate-button></app-calculate-button>
</div>
@if (hasRemainingDays()) {
<mat-card class="warning-card" [class.is-informational]="!hasAtRiskDays()">
+34 -95
View File
@@ -72,72 +72,22 @@
gap: 0.75rem;
}
.declaration-controls {
display: grid;
container: declaration-controls / inline-size;
.empty-balances {
display: flex;
align-items: flex-start;
gap: 0.75rem;
grid-column: 1 / -1;
margin: 0;
padding: 1rem;
border: 1px solid var(--ui-border);
border-radius: var(--ui-radius-sm);
background: var(--ui-panel-bg);
&.is-active {
border-color: var(--mat-sys-primary);
}
}
.declaration-entry-toggle {
justify-content: flex-start;
width: 100%;
height: auto;
min-height: 3.25rem;
padding: 0.75rem 1rem;
border-radius: calc(var(--ui-radius-sm) - 1px);
text-align: start;
font-size: 0.875rem;
line-height: 1.5;
transition:
background-color 150ms ease-out,
color 150ms ease-out;
&[aria-pressed='true'] {
background: var(--mat-sys-primary-container);
color: var(--mat-sys-on-primary-container);
}
}
.declaration-types {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 0.5rem;
padding: 0.75rem;
button {
min-height: 2.75rem;
height: auto;
padding: 0.5rem;
border-radius: calc(var(--ui-radius-sm) - 1px);
background-color: var(--ui-card-bg);
color: var(--number-color);
line-height: 1.5;
&[data-declared-type='cp'] {
background-color: var(--cp-bg);
}
&[data-declared-type='rtt'] {
background-color: var(--rtt-bg);
}
&[data-declared-type='other'] {
background-color: var(--other-bg);
}
&[aria-pressed='true'] {
border-color: currentColor;
box-shadow: inset 0 0 0 1px currentColor;
}
&[data-declared-type][aria-pressed='true'] {
background-image: var(--declared-day-pattern);
}
&[aria-pressed='false'] .declaration-type-check {
visibility: hidden;
}
mat-icon {
flex-shrink: 0;
color: var(--mat-sys-primary);
}
}
@@ -178,15 +128,18 @@ form {
flex-direction: column;
}
.add-day-button,
.calculate-button {
.add-day-button {
width: 100%;
min-height: 3rem;
}
// Below 75rem, Calculate is in the app's bottom bar instead.
.calculate-bar {
display: none;
}
.duration-estimate {
grid-column: 1 / -1;
margin: 0 0 -0.5rem;
margin: 0;
color: var(--ui-text-secondary);
font-size: 0.875rem;
line-height: 1.5;
@@ -200,12 +153,6 @@ form {
border-radius: var(--ui-radius-sm);
}
.calculate-button {
min-height: 3.25rem;
border-radius: var(--ui-radius-sm);
font-weight: 600;
}
.warning-card {
background: var(--ui-warning-bg, #fff4d6);
color: var(--ui-warning-text, #4f3800);
@@ -252,18 +199,6 @@ form {
max-width: 100%;
}
@container declaration-controls (min-width: 18rem) {
.declaration-types {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@container declaration-controls (min-width: 34rem) {
.declaration-types {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
}
@container user-input (min-width: 40rem) {
.planning-dates {
grid-template-columns: repeat(2, minmax(0, 1fr));
@@ -283,7 +218,6 @@ form {
column-gap: 1.5rem;
}
.section-heading,
.calculate-button,
.warning-card {
grid-column: 1 / -1;
}
@@ -292,18 +226,23 @@ form {
}
}
.jump-to-plan {
display: inline-flex;
align-items: center;
gap: 0.5rem;
width: fit-content;
min-height: 2.75rem;
color: var(--mat-sys-primary);
font-size: 0.875rem;
text-underline-offset: 0.25em;
}
@media (min-width: 75rem) {
.jump-to-plan {
display: none;
// The configuration panel scrolls here: keep Calculate and its indicative wait in view.
// A flex column instead of the grid, so that the sticky bar spans the whole content.
.user-input {
display: flex;
flex-direction: column;
align-items: stretch;
}
.calculate-bar {
display: grid;
gap: 0.5rem;
position: sticky;
bottom: calc(-1 * var(--panel-padding));
z-index: 1;
margin-inline: calc(-1 * var(--panel-padding));
padding: 0.75rem var(--panel-padding);
background: var(--ui-card-bg);
border-block-start: 1px solid var(--ui-border);
}
}
@@ -10,6 +10,8 @@ import { MatSlideToggleHarness } from '@angular/material/slide-toggle/testing';
import { type MockInstance, vi } from '../../../testing/vitest-compat';
import { createInProcessCalculation } from '../../../testing/planning-jobs';
import { UserInput } from './user-input';
import { CalculateButton } from '../calculate-button/calculate-button';
import { By } from '@angular/platform-browser';
import { UserInputService } from '../../services/user-input-service';
import { PlanningCalculationService } from '../../services/planning-calculation.service';
import { UserSettings } from '../user-settings/user-settings';
@@ -23,6 +25,16 @@ import { TranslationService } from '../../services/translation-service';
const presets = createOptimizationPresetRules();
const savedBalances = JSON.stringify(
(['cp', 'rtt', 'other'] as const).map((type, index) => ({
id: `00000000-0000-4000-8000-00000000000${index + 1}`,
type,
numberOfDays: 15,
availableDate: '2026-10-04',
expiryDate: '2027-10-04',
})),
);
describe('UserInput', () => {
let component: UserInput;
let fixture: ComponentFixture<UserInput>;
@@ -35,12 +47,8 @@ describe('UserInput', () => {
localStorage.setItem('app.language', '"en"');
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date(2026, 9, 4, 12));
vi.spyOn(Math, 'random').mockReturnValue(0.5);
vi.spyOn(crypto, 'randomUUID')
.mockReturnValueOnce('00000000-0000-4000-8000-000000000001')
.mockReturnValueOnce('00000000-0000-4000-8000-000000000002')
.mockReturnValueOnce('00000000-0000-4000-8000-000000000003')
.mockReturnValueOnce('00000000-0000-4000-8000-000000000004');
localStorage.setItem('leaveBalances', savedBalances);
vi.spyOn(crypto, 'randomUUID').mockReturnValueOnce('00000000-0000-4000-8000-000000000004');
await createInput();
});
@@ -62,6 +70,11 @@ describe('UserInput', () => {
await fixture.whenStable();
}
/** Calculate's own guard, as if the disabled button were activated anyway. */
function calculateDirectly(): void {
fixture.debugElement.query(By.directive(CalculateButton)).componentInstance.calculate();
}
async function revisit(): Promise<void> {
fixture.destroy();
TestBed.resetTestingModule();
@@ -136,8 +149,8 @@ describe('UserInput', () => {
const root = fixture.nativeElement as HTMLElement;
const card = root.querySelector<HTMLElement>('.warning-card')!;
expect(card.textContent).toContain('Disponible seulement à partir du 10 mai 2027');
expect(card.textContent).toContain('la dernière date du planning, le 9 mai 2027');
expect(card.textContent).toContain('prolonger la période planifiée');
expect(card.textContent).toContain('après la fin de la période planifiée (9 mai 2027)');
expect(card.textContent).toContain('prolongez la période à planifier');
expect(card.textContent).not.toContain('manuellement');
const explanation = card.textContent;
TestBed.inject(CalendarSettingsService).setPlanningDates('2027-01-01', '2028-12-31');
@@ -192,8 +205,8 @@ describe('UserInput', () => {
const root = fixture.nativeElement as HTMLElement;
const card = root.querySelector<HTMLElement>('.warning-card')!;
expect(card.classList.contains('is-informational')).toBe(true);
expect(card.textContent).toContain('Conservé pour plus tard');
expect(card.textContent).toContain('Aucune action nécessaire');
expect(card.textContent).toContain('Gardé pour plus tard');
expect(card.textContent).toContain('Rien à faire');
expect(card.textContent).not.toContain('Disponible seulement');
expect(root.querySelector('.remaining-history')).toBeNull();
const outcome = JSON.stringify(calculations.outcome());
@@ -208,8 +221,8 @@ describe('UserInput', () => {
completedStages: [],
reasons: [{ code: 'user-cancelled', message: 'Cancelled' }],
});
expect(card.textContent).toContain('Sa non-utilisation n’est pas une décision définitive');
expect(card.textContent).not.toContain('Conservé pour plus tard');
expect(card.textContent).toContain('ces jours auraient peut-être été posés');
expect(card.textContent).not.toContain('Gardé pour plus tard');
expect(root.querySelector('.remaining-history')).toBeNull();
expect(card.querySelector('details')).toBeNull();
});
@@ -219,8 +232,12 @@ describe('UserInput', () => {
const calculate = root.querySelector<HTMLButtonElement>('.calculate-button')!;
const estimateText = () =>
root.querySelector('#planning-duration-estimate')?.textContent?.trim();
expect(estimateText()).toMatch(/Approximate wait: \d+–\d+ (s|min)/);
expect(estimateText()).toMatch(/Estimated calculation time: \d+–\d+ (s|min)/);
expect(calculate.getAttribute('aria-describedby')).toBe('planning-duration-estimate');
// One bar, so that the wide layout pins the wait and the action together.
const bar = root.querySelector('.calculate-bar');
expect(bar?.contains(calculate)).toBe(true);
expect(root.querySelector('#planning-duration-estimate')?.parentElement).toBe(bar);
const initial = estimateText();
TestBed.inject(CalendarSettingsService).setPlanningDates('2026-10-04', '2029-10-03');
fixture.detectChanges();
@@ -269,10 +286,12 @@ describe('UserInput', () => {
const root = fixture.nativeElement as HTMLElement;
const calculate = root.querySelector<HTMLButtonElement>('.calculate-button')!;
expect(calculate.disabled).toBe(true);
expect(root.querySelector('#planning-dates-error')?.textContent).toContain('on or after');
expect(root.querySelector('#planning-dates-error')?.textContent).toContain(
'cannot be before the start date',
);
expect(calculate.getAttribute('aria-describedby')).toBe('planning-dates-error');
calculate.click();
component.triggerComputation();
calculateDirectly();
expect(createCalculation).not.toHaveBeenCalled();
editInput('input[name="planningStart"]', '29/02/2024');
expect(calculate.disabled).toBe(false);
@@ -293,7 +312,7 @@ describe('UserInput', () => {
);
expect(
fixture.nativeElement.querySelector('#planning-dates-error')?.textContent,
).toContain('two valid calendar dates');
).toContain('two valid dates');
expect(settings.planningHorizon()).toBeNull();
expect(JSON.parse(localStorage.getItem('calendarSettings.planningDates')!)).toEqual({
start: '2024-02-29',
@@ -311,9 +330,11 @@ describe('UserInput', () => {
const last = root.querySelector<HTMLInputElement>('input[name="lastPlanningDate"]')!;
expect(start.value).toBe('29/02/2024');
expect(last.value).toBe('28/02/2027');
expect(root.textContent).toContain('Last planning date (inclusive)');
expect(root.textContent).toContain('End date (inclusive)');
editInput('input[name="lastPlanningDate"]', '28/02/2024');
expect(root.querySelector('#planning-dates-error')?.textContent).toContain('on or after');
expect(root.querySelector('#planning-dates-error')?.textContent).toContain(
'cannot be before the start date',
);
expect(last.getAttribute('aria-invalid')).toBe('true');
expect(last.getAttribute('aria-describedby')).toContain('planning-dates-error');
expect(settings.planningHorizon()).toBeNull();
@@ -375,7 +396,7 @@ describe('UserInput', () => {
);
expect(await Promise.all(types.map((type) => type.getValueText()))).toEqual([
'RTT',
'Paid Leave',
'Paid leave',
]);
expect(userInputService.vacationNumberSignal().map((balance) => balance.id)).toEqual([
'rtt-first',
@@ -394,28 +415,42 @@ describe('UserInput', () => {
it.each([
['absent', null],
['unreadable', '{'],
])('renders unsaved random defaults when balance data is %s', async (_, saved) => {
])('shows the empty state and disables Calculate when balance data is %s', async (_, saved) => {
vi.spyOn(console, 'warn').mockImplementation(() => {});
if (saved !== null) localStorage.setItem('leaveBalances', saved);
if (saved === null) localStorage.removeItem('leaveBalances');
else localStorage.setItem('leaveBalances', saved);
await revisit();
const root = fixture.nativeElement as HTMLElement;
expect(
Array.from(root.querySelectorAll<HTMLInputElement>('app-day-input input')).map(
(input) => input.value,
),
).toEqual([
'15',
'04/10/2026',
'04/10/2027',
'15',
'04/10/2026',
'04/10/2027',
'15',
'04/10/2026',
'04/10/2027',
]);
expect(root.querySelector('app-day-input')).toBeNull();
expect(root.querySelector('#leave-balances-empty')?.textContent).toContain(
'No leave balance yet',
);
const calculate = root.querySelector<HTMLButtonElement>('.calculate-button')!;
expect(calculate.disabled).toBe(true);
expect(calculate.getAttribute('aria-describedby')).toBe('leave-balances-empty');
expect(root.querySelector('#planning-duration-estimate')).toBeNull();
calculateDirectly();
expect(createCalculation).not.toHaveBeenCalled();
expect(localStorage.getItem('leaveBalances')).toBeNull();
expect(localStorage.getItem('app.language')).toBe('"en"');
root.querySelector<HTMLButtonElement>('.add-day-button')!.click();
fixture.detectChanges();
expect(root.querySelectorAll('app-day-input')).toHaveLength(1);
expect(root.querySelector('#leave-balances-empty')).toBeNull();
expect(calculate.disabled).toBe(false);
expect(calculate.getAttribute('aria-describedby')).toBe('planning-duration-estimate');
});
it('explains both reasons when the planning dates are invalid and there is nothing to plan', async () => {
localStorage.setItem('leaveBalances', '[]');
await revisit();
editInput('input[name="lastPlanningDate"]', '');
const calculate = fixture.nativeElement.querySelector('.calculate-button');
expect(calculate.disabled).toBe(true);
expect(calculate.getAttribute('aria-describedby')).toBe(
'planning-dates-error leave-balances-empty',
);
});
it('restores the complete edited list on a fresh visit', async () => {
@@ -431,8 +466,8 @@ describe('UserInput', () => {
expect(localStorage.getItem('leaveBalances')).toBe(saved);
});
it('saves the complete ordered balance list on the first quantity edit', () => {
expect(localStorage.getItem('leaveBalances')).toBeNull();
it('saves the complete ordered balance list on a quantity edit', () => {
expect(localStorage.getItem('leaveBalances')).toBe(savedBalances);
editInput('app-day-input input[type="number"]', '7');
expect(JSON.parse(localStorage.getItem('leaveBalances')!)).toEqual([
@@ -460,7 +495,7 @@ describe('UserInput', () => {
]);
});
it('saves a leave-type selection as the first balance edit', async () => {
it('saves a leave-type selection as a balance edit', async () => {
const loader = TestbedHarnessEnvironment.loader(fixture);
const type = await loader.getHarness(
MatSelectHarness.with({ selector: 'app-day-input mat-select' }),
@@ -492,7 +527,7 @@ describe('UserInput', () => {
]);
});
it('saves adding a balance as the first edit and keeps saving subsequent edits', () => {
it('saves adding a balance and keeps saving subsequent edits', () => {
fixture.nativeElement.querySelector('.add-day-button').click();
fixture.detectChanges();
@@ -515,7 +550,7 @@ describe('UserInput', () => {
expect(JSON.parse(localStorage.getItem('leaveBalances')!)[0].numberOfDays).toBe(9);
});
it('saves removing a balance as the first edit and retains an entry after the final deletion', () => {
it('saves removing a balance and retains an empty list after the final deletion', () => {
fixture.nativeElement.querySelectorAll('.delete-button')[2].click();
fixture.detectChanges();
expect(JSON.parse(localStorage.getItem('leaveBalances')!)).toMatchObject([
@@ -530,15 +565,16 @@ describe('UserInput', () => {
fixture.detectChanges();
expect(userInputService.vacationNumberSignal()).toEqual([]);
expect(localStorage.getItem('leaveBalances')).toBe('[]');
expect(fixture.nativeElement.querySelector('#leave-balances-empty')).not.toBeNull();
expect(fixture.nativeElement.querySelector('.calculate-button').disabled).toBe(true);
});
it('keeps untouched random balances unsaved through settings, rule changes, and calculation', async () => {
it('does not rewrite restored balances through settings, rule changes, and calculation', async () => {
const initialBalances = userInputService.vacationNumberSignal();
expect(localStorage.getItem('leaveBalances')).toBeNull();
const write = vi.spyOn(Storage.prototype, 'setItem');
const loader = TestbedHarnessEnvironment.documentRootLoader(fixture);
const dialogRef = TestBed.inject(MatDialog).open(UserSettings);
const dialog = await loader.getHarness(MatDialogHarness);
expect(localStorage.getItem('leaveBalances')).toBeNull();
const [theme, language] = await dialog.getAllHarnesses(MatSelectHarness);
await selectOption(theme, 'Dark');
@@ -560,7 +596,8 @@ describe('UserInput', () => {
expect(createCalculation).toHaveBeenCalledTimes(1);
expect(userInputService.vacationNumberSignal()).toEqual(initialBalances);
expect(localStorage.getItem('leaveBalances')).toBeNull();
expect(write.mock.calls.some(([key]) => key === 'leaveBalances')).toBe(false);
expect(localStorage.getItem('leaveBalances')).toBe(savedBalances);
});
it('preserves unrelated stored preferences, rules, and other values when editing balances', () => {
@@ -589,7 +626,7 @@ describe('UserInput', () => {
editInput('app-day-input input[type="number"]', '7');
expect(userInputService.vacationNumberSignal()[0].numberOfDays).toBe(7);
expect(localStorage.getItem('leaveBalances')).toBeNull();
expect(localStorage.getItem('leaveBalances')).toBe(savedBalances);
write.mockRestore();
editInput('app-day-input input[type="number"]', '8');
+5 -9
View File
@@ -11,13 +11,14 @@ import { MatCard, MatCardContent } from '@angular/material/card';
import { MatIcon } from '@angular/material/icon';
import { DayInput } from '../userInput/day-input/day-input';
import { MatButtonModule } from '@angular/material/button';
import type { LeaveType } from '../../services/leave-planner.service';
import { TranslationService } from '../../services/translation-service';
import { CalendarSettingsService } from '../../services/calendar-settings-service';
import { PlanningCalculationService } from '../../services/planning-calculation.service';
import { PlanningDurationService } from '../../services/planning-duration.service';
import { addPlanningDays, isPlanningDate } from '../../services/planning-date';
import { DAY_FIRST_DATE_PROVIDERS } from '../../shared/day-first-date-adapter';
import { DeclarationControls } from '../declaration-controls/declaration-controls';
import { CalculateButton } from '../calculate-button/calculate-button';
@Component({
selector: 'app-user-input',
@@ -32,6 +33,8 @@ import { DAY_FIRST_DATE_PROVIDERS } from '../../shared/day-first-date-adapter';
MatIcon,
MatButtonModule,
DayInput,
DeclarationControls,
CalculateButton,
],
templateUrl: './user-input.html',
styleUrl: './user-input.scss',
@@ -40,9 +43,7 @@ import { DAY_FIRST_DATE_PROVIDERS } from '../../shared/day-first-date-adapter';
})
export class UserInput {
private userInputService: UserInputService = inject(UserInputService);
protected readonly declarationEntry = this.userInputService.declarationEntrySignal;
protected readonly declaredType = this.userInputService.declaredTypeSignal;
protected readonly declaredTypes: readonly LeaveType[] = ['cp', 'rtt', 'other'];
protected readonly nothingToPlan = this.userInputService.nothingToPlan;
protected readonly calendarSettings = inject(CalendarSettingsService);
protected readonly duration = inject(PlanningDurationService);
private readonly calculations = inject(PlanningCalculationService);
@@ -172,9 +173,4 @@ export class UserInput {
days.map((day, i) => (i === index ? updatedDay : day)),
);
}
public triggerComputation() {
if (this.calendarSettings.planningHorizonError()) return;
this.calculations.start();
}
}
+23
View File
@@ -18,6 +18,7 @@ import {
weekday,
type Req,
} from './frozen-engine/random-planning-requests';
import { multiYearRequests } from './frozen-engine/multi-year-planning-requests';
/** Rebuild instructions for the frozen engine: docs/benchmark/README.md. */
const BASE_SEED = 280_000;
@@ -91,6 +92,23 @@ function assertSameAsFrozen(seed: number): void {
}
}
/** Fixed multi-year requests are compared like seeded ones; a failure names the request. */
function assertMultiYearSameAsFrozen(name: string, request: Req): void {
const current = run(calculatePlanningInternal, request);
const frozen = run(frozenCalculate, request);
try {
expect(current).toStrictEqual(frozen);
} catch (error) {
throw new Error(
`Engine differs from frozen engine. multi-year request=${name}\nrequest=${JSON.stringify(request)}\n${
(error as Error).message
}`,
{ cause: error },
);
}
expect(current.outcome.kind, name).toBe('Plan');
}
type AsyncEngine = typeof calculatePlanningAsyncInternal;
/** Cancels after a seed-derived step count: during preparation, mid-search, or never. */
@@ -167,6 +185,11 @@ describe('frozen engine differential check', () => {
}, 300_000);
}
for (const { name, request } of multiYearRequests())
it(`matches the frozen engine on a multi-year request: ${name}`, () => {
assertMultiYearSameAsFrozen(name, request);
}, 120_000);
it('retains incumbents of cancelled calculations', () => {
console.info('cancelled coverage', Object.fromEntries(cancelledKinds), { incumbents });
expect(cancelledKinds.get('PlanningIncomplete') ?? 0).toBeGreaterThan(20);
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,137 @@
// Fixed multi-year requests for the frozen-engine check, planned with the default rules.
// Nothing here reads the clock: calculation dates and window dates are explicit.
import { createOptimizationPresetRules } from '../rule-service';
import type { Req } from './random-planning-requests';
type Rule = Req['rules'][number];
const [lossPrevention, ...otherPresets] = createOptimizationPresetRules() as unknown as Rule[];
/** Samedi Malin: two CP on the days around a Saturday, earning one Other day. */
const samediMalin: Rule = {
id: 'samedi',
type: 'if_then',
force: 'preference',
enabled: true,
dayOfWeek: 6,
placeDays: 2,
placeType: 'cp',
placement: 'auto',
rewardDays: 1,
rewardType: 'other',
};
/** Five days of any type between 20 December of `year` and 3 January of the next year. */
const christmasWindow = (year: number): Rule => ({
id: 'christmas',
type: 'time_window',
force: 'preference',
enabled: true,
startDate: `${year}-12-20`,
endDate: `${year + 1}-01-03`,
placeDays: 5,
placeType: 'any',
});
/** The default rules, in order: loss prevention, Samedi Malin, Christmas, the other presets. */
const defaultRules = (year: number): Rule[] => [
lossPrevention,
samediMalin,
christmasWindow(year),
...otherPresets,
];
/** One balance per type and year, available on 1 January and expiring on 31 December. */
function yearlyBalances(first: number, years: number, quantities: Record<string, number>) {
return Array.from({ length: years }, (_, index) => first + index).flatMap((year) =>
Object.entries(quantities).map(([type, quantity]) => ({
id: `${type}-${year}`,
type,
quantity,
availableFrom: `${year}-01-01`,
expiryDate: `${year}-12-31`,
})),
);
}
/** Balances for `years` calendar years from `first`, planned over `horizon`, calculated on its first day. */
function request(
first: number,
years: number,
quantities: Record<string, number>,
rules: Rule[],
horizon = { start: `${first}-01-01`, end: `${first + years}-01-01` },
): Req {
return {
calculationDate: horizon.start,
horizon,
balances: yearlyBalances(first, years, quantities),
rules,
};
}
export interface MultiYearCase {
name: string;
request: Req;
}
export function multiYearRequests(): MultiYearCase[] {
return [
{
// #350: Samedi Malin on Saturday 8 May 2027 follows Ascension.
name: 'three years of 5 CP',
request: request(2025, 3, { cp: 5 }, defaultRules(2025)),
},
{
// The obligation search with a rule that earns leave (#347).
name: 'two years of 5 CP with a TIME_WINDOW obligation',
request: request(2024, 2, { cp: 5 }, [
lossPrevention,
samediMalin,
christmasWindow(2024),
{
id: 'february',
type: 'time_window',
force: 'obligation',
enabled: true,
startDate: '2024-02-01',
endDate: '2024-02-28',
placeDays: 5,
placeType: 'any',
},
...otherPresets,
]),
},
{
// Samedi Malin ahead of loss prevention (#349).
name: 'two years of 5 CP with Samedi Malin before loss prevention',
request: request(2025, 2, { cp: 5 }, [
samediMalin,
lossPrevention,
christmasWindow(2025),
...otherPresets,
]),
},
{
name: 'one year of 25 CP and 12 RTT',
request: request(2025, 1, { cp: 25, rtt: 12 }, defaultRules(2025)),
},
{
// Three Saturday public holidays: Samedi Malin shapes the Christmas and holiday-week stages (#348).
name: 'one year of 25 CP and 12 RTT from 2027',
request: request(2027, 1, { cp: 25, rtt: 12 }, defaultRules(2027)),
},
{
name: 'three years of 5 CP from 2026',
request: request(2026, 3, { cp: 5 }, defaultRules(2026)),
},
{
// A horizon that crosses the year boundary of the balances and of the Christmas window.
name: 'one year from 1 September 2025 of 10 CP and 4 RTT',
request: request(2025, 2, { cp: 10, rtt: 4 }, defaultRules(2025), {
start: '2025-09-01',
end: '2026-09-01',
}),
},
];
}
@@ -0,0 +1,283 @@
// Opt-in runner, outside the functional suite and CI: plans one of the named requests of the
// #347 to #350 records (docs/benchmark/issue-347.md and following) and prints where the time goes.
// bun src/app/services/frozen-engine/repro-requests.ts list
// bun src/app/services/frozen-engine/repro-requests.ts <request> [current|frozen] [budget ms] [dump file]
// The budget is the request's planning-work budget (default 120000). Keep one: before #347 and
// #349, some of these requests searched without end and held gigabytes of memory.
import { readFileSync } from 'node:fs';
import type {
PlanningArtifacts,
PlanningOutcome,
PlanningRule,
SubmittedRequest,
} from '../leave-planner.core';
// The preset rules come from an Angular service file, which needs the JIT compiler outside tests.
await import('@angular/compiler');
const { createOptimizationPresetRules } = await import('../rule-service');
const engines = {
current: await import('../leave-planner.core'),
frozen: await import('./leave-planner.core.frozen.mjs'),
};
const [lossPrevention, holidayWeeks, ...laterPresets] =
createOptimizationPresetRules() as unknown as PlanningRule[];
const otherPresets = [holidayWeeks, ...laterPresets];
const samediMalin: PlanningRule = {
id: 'samedi',
type: 'if_then',
force: 'preference',
enabled: true,
dayOfWeek: 6,
placeDays: 2,
placeType: 'cp',
placement: 'auto',
rewardDays: 1,
rewardType: 'other',
};
function timeWindow(
id: string,
force: 'obligation' | 'preference',
startDate: string,
endDate: string,
placeDays: number,
placeType = 'any',
): PlanningRule {
return {
id,
type: 'time_window',
force,
enabled: true,
startDate,
endDate,
placeDays,
placeType,
};
}
/** Five days of any type between 20 December of `year` and 3 January of the next year. */
const christmas = (year: number) =>
timeWindow('christmas', 'preference', `${year}-12-20`, `${year + 1}-01-03`, 5);
/** One balance per type and year, available on 1 January and expiring on 31 December. */
function request(
first: number,
years: number,
quantities: Record<string, number>,
rules: PlanningRule[],
): SubmittedRequest {
return {
calculationDate: `${first}-01-01`,
horizon: { start: `${first}-01-01`, end: `${first + years}-01-01` },
balances: Array.from({ length: years }, (_, index) => first + index).flatMap((year) =>
Object.entries(quantities).map(([type, quantity]) => ({
id: `${type}-${year}`,
type,
quantity,
availableFrom: `${year}-01-01`,
expiryDate: `${year}-12-31`,
})),
),
rules,
};
}
/** A day that expires after the horizon of a 2025 request: a deferred balance. */
function withDeferredCpDay(base: SubmittedRequest): SubmittedRequest {
return {
...base,
balances: [
...base.balances,
{
id: 'cp-next',
type: 'cp',
quantity: 1,
availableFrom: '2025-06-01',
expiryDate: '2026-05-31',
},
],
};
}
const february2024 = timeWindow('feb', 'obligation', '2024-02-01', '2024-02-28', 5);
const august2024 = (days: number) =>
timeWindow('aug', 'obligation', '2024-08-01', '2024-08-28', days, 'cp');
const december2025 = timeWindow('dec', 'obligation', '2025-12-01', '2025-12-28', 5);
const fullYear = { cp: 25, rtt: 12 };
/** `samedi` chooses between a request and its variant without Samedi Malin. */
const optionalSamedi = (samedi: boolean) => (samedi ? [samediMalin] : []);
const requests: Record<string, () => SubmittedRequest> = {
// #347: an obligation with a preference rule that earns leave.
'347-3y': () => obligationRequest(3, true, [february2024]),
'347-3y-nosamedi': () => obligationRequest(3, false, [february2024]),
'347-2y': () => obligationRequest(2, true, [february2024]),
'347-2y-noobligation': () => obligationRequest(2, true, []),
'347-4y-conflict': () =>
obligationRequest(4, true, [christmas(2024), august2024(10), february2024]),
'347-4y-conflict-nosamedi': () =>
obligationRequest(4, false, [christmas(2024), august2024(10), february2024]),
'347-3y-two-obligations': () =>
obligationRequest(3, true, [
christmas(2024),
august2024(3),
timeWindow('feb', 'obligation', '2024-02-01', '2024-02-28', 2),
]),
'347-3y-two-obligations-nosamedi': () =>
obligationRequest(3, false, [
christmas(2024),
august2024(3),
timeWindow('feb', 'obligation', '2024-02-01', '2024-02-28', 2),
]),
// The window follows Saturday 1 November 2025, so that occurrence can fund the obligation.
'347x-3y-obligation-after': () => obligationRequest(3, true, [december2025]),
'347x-3y-obligation-after-nosamedi': () => obligationRequest(3, false, [december2025]),
// Sixteen months with fuller balances: the February 2026 obligation follows Saturday
// 1 November 2025, so that occurrence joins the obligation search and lifts its solution limit.
'347x-16-months-obligation-after': () => sixteenMonthsRequest(true),
'347x-16-months-obligation-after-nosamedi': () => sixteenMonthsRequest(false),
// #348: the stages after Samedi Malin, three years from 2024 and the 2027 year.
'348-presets': () => request(2024, 3, fullYear, [lossPrevention, ...otherPresets]),
'348-christmas': () =>
request(2024, 3, fullYear, [lossPrevention, christmas(2024), ...otherPresets]),
'348-samedi': () => request(2024, 3, fullYear, [lossPrevention, samediMalin, ...otherPresets]),
'348-default': () => defaultRequest(2024, 3),
'348x-2025-1y-default': () => defaultRequest(2025, 1),
'348x-2027-1y-default': () => defaultRequest(2027, 1),
'348x-2027-1y-nosamedi': () =>
request(2027, 1, fullYear, [lossPrevention, christmas(2027), ...otherPresets]),
'348x-2027-2y-default': () => defaultRequest(2027, 2),
// #349: loss prevention behind another preference, with a balance that keeps days.
'349-samedi-first': () =>
request(2025, 1, fullYear, [samediMalin, lossPrevention, ...otherPresets]),
'349-loss-first': () =>
request(2025, 1, fullYear, [lossPrevention, samediMalin, ...otherPresets]),
'349-samedi-first-2y-5cp': () =>
request(2025, 2, { cp: 5 }, [samediMalin, lossPrevention, ...otherPresets]),
'349x-christmas-first': () =>
request(2025, 1, fullYear, [christmas(2025), lossPrevention, ...otherPresets]),
'349x-christmas-first-deferred': () =>
withDeferredCpDay(
request(2025, 1, fullYear, [christmas(2025), lossPrevention, ...otherPresets]),
),
'349x-loss-first-deferred': () =>
withDeferredCpDay(
request(2025, 1, fullYear, [lossPrevention, christmas(2025), ...otherPresets]),
),
'349x-holiday-weeks-first-deferred': () =>
withDeferredCpDay(
request(2025, 1, fullYear, [holidayWeeks, lossPrevention, ...laterPresets]),
),
// #350: Samedi Malin on Saturday 8 May 2027 follows Ascension.
'350': () =>
request(2025, 3, { cp: 5 }, [
lossPrevention,
samediMalin,
christmas(2025),
...otherPresets,
]),
};
/** 5 CP per year from 2024: loss prevention, Samedi Malin, the extra rules, then the other presets. */
function obligationRequest(years: number, samedi: boolean, extra: PlanningRule[]) {
return request(2024, years, { cp: 5 }, [
lossPrevention,
...optionalSamedi(samedi),
...extra,
...otherPresets,
]);
}
/** May 2025 to August 2026, 16 CP and 12 RTT per year, an obligation of 4 days in February 2026. */
function sixteenMonthsRequest(samedi: boolean): SubmittedRequest {
return {
...request(2025, 2, { cp: 16, rtt: 12 }, [
lossPrevention,
...optionalSamedi(samedi),
timeWindow('feb', 'obligation', '2026-02-03', '2026-02-24', 4),
timeWindow('christmas', 'preference', '2025-12-20', '2026-01-03', 5, 'cp'),
...otherPresets,
]),
calculationDate: '2025-05-01',
horizon: { start: '2025-05-01', end: '2026-09-01' },
};
}
/** 25 CP and 12 RTT per year with the default rules. */
function defaultRequest(first: number, years: number) {
return request(first, years, fullYear, [
lossPrevention,
samediMalin,
christmas(first),
...otherPresets,
]);
}
const [name = 'list', engineName = 'current', budget = '120000', dumpFile] = process.argv.slice(2);
if (name === 'list') {
console.log(Object.keys(requests).join('\n'));
process.exit(0);
}
if (!Object.hasOwn(requests, name) || !Object.hasOwn(engines, engineName))
throw new Error(
`Unknown request "${name}" or engine "${engineName}". Usage: repro-requests.ts <request|list> [current|frozen] [budget ms] [dump file]`,
);
const build = requests[name];
const engine = engines[engineName as keyof typeof engines];
const stages: [stage: string, at: number][] = [];
const started = performance.now();
let artifacts: PlanningArtifacts | undefined;
const outcome: PlanningOutcome = await engine.calculatePlanningAsyncInternal(
{
...build(),
deadlineMs: Number(budget),
progress: (stage: string) => stages.push([stage, performance.now() - started]),
},
undefined,
(value) => (artifacts = value),
);
const total = performance.now() - started;
/** Time between the first report of each planning stage and the first report of the next one. */
const stageMs: Record<string, number> = {};
for (const [index, [stage, at]] of stages.entries()) {
const next = stages.slice(index + 1).find(([other]) => other !== stage);
if (stages[index - 1]?.[0] !== stage)
stageMs[stage] = Math.round((stageMs[stage] ?? 0) + (next?.[1] ?? total) - at);
}
const plan = outcome.kind === 'Plan' ? outcome : undefined;
let peakMemory: string | undefined;
try {
peakMemory = /VmHWM:\s+(\d+ kB)/.exec(readFileSync('/proc/self/status', 'utf8'))?.[1];
} catch {
// Not Linux: no peak resident memory to report.
}
console.log(
JSON.stringify(
{
request: name,
engine: engineName,
outcome: outcome.kind,
reasons: 'reasons' in outcome ? outcome.reasons.map(({ code }) => code) : undefined,
seconds: Number((total / 1000).toFixed(2)),
placements: plan?.placements.length,
preferences: plan?.preferences.map(
({ ruleId, satisfied, requested, reason }) =>
`${ruleId} ${satisfied}/${requested}${reason ? ` ${reason.code}` : ''}`,
),
lastStageReported: stages.at(-1)?.[0],
stageMs,
peakMemory,
},
null,
'\t',
),
);
if (dumpFile) await Bun.write(dumpFile, JSON.stringify({ outcome, artifacts }, null, '\t'));
@@ -100,3 +100,161 @@ describe('choosing among obligation solutions', () => {
]);
});
});
describe('preference producers in the obligation search', () => {
const samediMalin = {
id: 'samedi',
type: 'if_then',
force: 'preference',
dayOfWeek: 6,
placeDays: 2,
placeType: 'cp',
placement: 'auto',
rewardDays: 1,
rewardType: 'other',
} as const;
const obligation = (id: string, startDate: string, endDate: string, placeDays: number) =>
({
id,
type: 'time_window',
force: 'obligation',
startDate,
endDate,
placeDays,
placeType: 'any',
}) as const;
const yearlyCp = (...years: number[]) =>
years.map((year) => ({
id: `cp-${year}`,
type: 'cp' as const,
quantity: 5,
availableFrom: `${year}-01-01`,
expiryDate: `${year}-12-31`,
}));
const [lossPrevention, ...otherPresets] = presets;
it('leaves a pattern that funds no obligation to its own stage', () => {
// Samedi Malin falls in November 2025, after the February 2024 obligation,
// so its earned day cannot fund it. Loss prevention then ranks before the
// pattern, as it does for the same request without the obligation, and the
// plan is the one planned without Samedi Malin.
const request = (rules: { samedi: boolean; obligation: boolean }) => ({
calculationDate: '2024-01-01',
horizon: { start: '2024-01-01', end: '2026-01-01' },
balances: yearlyCp(2024, 2025),
rules: [
lossPrevention,
...(rules.samedi ? [samediMalin] : []),
...(rules.obligation
? [obligation('february', '2024-02-01', '2024-02-28', 5)]
: []),
...otherPresets,
],
});
const samediVerdict = (outcome: ReturnType<typeof calculatePlanningInternal>) =>
outcome.kind === 'Plan'
? outcome.preferences.find(({ ruleId }) => ruleId === 'samedi')
: undefined;
const outcome = calculatePlanningInternal(request({ samedi: true, obligation: true }));
const withoutObligation = calculatePlanningInternal(
request({ samedi: true, obligation: false }),
);
const withoutSamedi = calculatePlanningInternal(
request({ samedi: false, obligation: true }),
);
expect(outcome.kind).toBe('Plan');
if (outcome.kind !== 'Plan' || withoutSamedi.kind !== 'Plan') return;
expect(outcome.placements).toHaveLength(10);
expect(
outcome.placements.filter(({ ruleIds }) => ruleIds.includes('february')),
).toHaveLength(5);
expect(samediVerdict(outcome)).toMatchObject({
satisfied: 0,
reason: { code: 'higher-priority' },
});
expect(samediVerdict(outcome)).toEqual(samediVerdict(withoutObligation));
expect(outcome.placements).toEqual(withoutSamedi.placements);
});
it('still lets a pattern fund an obligation that only its earned leave can pay', () => {
const outcome = calculatePlanningInternal({
calculationDate: '2025-10-27',
horizon: { start: '2025-10-27', end: '2025-11-15' },
balances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2026-05-31' }],
rules: [
samediMalin,
{ ...obligation('after', '2025-11-12', '2025-11-14', 1), placeType: 'other' },
],
});
expect(outcome.kind).toBe('Plan');
if (outcome.kind !== 'Plan') return;
expect(
outcome.placements.map(({ date, balanceId, ruleIds }) => [date, balanceId, ruleIds]),
).toEqual([
['2025-10-30', 'cp', ['samedi']],
['2025-10-31', 'cp', ['samedi']],
['2025-11-12', 'earned:samedi:2025-11-01', ['after']],
]);
});
it('still lets a pattern fund an obligation through the pattern of another producer', () => {
// The Saturday pattern earns RTT, which no obligation accepts; only the
// Armistice pattern can spend it, and that pattern earns the Other day the
// obligation needs.
const outcome = calculatePlanningInternal({
calculationDate: '2025-10-27',
horizon: { start: '2025-10-27', end: '2025-11-22' },
balances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2026-05-31' }],
rules: [
{ ...samediMalin, rewardType: 'rtt' },
{
id: 'armistice',
type: 'if_then',
force: 'preference',
dayOfWeek: 2,
placeDays: 1,
placeType: 'rtt',
placement: 'before',
rewardDays: 1,
rewardType: 'other',
},
{ ...obligation('after', '2025-11-13', '2025-11-14', 1), placeType: 'other' },
],
});
expect(outcome.kind).toBe('Plan');
if (outcome.kind !== 'Plan') return;
expect(
outcome.placements.map(({ date, balanceId, ruleIds }) => [date, balanceId, ruleIds]),
).toEqual([
['2025-10-30', 'cp', ['samedi']],
['2025-10-31', 'cp', ['samedi']],
['2025-11-10', 'earned:samedi:2025-11-01', ['armistice']],
['2025-11-13', 'earned:armistice:2025-11-11', ['after']],
]);
});
it('reports a planning conflict without enumerating patterns that fund no obligation', () => {
// Both obligations need 2025 leave and every Saturday holiday of the horizon
// comes after them. Enumerating those patterns with every obligation choice
// used to take seconds; the budget turns that cost into an incomplete outcome.
const outcome = calculatePlanningInternal({
calculationDate: '2025-01-01',
horizon: { start: '2025-01-01', end: '2027-01-01' },
balances: yearlyCp(2025, 2026),
rules: [
lossPrevention,
samediMalin,
{ ...obligation('august', '2025-08-01', '2025-08-28', 3), placeType: 'cp' },
obligation('february', '2025-02-01', '2025-02-28', 3),
...otherPresets,
],
deadlineMs: 2_000,
});
expect(outcome.kind).toBe('PlanningConflict');
});
});
+340 -52
View File
@@ -854,7 +854,7 @@ function normalizeBalances(
return { balances, submitted, reasons };
}
function normalizeRules(rawInput: unknown): {
export function normalizeRules(rawInput: unknown): {
rules: NormalizedRule[];
reasons: PlanningReason[];
} {
@@ -1321,6 +1321,41 @@ function compareRequirements(a: Requirement, b: Requirement): number {
);
}
/**
* Keep the preference producers whose earned leave can fund an obligation,
* directly or through the pattern of another kept producer (ADR 0012). An
* earned leave entitlement becomes available after its time-off period, which
* holds the occurrence, so only a compatible date after the occurrence can
* spend it. The other producers wait for their own preference stage.
*/
function obligationFundingProducers(
producers: Requirement[],
obligations: Requirement[],
): Requirement[] {
const canFund = (producer: Requirement, consumer: Requirement) =>
consumer !== producer &&
consumer.requiredPlacements > 0 &&
selectorMatches(consumer.rule.placeType, producer.rule.rewardType!) &&
(consumer.candidates ?? consumer.patterns!.flat()).some(
(date) => compareDate(date, producer.occurrenceDate!) > 0,
);
const funding = new Set<Requirement>();
// Grow the set until no producer joins: chains and cycles settle in at most one pass per producer.
for (let grown = true; grown; ) {
grown = false;
for (const producer of producers) {
if (
!funding.has(producer) &&
[...obligations, ...funding].some((consumer) => canFund(producer, consumer))
) {
funding.add(producer);
grown = true;
}
}
}
return producers.filter((producer) => funding.has(producer));
}
function obligationBranchEstimate(requirements: Requirement[]): number {
let estimate = 1;
for (const requirement of requirements) {
@@ -2240,6 +2275,81 @@ function typedCalendarDates(context: SearchContext): Set<string> {
return typedDates;
}
/**
* Whether no completion of a calendar bundle can be accepted. From `current`, the bundle only
* fills the `open` target dates, each with an addition or a donor moved from a date outside the
* targets, and finalizing never moves or retypes a placement. So each protected objective has an
* optimistic value over every completion; when the first one that differs from the baseline is
* worse, every completion has a worse prefix and is rejected. An objective without such a value
* stops the check.
*/
function bundleCannotBeAccepted(
current: State,
open: readonly string[],
prefix: readonly NormalizedRule[],
baseline: readonly PlanningObjective[],
context: SearchContext,
): boolean {
const openDates = new Set(open);
const filled = (date: string) =>
current.placements.has(date) || context.declaredDates.has(date) || openDates.has(date);
for (const [index, rule] of prefix.entries()) {
let optimistic: number | undefined;
if (rule.type === 'time_window') {
let count = declaredWindowDays(rule, context).length;
for (const placement of current.placements.values())
if (
placement.date >= rule.startDate! &&
placement.date <= rule.endDate! &&
selectorMatches(rule.placeType, placement.type)
)
count++;
for (const date of open) if (date >= rule.startDate! && date <= rule.endDate!) count++;
optimistic = Math.min(rule.placeDays, count);
} else if (rule.type === 'if_then')
optimistic = occurrences(rule, context).filter((occurrence) =>
patternsFor(rule, occurrence, context).some((pattern) =>
pattern.every(
(date) =>
openDates.has(date) ||
patternDateSatisfied(date, rule, current, context),
),
),
).length;
else if (rule.type === 'optimization' && isUnplacedQuantitySum(rule)) {
// Moves keep every quantity, additions spend at most one day per open date, and only
// earned balances can appear or disappear when finalizing.
const selected = optimizationBalanceObservations(current, context).reduce(
(sum, observation, position) =>
current.balances[position].earned ||
(rule.configuration.conditions.includes('at-risk') && !observation.atRisk)
? sum
: sum + observation.unplacedQuantity,
0,
);
optimistic = Math.max(0, selected - open.length);
} else if (rule.type === 'optimization' && isHolidayWeekValueMaximum(rule))
optimistic = evaluateValidatedOptimization(rule.configuration, {
leaveBalances: [],
publicHolidayWeeks: context.holidayWeeks.map(({ value, dates }) => ({
value,
complete: dates.every(filled),
})),
timeOffPeriods: [],
workSequences: [],
leavePlacements: [],
});
if (optimistic === undefined) return false;
const comparison = compareObjectiveValues(
baseline[index].direction,
optimistic,
baseline[index].value,
);
if (comparison !== 0) return comparison > 0;
}
return false;
}
function* calendarPlacementCandidates(
state: State,
targetDates: string[],
@@ -2247,6 +2357,7 @@ function* calendarPlacementCandidates(
context: SearchContext,
accept: (candidate: State, addition?: boolean) => boolean,
donorObjectives = new Map<string, PlanningObjective[]>(),
cannotBeAccepted?: (current: State, open: readonly string[]) => boolean,
): PlanningSteps<boolean> {
const missing = targetDates.filter(
(date) => !state.placements.has(date) && !context.declaredDates.has(date),
@@ -2300,6 +2411,14 @@ function* calendarPlacementCandidates(
]),
]);
if (failed.has(key)) return false;
if (
index > 0 &&
index < missing.length &&
cannotBeAccepted?.(current, missing.slice(index))
) {
failed.add(key);
return false;
}
if (index === missing.length) {
const benefit = supportingCalendarBenefit(before, current, context);
for (const date of additions) {
@@ -2370,6 +2489,7 @@ function* holidayWeekPlacementCandidates(
ruleId: string,
context: SearchContext,
accept: (candidate: State, addition?: boolean) => boolean,
cannotBeAccepted?: (current: State, open: readonly string[]) => boolean,
): PlanningSteps<void> {
// Releasing a donor scores the same for every week of this plan.
const donorObjectives = new Map<string, PlanningObjective[]>();
@@ -2381,6 +2501,7 @@ function* holidayWeekPlacementCandidates(
context,
accept,
donorObjectives,
cannotBeAccepted,
);
}
@@ -2389,6 +2510,7 @@ function* timeOffPeriodPlacementCandidates(
ruleId: string,
context: SearchContext,
accept: (candidate: State, addition?: boolean) => boolean,
cannotBeAccepted?: (current: State, open: readonly string[]) => boolean,
): PlanningSteps<void> {
const periods = periodData(state, context);
for (let index = 1; index < periods.length; index++) {
@@ -2396,7 +2518,15 @@ function* timeOffPeriodPlacementCandidates(
(date) => date > periods[index - 1].end && date < periods[index].start,
);
if (dates.length > 1)
yield* calendarPlacementCandidates(state, dates, ruleId, context, accept);
yield* calendarPlacementCandidates(
state,
dates,
ruleId,
context,
accept,
undefined,
cannotBeAccepted,
);
}
}
@@ -2506,6 +2636,53 @@ function provablyWorseThanProtectedPrefix(
return false;
}
/**
* True when the candidate's finalized vector provably cannot beat the incumbent: its first
* difference on finalize-invariant objectives and tie-breaks is worse, or it has none. A
* finalized candidate always satisfies every obligation, so a valid incumbent is required.
*/
function provablyNotBetterThanIncumbent(
candidate: State,
context: SearchContext,
incumbent: readonly PlanningObjective[],
): boolean {
if (incumbent[0].value !== 0) return false;
const invariance = finalizeInvariance(context);
let index = 0;
let settled: boolean | undefined;
for (const objective of activeObjectives(candidate, context)) {
const kind = invariance[index];
if (
kind === 'unknown' ||
(kind === 'settled-earning' && !(settled ??= earningSettled(candidate, context)))
)
return false;
const comparison = compareObjectiveValues(
objective.direction,
objective.value,
incumbent[index + 1].value,
);
if (comparison !== 0) return comparison > 0;
index++;
}
// Placement dates never change when finalizing; balance expiries only with earned leave.
if (!(settled ?? earningSettled(candidate, context))) return false;
for (const objective of tieBreakObjectives(candidate, context)) {
const comparison = compareObjectiveValues(
objective.direction,
objective.value,
incumbent[index + 1].value,
);
if (comparison !== 0) return comparison > 0;
index++;
}
return true;
}
/**
* With `onlyIfBetter`, the caller acts only on a returned vector that beats the incumbent, so a
* candidate that provably cannot is rejected before it is finalized.
*/
function evaluateRuleCandidate(
before: State,
candidate: State | null,
@@ -2514,9 +2691,14 @@ function evaluateRuleCandidate(
addition = false,
baseline = activeObjectiveVector(before, context, throughIndex),
incumbentVector = objectiveVector(before, context),
onlyIfBetter = false,
): { state: State; vector?: PlanningObjectiveVector } | undefined {
if (!candidate) return undefined;
if (provablyWorseThanProtectedPrefix(candidate, context, throughIndex, baseline))
if (
onlyIfBetter
? provablyNotBetterThanIncumbent(candidate, context, incumbentVector.objectives)
: provablyWorseThanProtectedPrefix(candidate, context, throughIndex, baseline)
)
return undefined;
const state = finalizeRuleCandidate(candidate, context, before);
if (!state) return undefined;
@@ -2681,6 +2863,106 @@ function* workSequencePlacementCandidates(
}
}
function isUnplacedQuantitySum(rule: NormalizedRule): boolean {
return (
rule.type === 'optimization' &&
rule.configuration.elements === 'leave-balances' &&
rule.configuration.measure === 'unplaced-quantity' &&
rule.configuration.aggregation === 'sum' &&
rule.configuration.direction === 'minimize'
);
}
function isHolidayWeekValueMaximum(rule: NormalizedRule): boolean {
return (
rule.type === 'optimization' &&
rule.configuration.elements === 'public-holiday-weeks' &&
rule.configuration.measure === 'public-holiday-week-value' &&
rule.configuration.direction === 'maximize'
);
}
/** A value no valid plan can beat for this preference, when one is known without search. */
function bestObjectiveValue(rule: NormalizedRule, context: SearchContext): number | undefined {
if (rule.type === 'time_window') return rule.placeDays;
if (rule.type === 'if_then')
return occurrences(rule, context).filter(
(occurrence) => patternsFor(rule, occurrence, context).length > 0,
).length;
if (rule.type !== 'optimization') return undefined;
// Every measure is a count, quantity, length or distance: none is negative.
if (rule.configuration.direction === 'minimize') return 0;
if (isHolidayWeekValueMaximum(rule))
return evaluateValidatedOptimization(rule.configuration, {
leaveBalances: [],
publicHolidayWeeks: context.holidayWeeks.map(({ value }) => ({
value,
complete: true,
})),
timeOffPeriods: [],
workSequences: [],
leavePlacements: [],
});
return undefined;
}
/** Preferences whose value depends only on which dates are occupied, whatever their leave type or balance. */
function occupancyOnlyObjective(rule: NormalizedRule): boolean {
return rule.type === 'optimization'
? ['public-holiday-weeks', 'time-off-periods', 'work-sequences'].includes(
rule.configuration.elements,
)
: rule.type === 'time_window' && rule.placeType === 'any';
}
/**
* A relocation chain keeps every occupied date and ends on one free date, and its addition is
* accepted only when it strictly improves the protected prefix. False when no such candidate can:
* every prefix objective is at its best value, or depends only on occupied dates and no single
* free date would improve it.
*/
function relocationMayImprovePrefix(
state: State,
context: SearchContext,
prefix: readonly NormalizedRule[],
active: readonly PlanningObjective[],
bestValues: readonly (number | undefined)[],
): boolean {
const probed = new Set<PlanningObjectiveId>();
for (const [index, rule] of prefix.entries()) {
if (bestValues[index] !== undefined && active[index].value === bestValues[index]) continue;
if (!occupancyOnlyObjective(rule)) return true;
probed.add(active[index].id);
}
if (!probed.size) return false;
const baseline = new Map(active.map((objective) => [objective.id, objective.value]));
for (const date of context.workingDays) {
context.check();
if (state.placements.has(date) || context.declaredDates.has(date)) continue;
// The probe only occupies the date: no balance funds it and no objective it is asked for reads one.
const placements = new Map(state.placements);
notePlacementAdded(state.placements, placements, date);
placements.set(date, {
date,
balanceId: '',
type: 'cp',
ruleIds: new Set(),
supporting: false,
});
const probe: State = { ...state, placements };
for (const objective of activeObjectives(probe, context, prefix.length - 1, probed))
if (
compareObjectiveValues(
objective.direction,
objective.value,
baseline.get(objective.id)!,
) < 0
)
return true;
}
return false;
}
/** Candidate additions need an active rule improvement; expiry and date ties only reshape existing placements. */
function* optimizeRulePlacements(
state: State,
@@ -2690,13 +2972,7 @@ function* optimizeRulePlacements(
rule?: NormalizedRule,
): PlanningSteps<State> {
let result = state;
const addingBalanceQuantity =
allowAdd &&
rule?.type === 'optimization' &&
rule.configuration.elements === 'leave-balances' &&
rule.configuration.measure === 'unplaced-quantity' &&
rule.configuration.aggregation === 'sum' &&
rule.configuration.direction === 'minimize';
const addingBalanceQuantity = allowAdd && rule !== undefined && isUnplacedQuantitySum(rule);
const equivalentAdditionFunding =
addingBalanceQuantity &&
throughIndex === 0 &&
@@ -2714,34 +2990,17 @@ function* optimizeRulePlacements(
const preferencePrefix = context.rules
.filter((item) => item.enabled && item.force === 'preference')
.slice(0, throughIndex + 1);
const prefixBounds = preferencePrefix.map((item, index): number | undefined => {
if (index === 0)
return item.type === 'optimization' &&
item.configuration.elements === 'leave-balances' &&
item.configuration.measure === 'unplaced-quantity' &&
item.configuration.aggregation === 'sum' &&
item.configuration.direction === 'minimize'
? 0
: undefined;
if (item.type === 'time_window') return item.placeDays;
if (
item.type === 'optimization' &&
item.configuration.elements === 'public-holiday-weeks' &&
item.configuration.measure === 'public-holiday-week-value' &&
item.configuration.direction === 'maximize'
const prefixBestValues = preferencePrefix.map((item) => bestObjectiveValue(item, context));
// Ending the whole stage at these bounds schedules lower priorities later; it keeps its original reach.
const prefixBounds = preferencePrefix.map((item, index): number | undefined =>
(
index === 0
? isUnplacedQuantitySum(item)
: item.type === 'time_window' || isHolidayWeekValueMaximum(item)
)
return evaluateValidatedOptimization(item.configuration, {
leaveBalances: [],
publicHolidayWeeks: context.holidayWeeks.map(({ value }) => ({
value,
complete: true,
})),
timeOffPeriods: [],
workSequences: [],
leavePlacements: [],
});
return undefined;
});
? prefixBestValues[index]
: undefined,
);
const dateInvariantObjectives = context.rules
.filter((item) => item.force === 'preference')
.every(
@@ -2767,9 +3026,7 @@ function* optimizeRulePlacements(
return result;
}
const genericStateKey =
allowAdd &&
result.balances.every(({ remaining }) => remaining === 0) &&
!context.rules.some((item) => item.enabled && item.type === 'if_then')
allowAdd && result.balances.every(({ remaining }) => remaining === 0)
? preferenceStateKey(result)
: undefined;
const reuseGeneric =
@@ -2783,7 +3040,11 @@ function* optimizeRulePlacements(
let beforeCalendar: OptimizationObservations | undefined;
let best = result;
let bestVector = beforeVector;
const consider = (candidate: State | null, addition = false): boolean => {
const consider = (
candidate: State | null,
addition = false,
onlyIfBetter = false,
): boolean => {
const evaluated = evaluateRuleCandidate(
result,
candidate,
@@ -2792,6 +3053,7 @@ function* optimizeRulePlacements(
addition,
baseline,
bestVector,
onlyIfBetter,
);
if (!evaluated) return false;
if (!evaluated.vector) return true;
@@ -2840,7 +3102,14 @@ function* optimizeRulePlacements(
rule.configuration.conditions.includes('complete') &&
rule.configuration.direction === 'maximize'
)
yield* holidayWeekPlacementCandidates(result, rule.id, context, consider);
yield* holidayWeekPlacementCandidates(
result,
rule.id,
context,
consider,
(current, open) =>
bundleCannotBeAccepted(current, open, preferencePrefix, baseline, context),
);
if (
allowAdd &&
rule?.type === 'optimization' &&
@@ -2850,7 +3119,14 @@ function* optimizeRulePlacements(
(rule.configuration.aggregation === 'count' &&
rule.configuration.direction === 'minimize'))
)
yield* timeOffPeriodPlacementCandidates(result, rule.id, context, consider);
yield* timeOffPeriodPlacementCandidates(
result,
rule.id,
context,
consider,
(current, open) =>
bundleCannotBeAccepted(current, open, preferencePrefix, baseline, context),
);
// shortcut: commit a strict bundle prefix improvement before exploring old-state
// generic alternatives; upgrade to a combined frontier if measured cases need it.
const deferGeneric =
@@ -2920,7 +3196,8 @@ function* optimizeRulePlacements(
}
if (!existing || (addingBalanceQuantity && best !== result)) continue;
const without = releasePlacement(result, date);
consider(without);
// The generic scan reads no answer: only a candidate that beats the best one counts.
consider(without, false, true);
for (const balance of without.balances) {
yield;
if (
@@ -2940,7 +3217,7 @@ function* optimizeRulePlacements(
if (reassigned)
reassigned.placements.get(date)!.supporting =
existing.supporting && !isAtRisk(balance, context);
consider(reassigned);
consider(reassigned, false, true);
}
for (const destination of moveDates) {
yield;
@@ -2964,7 +3241,7 @@ function* optimizeRulePlacements(
second.placements.get(destination)!.supporting = existing.supporting;
second.placements.get(date)!.supporting = other.supporting;
}
consider(second);
consider(second, false, true);
} else {
const moved = assignDateToBalance(
without,
@@ -2984,7 +3261,7 @@ function* optimizeRulePlacements(
) {
continue;
}
consider(moved);
consider(moved, false, true);
}
}
}
@@ -2993,7 +3270,17 @@ function* optimizeRulePlacements(
(addingBalanceQuantity ||
(rule?.type === 'time_window' &&
Number(active[throughIndex].value) < rule.placeDays)) &&
compareObjectiveLists(bestVector.objectives.slice(1, throughIndex + 2), baseline) === 0
compareObjectiveLists(bestVector.objectives.slice(1, throughIndex + 2), baseline) ===
0 &&
// A chain only serves an addition that strictly improves the prefix: skip it when none can.
(!addingBalanceQuantity ||
relocationMayImprovePrefix(
result,
context,
preferencePrefix,
active,
prefixBestValues,
))
) {
for (const balance of result.balances) {
if (balance.remaining <= 0) continue;
@@ -4531,14 +4818,15 @@ function* calculatePlanningSteps(
const optionalProducers = obligationRequirements.some(
(requirement) => requirement.requiredPlacements > 0,
)
? buildRequirements(normalized.rules, context, 'preference')
.filter(
? obligationFundingProducers(
buildRequirements(normalized.rules, context, 'preference').filter(
(requirement) =>
requirement.patterns?.length &&
requirement.rule.rewardDays &&
requirement.requiredPlacements > 0,
)
.map((requirement) => ({ ...requirement, optional: true }))
),
obligationRequirements,
).map((requirement) => ({ ...requirement, optional: true }))
: [];
const jointRequirements = optionalProducers.length
? [...obligationRequirements, ...optionalProducers].sort(compareRequirements)
+15 -23
View File
@@ -402,30 +402,22 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));
root.querySelector<HTMLButtonElement>('.statistics-button')!.click();
await fixture.whenStable();
const dialog = document.querySelector('[role="dialog"]')!;
const figure = (label: string) =>
Array.from(
document.querySelectorAll('[role="dialog"] .statistics-summary > div'),
(item) =>
Array.from(item.children, (part) =>
part.textContent?.replace(/\s+/g, ' ').trim(),
),
).find(([name]) => name === label);
const connectedHolidays = () =>
Array.from(document.querySelectorAll('[role="dialog"] .statistics-summary dt'))
.find((label) =>
label.textContent?.includes('Jours fériés reliés à un week-end'),
)
?.nextElementSibling?.textContent?.trim();
figure('Jours fériés qui font un pont')?.[1]?.split(' ')[0];
expect(connectedHolidays()).toBe('1');
const earnedStatistics = () => [
dialog
.querySelector('.statistics-summary > div:last-child dt')
?.textContent?.replace(/\s+/g, ' ')
.trim(),
dialog
.querySelector('.statistics-summary > div:last-child dd')
?.textContent?.trim(),
...Array.from(dialog.querySelectorAll('.earned-leave-breakdown dt'), (label) => [
label.textContent?.trim(),
label.nextElementSibling?.textContent?.trim(),
]),
];
const earnedStatistics = () => figure('Jours gagnés grâce à vos règles');
expect(earnedStatistics()).toEqual([
'Congés acquis avant consommation (jours)',
'Jours gagnés grâce à vos règles',
'1',
['CP autour du férié', '1'],
'CP autour du férié',
]);
expect(dialog.textContent?.includes('Planning partiel')).toBe(cancelled);
const originalDeclarations = structuredClone(calculation.snapshot.declaredDays);
@@ -450,9 +442,9 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));
fixture.detectChanges();
expect(connectedHolidays()).toBe('1');
expect(earnedStatistics()).toEqual([
'Congés acquis avant consommation (jours)',
'Jours gagnés grâce à vos règles',
'1',
['CP autour du férié', '1'],
'CP autour du férié',
]);
dialog.querySelector<HTMLButtonElement>('button')!.click();
await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')).toBeNull());
@@ -479,7 +471,7 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));
expect(plan.ifThenContributions).toEqual(direct.ifThenContributions);
expect(plan.metrics).toEqual(direct.metrics);
expect(plan.timeOffPeriods).toEqual(direct.timeOffPeriods);
expect(root.textContent).toContain('Droit futur généré');
expect(root.textContent).toContain('Jours gagnés');
expect(root.textContent).toContain('CP autour du férié');
expect(root.textContent).not.toContain('Règle modifiée après calcul');
expect(
@@ -193,6 +193,95 @@ describe('explicit active planning objectives', () => {
},
);
// #349: once nothing at risk is left, relocation chains for a balance that is not at risk
// cannot improve a prefix already at its best, and used to be searched without end.
describe('loss prevention behind another preference', () => {
const autumn = {
deadlineMs: 5_000,
horizon: { start: '2025-09-01', end: '2026-01-01' },
balances: [
{ id: 'cp', type: 'cp' as const, quantity: 8, expiryDate: '2025-12-31' },
{ id: 'rtt', type: 'rtt' as const, quantity: 4, expiryDate: '2025-12-31' },
],
};
beforeEach(() => vi.setSystemTime(new Date('2025-09-01T12:00:00Z')));
it('finishes behind Samedi Malin with its earned leave entitlement left', async () => {
const outcome = await createInProcessCalculation({
...autumn,
rules: [
{
id: 'samedi',
name: 'Samedi Malin',
type: 'if_then',
dayOfWeek: 6,
placeDays: 2,
placeType: 'cp',
placement: 'auto',
rewardDays: 1,
rewardType: 'other',
},
loss,
{
id: 'gain',
name: 'Non-working-day gain',
type: 'optimization',
force: 'preference',
configuration: OPTIMIZATION_PRESETS.nonWorkingDayGain,
},
],
}).outcome;
if (outcome.kind !== 'Plan') throw new Error(`Expected a plan, got ${outcome.kind}`);
expect(outcome.metrics.unplacedAtRisk).toBe(0);
expect(outcome.preferences).toMatchObject([{ ruleId: 'samedi', satisfied: 1 }]);
expect(
outcome.placements
.filter(({ ruleIds }) => ruleIds.includes('samedi'))
.map(({ date, type }) => ({ date, type })),
).toEqual([
{ date: '2025-10-30', type: 'cp' },
{ date: '2025-10-31', type: 'cp' },
]);
// The earned day stays for the later rule, which places it as a supporting placement.
expect(
outcome.placements.find(({ balanceId }) => balanceId.startsWith('earned:')),
).toMatchObject({ ruleIds: ['gain'], supporting: true });
}, 30_000);
it('finishes behind a Christmas window with a deferred balance left', async () => {
const outcome = await createInProcessCalculation({
...autumn,
balances: [
...autumn.balances,
{
id: 'deferred-cp',
type: 'cp',
quantity: 1,
availableFrom: '2025-09-01',
expiryDate: '2026-05-31',
},
],
rules: [
{
...personal,
id: 'christmas',
startDate: '2025-12-20',
endDate: '2026-01-03',
placeDays: 5,
placeType: 'any',
},
loss,
],
}).outcome;
if (outcome.kind !== 'Plan') throw new Error(`Expected a plan, got ${outcome.kind}`);
expect(outcome.metrics.unplacedAtRisk).toBe(0);
expect(outcome.preferences).toMatchObject([{ ruleId: 'christmas', satisfied: 5 }]);
expect(outcome.remainingBalances).toMatchObject([
{ id: 'deferred-cp', quantity: 1, classification: 'deferred' },
]);
}, 30_000);
});
it('relocates repeated balance tokens across mandatory windows as a complete chain', async () => {
const windows = [
['cp-first', 'cp', '2024-01-02', '2024-01-03'],
+34 -1
View File
@@ -510,7 +510,40 @@ export function periodBoundsHolding(
): { start: string; end: string } | undefined {
const occupancy = occupancyOf(state.placements, context);
if (shadowMode) verifyOccupancy(state, context, occupancy);
for (const group of occupancy.groups) {
const { groups } = occupancy;
// Group ranges are disjoint and ordered, and a group holds a date only within its range, so
// the first holding group is the lowest one found by searching each date's range.
let first = groups.length;
for (const date of dates) {
const index = context.calendarIndex.get(date);
if (index === undefined) return periodBoundsHoldingByScan(state, context, dates);
let low = 0;
let high = Math.min(first, groups.length);
while (low < high) {
const mid = (low + high) >> 1;
if (groups[mid].endIndex < index) low = mid + 1;
else high = mid;
}
const group = groups[low];
if (
low < first &&
group.startIndex <= index &&
((state.placements.has(date) && group.anchors.includes(date)) ||
context.declaredDates.has(date))
)
first = low;
}
if (first === groups.length) return undefined;
const group = groups[first];
return (group.period ??= calendarPeriod(group.startIndex, group.endIndex, context));
}
function periodBoundsHoldingByScan(
state: ObservedPlan,
context: ObservationCalendar,
dates: readonly string[],
): { start: string; end: string } | undefined {
for (const group of occupancyOf(state.placements, context).groups) {
const period = (group.period ??= calendarPeriod(group.startIndex, group.endIndex, context));
if (
dates.some(
+147 -10
View File
@@ -14,8 +14,10 @@ import {
numericChanges,
objectiveCopy,
objectiveLabel,
optimizationGoal,
optimizationSummary,
outcomeLabel,
plural,
progressStageLabel,
reasonLabel,
ruleLabel,
@@ -24,7 +26,12 @@ import {
validationReasonLabel,
type RuleSource,
} from './planner-labels';
import { OPTIMIZATION_PRESETS } from './planning-objectives';
import {
OPTIMIZATION_CATALOG,
OPTIMIZATION_PRESETS,
type OptimizationCondition,
type OptimizationConfiguration,
} from './planning-objectives';
import type { AppTranslations } from './translation-service';
const en = translationsMap['en'];
@@ -205,15 +212,15 @@ describe('planning stage label', () => {
expect(stageLabel(en, source, 'preference:spring')).toBe('Preference: Spring break');
});
it('names an optimization stage after its rule and its summary', () => {
it('names an optimization stage after its rule and its goal', () => {
expect(stageLabel(en, source, 'optimization:gain')).toBe(
`More days off: ${optimizationSummary(en, OPTIMIZATION_PRESETS.nonWorkingDayGain)}`,
'More days off — Attach leave to weekends and public holidays, to gain as many days off as possible without taking them as leave',
);
});
it('shows the rule identifier when the rule is not in the snapshot', () => {
expect(stageLabel(en, source, 'preference:ghost')).toBe('Preference: ghost');
expect(stageLabel(en, source, 'optimization:ghost')).toBe('ghost: ');
expect(stageLabel(en, source, 'optimization:ghost')).toBe('ghost');
expect(stageLabel(en, null, 'preference:spring')).toBe('Preference: spring');
});
@@ -292,15 +299,15 @@ describe('objective copy', () => {
);
});
it('names an optimization after its rule and its configuration', () => {
it('names an optimization after its rule and its goal, keeping its composition technical', () => {
expect(objectiveCopy(en, source, 'optimization:gain')).toEqual({
label: `More days off: ${optimizationSummary(en, OPTIMIZATION_PRESETS.nonWorkingDayGain)}`,
help: objectives['optimization'].help,
label: 'More days off — Attach leave to weekends and public holidays, to gain as many days off as possible without taking them as leave',
technical: optimizationSummary(en, OPTIMIZATION_PRESETS.nonWorkingDayGain),
});
});
it('names an optimization whose rule is unknown by its identifier alone', () => {
expect(objectiveCopy(en, source, 'optimization:ghost')?.label).toBe('ghost: ');
expect(objectiveCopy(en, source, 'optimization:ghost')).toEqual({ label: 'ghost' });
});
it('has no copy for an unknown objective', () => {
@@ -328,7 +335,7 @@ describe('objective label', () => {
});
describe('numeric changes', () => {
it('lists only numeric objectives whose value differs, with their label and help', () => {
it('lists only numeric objectives whose value differs, with help only where it is specific', () => {
const vector = (
gain: number,
tieBreak: string,
@@ -344,16 +351,146 @@ describe('numeric changes', () => {
{
id: 'optimization:gain',
label: objectiveLabel(en, source, { id: 'optimization:gain' }),
help: objectiveCopy(en, source, 'optimization:gain')?.help,
help: undefined,
before: 1,
after: 3,
},
]);
expect(numericChanges(en, source, vector(1, 'a', 2), vector(1, 'b', 3))).toEqual([
{
id: 'preference:spring',
label: 'Preference: Spring break',
help: en.planning.explanation.preferenceHelp['time_window'],
before: 2,
after: 3,
},
]);
expect(numericChanges(en, source, undefined, vector(3, 'b', 2))).toEqual([]);
expect(numericChanges(en, source, vector(1, 'a', 2), undefined)).toEqual([]);
});
});
describe('optimization goal', () => {
const subsets = (conditions: readonly OptimizationCondition[]) =>
conditions.reduce<OptimizationCondition[][]>(
(found, condition) => [...found, ...found.map((subset) => [...subset, condition])],
[[]],
);
const compositions = OPTIMIZATION_CATALOG.flatMap((row) =>
subsets(row.conditions).flatMap((conditions) =>
row.aggregations.flatMap((aggregation) =>
(['minimize', 'maximize'] as const).map(
(direction) =>
({
elements: row.elements,
measure: row.measure,
conditions,
aggregation,
direction,
...(row.measure === 'work-sequence-deficit'
? { thresholdDays: 3 }
: {}),
}) as OptimizationConfiguration,
),
),
),
);
it('says in French what the supplied rules do for the person', () => {
const goals = Object.fromEntries(
Object.entries(OPTIMIZATION_PRESETS).map(([key, configuration]) => [
key,
optimizationGoal(fr, configuration),
]),
);
expect(goals).toEqual({
unplacedAtRisk:
'Poser les jours qui expirent pendant la période planifiée, pour en perdre le moins possible',
holidayWeekValue:
'Prendre la semaine entière quand elle contient un jour férié, surtout s’il tombe en milieu de semaine',
nonWorkingDayGain:
'Coller les congés aux week-ends et aux jours fériés, pour gagner un maximum de jours de repos sans les poser',
longestWorkSequence:
'Répartir les congés pour raccourcir la plus longue période de travail sans congé',
shortSequenceDeficit:
'Éviter de reprendre le travail pour moins de 5 jours ouvrés entre deux périodes de repos',
supportingPlacements:
'Poser le moins possible de jours qui n’expirent qu’après la période planifiée, afin de les garder pour plus tard',
});
});
it('keeps the intent of a supplied rule with another threshold, and only for its composition', () => {
const deficit = OPTIMIZATION_PRESETS.shortSequenceDeficit;
expect(optimizationGoal(fr, { ...deficit, thresholdDays: 3 })).toBe(
'Éviter de reprendre le travail pour moins de 3 jours ouvrés entre deux périodes de repos',
);
expect(optimizationGoal(fr, { ...deficit, aggregation: 'maximum' })).toBe(
'Réduire le plus grand nombre de jours qui manquent à une période de travail entre deux périodes de repos pour atteindre 5 jours ouvrés',
);
expect(
optimizationGoal(fr, { ...OPTIMIZATION_PRESETS.unplacedAtRisk, conditions: [] }),
).toBe('Réduire les jours non posés');
});
it.each(Object.keys(translationsMap))(
'words every valid composition without engine terms in %s',
(language) => {
const tr = translationsMap[language];
const rules = tr.rules.optimization;
expect(compositions).toHaveLength(90);
const intents = Object.values(rules.plain.intents).map((intent) =>
intent.replace('{threshold}', plural(tr, rules.plain.workingDays, 3)),
);
let supplied = 0;
for (const configuration of compositions) {
const goal = optimizationGoal(tr, configuration);
expect(goal).toMatch(/^\p{Lu}[^{}]+$/u);
// The supplied compositions are worded by intent rather than by their parts.
if (intents.includes(goal!)) {
supplied++;
continue;
}
expect(goal).not.toContain(rules.directions[configuration.direction]);
expect(goal).not.toContain(' — ');
for (const condition of configuration.conditions)
if (condition !== 'non-empty' || configuration.aggregation === 'count')
expect(goal).toContain(rules.plain.scopes[condition]);
if (
configuration.measure === 'work-sequence-deficit' &&
configuration.aggregation !== 'count'
)
expect(goal).toContain(plural(tr, rules.plain.workingDays, 3));
}
expect(supplied).toBe(Object.keys(OPTIMIZATION_PRESETS).length);
},
);
it('leaves out an empty-sequence condition that cannot change a sum or a maximum', () => {
const length = {
...OPTIMIZATION_PRESETS.longestWorkSequence,
conditions: ['non-empty'] as const,
};
expect(optimizationGoal(fr, length)).toBe('Réduire la plus longue période de travail');
expect(optimizationGoal(fr, { ...length, aggregation: 'count' })).toBe(
'Réduire le nombre de périodes de travail d’au moins un jour ouvré',
);
});
it('puts the threshold in the singular or plural of the language', () => {
const deficit = { ...OPTIMIZATION_PRESETS.shortSequenceDeficit, thresholdDays: 1 };
expect(optimizationGoal(fr, deficit)).toContain('pour moins de 1 jour ouvré');
expect(optimizationGoal(en, deficit)).toContain('for fewer than 1 working day');
expect(optimizationGoal(en, { ...deficit, thresholdDays: 2 })).toContain(
'for fewer than 2 working days',
);
});
it('has no goal for an invalid configuration', () => {
const invalid = { ...OPTIMIZATION_PRESETS.nonWorkingDayGain, elements: 'leave-balances' };
expect(optimizationGoal(en, invalid as never)).toBeUndefined();
});
});
describe('optimization summary', () => {
it('describes a valid configuration in the language it is given', () => {
expect(optimizationSummary(en, OPTIMIZATION_PRESETS.nonWorkingDayGain)).not.toBe(
+79 -12
View File
@@ -6,11 +6,13 @@ import type {
PlanningSnapshot,
} from './leave-planner.service';
import {
OPTIMIZATION_PRESETS,
optimizationUnit,
validateOptimizationConfiguration,
type OptimizationCondition,
type OptimizationConfiguration,
} from './planning-objectives';
import type { AppTranslations } from './translation-service';
import type { AppTranslations, PluralForms } from './translation-service';
// Turns planner results into the sentences the page shows. Pure: no Angular, only translations and data.
@@ -79,6 +81,13 @@ export function ruleLabel(source: RuleSource, ruleId: string): string {
return source?.rules.find(({ id }) => id === ruleId)?.name ?? source?.labels[ruleId] ?? ruleId;
}
/** The form of a translation that suits a count in the translation's language. */
export function plural(tr: AppTranslations, forms: PluralForms, count: number): string {
const form = new Intl.PluralRules(tr.locale).select(count) === 'one' ? forms.one : forms.other;
return form.replace('{count}', String(count));
}
/** The technical composition of an optimization rule, kept for the calculation details. */
export function optimizationSummary(tr: AppTranslations, configuration: OptimizationConfiguration) {
const rules = tr.rules.optimization;
if (!validateOptimizationConfiguration(configuration).valid) return rules.invalidConfiguration;
@@ -100,25 +109,83 @@ export function optimizationSummary(tr: AppTranslations, configuration: Optimiza
.replace('{conditions}', conditions.length ? ` (${conditions.join(', ')})` : '');
}
/** The label and help of a planning objective; a rule's objective is named after its rule. */
export function objectiveCopy(tr: AppTranslations, source: RuleSource, id: string) {
/** The supplied rule whose composition a configuration repeats, whatever its threshold. */
function presetOf(configuration: OptimizationConfiguration) {
return (Object.keys(OPTIMIZATION_PRESETS) as (keyof typeof OPTIMIZATION_PRESETS)[]).find(
(key) => {
const preset: OptimizationConfiguration = OPTIMIZATION_PRESETS[key];
return (
preset.elements === configuration.elements &&
preset.measure === configuration.measure &&
preset.aggregation === configuration.aggregation &&
preset.direction === configuration.direction &&
preset.conditions.length === configuration.conditions.length &&
preset.conditions.every((condition) => configuration.conditions.includes(condition))
);
},
);
}
/**
* What an optimization rule aims for, in everyday words; undefined for an invalid configuration.
* The supplied compositions say what the planner does for the person; others describe their measure.
*/
export function optimizationGoal(
tr: AppTranslations,
configuration: OptimizationConfiguration,
): string | undefined {
if (!validateOptimizationConfiguration(configuration).valid) return undefined;
const plain = tr.rules.optimization.plain;
const threshold =
configuration.measure === 'work-sequence-deficit'
? plural(tr, plain.workingDays, configuration.thresholdDays)
: '';
const preset = presetOf(configuration);
if (preset) return plain.intents[preset].replace('{threshold}', threshold);
const { aggregation, conditions } = configuration;
// Qualifiers follow the key order of the translation. An empty work sequence adds nothing to a
// sum or a maximum, so leaving it out only changes a count.
const scope = (Object.keys(plain.scopes) as OptimizationCondition[])
.filter(
(condition) =>
conditions.includes(condition) &&
(condition !== 'non-empty' || aggregation === 'count'),
)
.map((condition) => plain.scopes[condition])
.join('');
const quantity =
aggregation === 'count'
? plain.count.replace('{elements}', plain.elements[configuration.elements])
: plain.quantities[configuration.measure][aggregation];
return plain.goals[configuration.direction].replace(
'{quantity}',
quantity.replace('{scope}', scope).replace('{threshold}', threshold),
);
}
/**
* The label and help of a planning objective; a rule's objective is named after its rule. An
* optimization rule's objective also carries its technical composition for the calculation details.
*/
export function objectiveCopy(
tr: AppTranslations,
source: RuleSource,
id: string,
): { label: string; help?: string; technical?: string } {
const objectives = tr.planning.explanation.objectives;
const reference = ruleOfIdentifier(id);
if (!reference) return objectives[id];
const rule = source?.rules.find((candidate) => candidate.id === reference.ruleId);
const name = ruleLabel(source, reference.ruleId);
if (reference.kind === 'optimization') {
const copy = objectives['optimization'];
const configuration = rule && 'configuration' in rule ? rule.configuration : undefined;
const goal = configuration && optimizationGoal(tr, configuration);
if (!configuration || !goal) return { label: name };
return {
...copy,
label: copy.label
label: objectives['optimization'].label
.replace('{rule}', name)
.replace(
'{summary}',
rule && 'configuration' in rule
? optimizationSummary(tr, rule.configuration)
: '',
),
.replace('{summary}', goal),
technical: optimizationSummary(tr, configuration),
};
}
const copy = objectives['preference'];
+26
View File
@@ -131,6 +131,32 @@ describe('saved rule migration', () => {
);
});
it('renames a saved preset still under its first name and keeps a name the person chose', () => {
const preset = (id: string, name: string) => ({
id,
name,
type: RuleType.OPTIMIZATION,
enabled: false,
configuration: {},
});
localStorage.setItem(
'vacationRules',
JSON.stringify({
version: 1,
rules: [
preset('default-short-sequence-deficit', 'Déficit des reprises'),
preset('default-holiday-week-value', 'Mes ponts'),
preset('mine', 'Déficit des reprises'),
],
}),
);
const names = ['Éviter les reprises trop courtes', 'Mes ponts', 'Déficit des reprises'];
expect(TestBed.inject(RuleService).rules.map(({ name }) => name)).toEqual(names);
const saved = JSON.parse(localStorage.getItem('vacationRules')!).rules;
expect(saved.map(({ name }: { name: string }) => name)).toEqual(names);
expect(saved[0].enabled).toBe(false);
});
it('saves the migrated list and version in one atomic write and retries after a failed save', () => {
localStorage.setItem('vacationRules', '[]');
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+57
View File
@@ -5,6 +5,7 @@ import {
IfThenRule,
TimeWindowRule,
OptimizationRule,
VacationRule,
} from './rule-service';
import { SelectableDayType } from './calendar-service';
import { OPTIMIZATION_PRESETS } from './planning-objectives';
@@ -182,4 +183,60 @@ describe('RuleService', () => {
vi.useRealTimers();
}
});
describe('replacing the whole rule set', () => {
const shared = (): VacationRule[] => [
{
id: 'shared-window',
name: 'Shared window',
type: RuleType.TIME_WINDOW,
enabled: false,
force: 'obligation',
startDate: new Date(2026, 6, 1),
endDate: new Date(2026, 6, 15),
placeDays: 3,
placeType: SelectableDayType.CP,
},
{
id: 'shared-loss',
name: 'Shared loss priority',
type: RuleType.OPTIMIZATION,
enabled: true,
force: 'preference',
configuration: structuredClone(OPTIMIZATION_PRESETS.unplacedAtRisk),
},
];
const reload = (): RuleService => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({});
return TestBed.inject(RuleService);
};
it('replaces every rule in order and keeps the new rule set after a reload', () => {
service.replaceRuleSet(shared());
expect(service.rules).toEqual(shared());
expect(reload().rules).toEqual(shared());
});
it('saves the replacement and later edits when the saved rules were unreadable at startup', () => {
localStorage.setItem('vacationRules', 'not a rule list');
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
service = reload();
service.toggleRule('default-samedi-malin');
// The guard: an edit must not replace saved rules that could not be read.
expect(localStorage.getItem('vacationRules')).toBe('not a rule list');
service.replaceRuleSet(shared());
expect(reload().rules).toEqual(shared());
service.toggleRule('shared-loss');
const edited = shared();
edited[1].enabled = false;
expect(reload().rules).toEqual(edited);
} finally {
warn.mockRestore();
}
});
});
});
+59 -28
View File
@@ -55,36 +55,51 @@ type SerializedRule =
})
| (Omit<OptimizationRule, 'force'> & { force?: 'preference' });
/** Each preset: key, name, the name it was first saved under, configuration. */
const PRESETS = [
[
'unplaced-at-risk',
'Éviter de perdre des jours',
'Prévention des pertes',
OPTIMIZATION_PRESETS.unplacedAtRisk,
],
[
'holiday-week-value',
'Semaines avec un jour férié',
'Semaines fériées',
OPTIMIZATION_PRESETS.holidayWeekValue,
],
[
'non-working-day-gain',
'Ponts et week-ends prolongés',
'Gain de jours non ouvrés',
OPTIMIZATION_PRESETS.nonWorkingDayGain,
],
[
'longest-work-sequence',
'Éviter les longues périodes sans congé',
'Séquence de travail maximale',
OPTIMIZATION_PRESETS.longestWorkSequence,
],
[
'short-sequence-deficit',
'Éviter les reprises trop courtes',
'Déficit des reprises',
OPTIMIZATION_PRESETS.shortSequenceDeficit,
],
[
'supporting-placements',
'Garder des jours pour plus tard',
'Économie des jours d’appoint',
OPTIMIZATION_PRESETS.supportingPlacements,
],
] as const;
export function createOptimizationPresetRules(
existingIds: readonly string[] = [],
): OptimizationRule[] {
const ids = new Set(existingIds);
return (
[
['unplaced-at-risk', 'Prévention des pertes', OPTIMIZATION_PRESETS.unplacedAtRisk],
['holiday-week-value', 'Semaines fériées', OPTIMIZATION_PRESETS.holidayWeekValue],
[
'non-working-day-gain',
'Gain de jours non ouvrés',
OPTIMIZATION_PRESETS.nonWorkingDayGain,
],
[
'longest-work-sequence',
'Séquence de travail maximale',
OPTIMIZATION_PRESETS.longestWorkSequence,
],
[
'short-sequence-deficit',
'Déficit des reprises',
OPTIMIZATION_PRESETS.shortSequenceDeficit,
],
[
'supporting-placements',
'Économie des jours d’appoint',
OPTIMIZATION_PRESETS.supportingPlacements,
],
] as const
).map<OptimizationRule>(([key, name, configuration]) => {
return PRESETS.map<OptimizationRule>(([key, name, , configuration]) => {
const base = `default-${key}`;
let id = base;
let suffix = 2;
@@ -101,6 +116,14 @@ export function createOptimizationPresetRules(
});
}
/** A saved preset still under its first name takes the current one; a name the person chose stays. */
function withCurrentPresetName(rule: SerializedRule): SerializedRule {
const preset = PRESETS.find(
([key, , former]) => rule.name === former && rule.id.startsWith(`default-${key}`),
);
return preset ? { ...rule, name: preset[1] } : rule;
}
function isRuleList(value: unknown): value is SerializedRule[] {
return (
Array.isArray(value) &&
@@ -168,8 +191,9 @@ export class RuleService {
'rules' in parsed &&
isRuleList(parsed.rules)
) {
rules = parsed.rules;
migrate = false;
const saved: SerializedRule[] = parsed.rules;
rules = saved.map(withCurrentPresetName);
migrate = rules.some((rule, index) => rule !== saved[index]);
} else throw new Error('Unsupported saved rule format.');
}
} catch (error) {
@@ -221,6 +245,13 @@ export class RuleService {
});
}
/** Replaces the whole rule set, as a confirmed import of a shared rule set does (ADR 0014). */
public replaceRuleSet(rules: VacationRule[]): void {
// The person accepted the replacement: saved rules that could not be read may now be overwritten.
this.canPersist = true;
this.updateRules(() => structuredClone(rules));
}
public addRule(rule: VacationRule): void {
const saved = structuredClone(rule);
saved.force ??= 'preference';
+268
View File
@@ -0,0 +1,268 @@
import { afterEach, describe, expect, it } from 'bun:test';
import { deflateRawSync } from 'node:zlib';
import { SelectableDayType } from './calendar-service';
import { OPTIMIZATION_PRESETS } from './planning-objectives';
import { decodeRuleSetLink, encodeRuleSetLink } from './rule-set-link';
import {
RuleType,
type IfThenRule,
type OptimizationRule,
type TimeWindowRule,
type VacationRule,
} from './rule-service';
/** Built on demand: its TIME_WINDOW boundaries are local midnights of the time zone in force. */
const ruleSet = (): VacationRule[] => [
{
id: 'bridge',
name: 'Samedi Malin',
type: RuleType.IF_THEN,
enabled: true,
force: 'obligation',
dayOfWeek: 6,
placeDays: 2,
placeType: SelectableDayType.CP,
placement: 'auto',
rewardDays: 1,
rewardType: SelectableDayType.OTHER,
},
{
id: 'christmas',
name: 'Vacances de Noël',
type: RuleType.TIME_WINDOW,
enabled: false,
force: 'preference',
startDate: new Date(2026, 11, 20),
endDate: new Date(2027, 0, 3),
placeDays: 5,
placeType: SelectableDayType.ANY,
},
{
id: 'deficit',
name: 'Déficit des reprises',
type: RuleType.OPTIMIZATION,
enabled: true,
force: 'preference',
configuration: structuredClone(OPTIMIZATION_PRESETS.shortSequenceDeficit),
},
];
/** The link of ruleSet() as version 1 first published it. It must keep decoding: links already sent rely on it. */
const GOLDEN_V1_FRAGMENT =
'dZLNTuwwDIVfpfI6lWaKACnr2cJdXAQLhJAncVuL_BQnZVRG80DoPgYvdpWZjgoSLH1iO-ezvYc3ksQxgF4rkNFRAv24B7agYStsOwIFAT2Bhr_oyXJ1g44DKKCAW0cWdJaRFLRRTMmKW8cd5tJTQZ6GonH7nHsqgsXpT_tA9AL6SsHg0NAGpwS6maO7U4UZYBY8hQwacMwRFAjtUOypZH0O55qYexI4qNm-6YVT9pgWgns0GAylylJ1Gz__ua8YLbr0hWMQakkoGFo4Mnt63nGwcQcKUkbJG8zlpVk1V_W6qZvVsaVd5Ot6ta5XF2eck_XL77QYpsW3pZYN58X15vPjqFSWUiU0CCcqUL8s4Cfjccjs-f28FhNDy90op1jvgdxxzgk07KK81Ilex9KhfGNisFwSy2kAh0wSsEwuxFCTH_IETwo8YRql_PWtQb3Q5F4o9dHN27tUgF0nNN-KhjT6ciAsZGbFcyiuCQ6Hp8N_';
const [ifThen, christmas, optimization] = ruleSet() as [
IfThenRule,
TimeWindowRule,
OptimizationRule,
];
const timeWindow = { ...christmas, startDate: '2026-12-20', endDate: '2027-01-03' };
/** A link fragment made without the module, so that it can carry what encoding refuses. */
const fragment = (envelope: unknown): string =>
deflateRawSync(JSON.stringify(envelope)).toString('base64url');
const fragmentOf = (link: string): string => link.slice(link.indexOf('#rules=') + 7);
async function linkOf(rules: readonly VacationRule[]): Promise<string> {
const result = await encodeRuleSetLink(rules);
if (!('link' in result)) throw new Error('The rule set was refused.');
return result.link;
}
const timeZone = process.env.TZ;
afterEach(() => {
if (timeZone === undefined) delete process.env.TZ;
else process.env.TZ = timeZone;
});
describe('rule set link', () => {
it('links to the app root with the rule set in the rules fragment parameter', async () => {
expect(await linkOf(ruleSet())).toMatch(/^http:\/\/localhost:3000\/#rules=[\w-]+$/);
});
it('round-trips a rule set with its order, forces, enabled states and parameters', async () => {
expect(await decodeRuleSetLink(fragmentOf(await linkOf(ruleSet())))).toEqual(ruleSet());
});
it('keeps the calendar dates of a rule window in another time zone', async () => {
process.env.TZ = 'Pacific/Kiritimati';
const link = await linkOf(ruleSet());
process.env.TZ = 'America/Los_Angeles';
const decoded = await decodeRuleSetLink(fragmentOf(link));
expect(decoded).toEqual(ruleSet());
expect(decoded?.[1]).toMatchObject({
startDate: new Date('2026-12-20T08:00:00Z'),
endDate: new Date('2027-01-03T08:00:00Z'),
});
});
it('encodes a legacy rule without force as a preference', async () => {
const { force: _, ...legacy } = ifThen;
const decoded = await decodeRuleSetLink(fragmentOf(await linkOf([legacy])));
expect(decoded).toEqual([{ ...legacy, force: 'preference' }]);
});
it('keeps decoding the golden v1 fragment', async () => {
expect(await decodeRuleSetLink(GOLDEN_V1_FRAGMENT)).toEqual(ruleSet());
});
it('names the first rule that cannot be shared instead of returning a link', async () => {
const reversed: VacationRule = {
...christmas,
id: 'reversed',
name: 'Fenêtre inversée',
enabled: false,
startDate: new Date(2027, 0, 3),
endDate: new Date(2026, 11, 20),
};
const duplicate = { ...optimization, name: 'Doublon' };
expect(await encodeRuleSetLink([ifThen, reversed, { ...ifThen, name: '' }])).toEqual({
unshareableRule: { id: 'reversed', name: 'Fenêtre inversée' },
});
expect(await encodeRuleSetLink([optimization, ifThen, duplicate])).toEqual({
unshareableRule: { id: 'deficit', name: 'Doublon' },
});
});
it('names the rule that takes a rule set past what a link may carry', async () => {
const rules = Array.from({ length: 101 }, (_, index) => ({
...ifThen,
id: `rule-${index}`,
}));
expect(await decodeRuleSetLink(fragmentOf(await linkOf(rules.slice(0, 100))))).toHaveLength(
100,
);
expect(await encodeRuleSetLink(rules)).toEqual({
unshareableRule: { id: 'rule-100', name: ifThen.name },
});
const long = { ...optimization, name: 'é'.repeat(40_000) };
expect(await encodeRuleSetLink([ifThen, long])).toEqual({
unshareableRule: { id: long.id, name: long.name },
});
});
it('drops the unknown fields of an accepted rule', async () => {
const decoded = await decodeRuleSetLink(
fragment({
version: 1,
note: 'ignored',
rules: [
{ ...ifThen, startDate: '2026-12-20', html: '<b>x</b>' },
{ ...timeWindow, dayOfWeek: 2, configuration: optimization.configuration },
{ ...optimization, placeDays: 3 },
],
}),
);
expect(decoded).toStrictEqual(ruleSet());
expect(decoded?.map((rule) => Object.keys(rule).sort())).toEqual(
ruleSet().map((rule) => Object.keys(rule).sort()),
);
});
it('refuses an IF_THEN rule without an earned leave type, even when it earns nothing', async () => {
const { rewardType: _, ...unrewarded } = { ...ifThen, rewardDays: 0 };
expect(await decodeRuleSetLink(fragment({ version: 1, rules: [unrewarded] }))).toBeNull();
});
it.each<[string, string]>([
['an empty value', ''],
['a value outside the base64url alphabet', `${GOLDEN_V1_FRAGMENT}=`],
['standard base64', deflateRawSync('{"version":1,"rules":[]}?>').toString('base64')],
[
'a truncated stream',
deflateRawSync(JSON.stringify({ version: 1, rules: [ifThen, timeWindow] }))
.subarray(0, -4)
.toString('base64url'),
],
['bytes that are not a deflate stream', Buffer.from('not deflate').toString('base64url')],
['a stream that is not JSON', deflateRawSync('rules').toString('base64url')],
[
'a stream that is not UTF-8',
deflateRawSync(Buffer.from([0x22, 0xff, 0x22])).toString('base64url'),
],
])('refuses %s', async (_, value) => {
expect(await decodeRuleSetLink(value)).toBeNull();
});
it('promptly refuses a payload that inflates to 50 MB', async () => {
const envelope = JSON.stringify({ version: 1, rules: [ifThen] });
// Trailing white space keeps the JSON valid: only the size limit can refuse it.
const value = deflateRawSync(envelope.padEnd(50 * 1024 * 1024)).toString('base64url');
const start = performance.now();
expect(await decodeRuleSetLink(value)).toBeNull();
expect(performance.now() - start).toBeLessThan(1000);
expect(
await decodeRuleSetLink(
deflateRawSync(envelope.padEnd(64 * 1024)).toString('base64url'),
),
).toEqual([ifThen]);
expect(
await decodeRuleSetLink(
deflateRawSync(envelope.padEnd(64 * 1024 + 1)).toString('base64url'),
),
).toBeNull();
});
it.each<[string, unknown]>([
['a version other than the number 1', { version: 2, rules: [ifThen] }],
['a version given as text', { version: '1', rules: [ifThen] }],
['a missing version', { rules: [ifThen] }],
['rules that are not a list', { version: 1, rules: { 0: ifThen, length: 1 } }],
['an envelope that is not an object', null],
[
'more than 100 rules',
{
version: 1,
rules: Array.from({ length: 101 }, (_, index) => ({ ...ifThen, id: `${index}` })),
},
],
['a duplicate id', { version: 1, rules: [ifThen, { ...timeWindow, id: ifThen.id }] }],
])('refuses %s', async (_, envelope) => {
expect(await decodeRuleSetLink(fragment(envelope))).toBeNull();
});
it.each<[string, unknown]>([
['a rule that is not an object', 'rule'],
['a missing rule', null],
['an empty id', { ...ifThen, id: '' }],
['a non-string id', { ...ifThen, id: 7 }],
['a missing name', { ...ifThen, name: undefined }],
['a blank name', { ...ifThen, name: ' \t' }],
['a non-string name', { ...ifThen, name: 42 }],
['a non-boolean enabled', { ...ifThen, enabled: 'true' }],
['a missing enabled', { ...ifThen, enabled: undefined }],
['an unknown type', { ...ifThen, type: 'bonus' }],
['a wrong-case type', { ...ifThen, type: 'IF_THEN' }],
['a wrong-case force', { ...ifThen, force: 'OBLIGATION' }],
['a missing force', { ...ifThen, force: undefined }],
['an optimization obligation', { ...optimization, force: 'obligation' }],
['a weekday of 9 on a disabled rule', { ...ifThen, enabled: false, dayOfWeek: 9 }],
['a fractional weekday', { ...ifThen, dayOfWeek: 1.5 }],
['a negative quantity', { ...ifThen, placeDays: -1 }],
['a quantity given as text', { ...timeWindow, placeDays: '5' }],
['a wrong-case leave selector', { ...ifThen, placeType: 'CP' }],
['an unknown leave selector', { ...timeWindow, placeType: 'sick' }],
['an unknown placement', { ...ifThen, placement: 'near' }],
['a negative earned quantity', { ...ifThen, rewardDays: -1 }],
['any as the earned leave type', { ...ifThen, rewardType: 'any' }],
[
'any as the earned leave type of a rule that earns nothing',
{ ...ifThen, rewardDays: 0, rewardType: 'any' },
],
['an earned quantity without its leave type', { ...ifThen, rewardType: undefined }],
['a date with a suffix', { ...timeWindow, startDate: '2026-12-20T00:00:00.000Z' }],
['an impossible date', { ...timeWindow, endDate: '2027-02-30' }],
['a date that is not text', { ...timeWindow, endDate: 1798934400000 }],
['a reversed window', { ...timeWindow, startDate: '2027-01-03', endDate: '2026-12-20' }],
['a missing optimization configuration', { ...optimization, configuration: undefined }],
[
'an invalid optimization configuration',
{ ...optimization, configuration: { ...optimization.configuration, direction: 'up' } },
],
])('refuses %s', async (_, rule) => {
expect(
await decodeRuleSetLink(fragment({ version: 1, rules: [timeWindow, rule] })),
).toBeNull();
});
});
+221
View File
@@ -0,0 +1,221 @@
import dayjs from 'dayjs';
import { SelectableDayType } from './calendar-service';
import { normalizeRules } from './leave-planner.core';
import { isPlanningDate } from './planning-date';
import { validateOptimizationConfiguration } from './planning-objectives';
import {
RuleType,
type IfThenRule,
type OptimizationRule,
type PlacementStrategy,
type RuleForce,
type TimeWindowRule,
type VacationRule,
} from './rule-service';
/**
* A rule set shared through a link (ADR 0014): the app root with a `rules` fragment parameter
* holding `{ version: 1, rules }` as JSON, compressed with raw deflate and encoded in base64url.
* The envelope is a public contract: every published version must stay decodable.
*/
export type RuleSetLink = { link: string } | { unshareableRule: { id: string; name: string } };
/** A rule as it travels: canonical values, known fields only, TIME_WINDOW boundaries as calendar dates. */
type WireRule =
| IfThenRule
| (Omit<TimeWindowRule, 'startDate' | 'endDate'> & { startDate: string; endDate: string })
| OptimizationRule;
const MAX_RULES = 100;
const MAX_BYTES = 64 * 1024;
const FORCES: readonly RuleForce[] = ['obligation', 'preference'];
const PLACEMENTS: readonly PlacementStrategy[] = ['before', 'after', 'around', 'auto'];
const SELECTORS = Object.values(SelectableDayType);
const LEAVE_TYPES = SELECTORS.filter((type) => type !== SelectableDayType.ANY);
const isOneOf = <T>(values: readonly T[], value: unknown): value is T =>
values.includes(value as T);
const isCount = (value: unknown): value is number =>
Number.isInteger(value) && (value as number) >= 0;
/** The rule in its canonical form, or null when it may not travel in a link. */
function canonicalRule(value: unknown): WireRule | null {
if (typeof value !== 'object' || value === null) return null;
const { id, name, type, enabled, force, ...fields } = value as Record<string, unknown>;
if (
typeof id !== 'string' ||
!id ||
typeof name !== 'string' ||
!name.trim() ||
typeof enabled !== 'boolean' ||
!isOneOf(FORCES, force)
)
return null;
const base = { id, name, enabled, force };
let rule: WireRule;
if (type === RuleType.IF_THEN) {
const { dayOfWeek, placeDays, placeType, placement, rewardDays, rewardType } = fields;
if (
!isCount(dayOfWeek) ||
dayOfWeek > 6 ||
!isCount(placeDays) ||
!isOneOf(SELECTORS, placeType) ||
!isOneOf(PLACEMENTS, placement) ||
!isCount(rewardDays) ||
!isOneOf(LEAVE_TYPES, rewardType)
)
return null;
rule = {
...base,
type,
dayOfWeek,
placeDays,
placeType,
placement,
rewardDays,
rewardType,
};
} else if (type === RuleType.TIME_WINDOW) {
const { startDate, endDate, placeDays, placeType } = fields;
if (
!isPlanningDate(startDate) ||
!isPlanningDate(endDate) ||
startDate > endDate ||
!isCount(placeDays) ||
!isOneOf(SELECTORS, placeType)
)
return null;
rule = { ...base, type, startDate, endDate, placeDays, placeType };
} else if (type === RuleType.OPTIMIZATION) {
const validated = validateOptimizationConfiguration(fields['configuration']);
if (force !== 'preference' || !validated.valid) return null;
rule = { ...base, type, force, configuration: validated.configuration };
} else return null;
// The planner coerces case and tolerates a missing name, so it only ever sees a canonical rule.
// It skips disabled rules, which a shared rule set checks too.
return normalizeRules([{ ...rule, enabled: true }]).reasons.length ? null : rule;
}
/** The canonical rules, or the position of the first rule that may not travel in a link. */
function canonicalRuleSet(rules: readonly unknown[]): WireRule[] | number {
const ids = new Set<string>();
const canonical: WireRule[] = [];
for (const [index, value] of rules.entries()) {
const rule = index < MAX_RULES ? canonicalRule(value) : null;
if (!rule || ids.has(rule.id)) return index;
ids.add(rule.id);
canonical.push(rule);
}
return canonical;
}
const envelope = (rules: readonly WireRule[]): Uint8Array =>
new TextEncoder().encode(JSON.stringify({ version: 1, rules }));
/** Feeds a compression stream in small slices, so that it stops soon after its output exceeds the limit. */
async function pump(
bytes: Uint8Array,
through: GenericTransformStream,
limit = Infinity,
): Promise<Uint8Array> {
let offset = 0;
const reader = new ReadableStream<Uint8Array>({
pull(controller) {
if (offset < bytes.length) controller.enqueue(bytes.subarray(offset, (offset += 1024)));
else controller.close();
},
})
.pipeThrough<Uint8Array>(through)
.getReader();
const chunks: Uint8Array[] = [];
let size = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
size += value.length;
if (size > limit) {
await reader.cancel();
throw new RangeError('The stream exceeds its size limit.');
}
chunks.push(value);
}
const output = new Uint8Array(size);
let position = 0;
for (const chunk of chunks) {
output.set(chunk, position);
position += chunk.length;
}
return output;
}
/**
* Encodes the rules, as `RuleService.rules` exposes them, into a share link, or names the
* first rule that cannot be shared, so that nobody sends a link that cannot be opened.
*/
export async function encodeRuleSetLink(rules: readonly VacationRule[]): Promise<RuleSetLink> {
const unshareable = (index: number): RuleSetLink => ({
unshareableRule: { id: rules[index].id, name: rules[index].name },
});
const canonical = canonicalRuleSet(
rules.map((rule) => ({
...rule,
force: rule.force ?? 'preference',
...(rule.type === RuleType.TIME_WINDOW && {
startDate: dayjs(rule.startDate).format('YYYY-MM-DD'),
endDate: dayjs(rule.endDate).format('YYYY-MM-DD'),
}),
})),
);
if (typeof canonical === 'number') return unshareable(canonical);
const json = envelope(canonical);
if (json.length > MAX_BYTES)
// The rule to name is the one that takes the set past the size decoding accepts.
return unshareable(
canonical.findIndex(
(_, index) => envelope(canonical.slice(0, index + 1)).length > MAX_BYTES,
),
);
const deflated = await pump(json, new CompressionStream('deflate-raw'));
const payload = btoa(Array.from(deflated, (byte) => String.fromCharCode(byte)).join(''))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
return { link: new URL(`#rules=${payload}`, document.baseURI).href };
}
/**
* Decodes the value of a link's `rules` fragment parameter into a rule set ready for
* `RuleService`, or returns null when the link is invalid. All or nothing.
*/
export async function decodeRuleSetLink(value: string): Promise<VacationRule[] | null> {
try {
if (!/^[\w-]+$/.test(value)) return null;
const deflated = Uint8Array.from(
atob(value.replace(/-/g, '+').replace(/_/g, '/')),
(char) => char.charCodeAt(0),
);
const json = await pump(deflated, new DecompressionStream('deflate-raw'), MAX_BYTES);
const parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(json)) as {
version?: unknown;
rules?: unknown;
} | null;
if (parsed?.version !== 1 || !Array.isArray(parsed.rules)) return null;
const canonical = canonicalRuleSet(parsed.rules);
if (typeof canonical === 'number') return null;
return canonical.map(
(rule): VacationRule =>
rule.type === RuleType.TIME_WINDOW
? {
...rule,
// Local midnight, never new Date('YYYY-MM-DD'), which is a UTC instant.
startDate: new Date(`${rule.startDate}T00:00:00`),
endDate: new Date(`${rule.endDate}T00:00:00`),
}
: rule,
);
} catch {
// Not base64, not a complete deflate stream, too large, not UTF-8 or not JSON.
return null;
}
}
+71 -32
View File
@@ -6,9 +6,10 @@ import type {
RemainingBalance,
} from './leave-planner.service';
import { addPlanningDays } from './planning-date';
import { optimizationSummary } from './planner-labels';
import type { SelectableDayType } from './calendar-service';
import type { PlacementStrategy } from './rule-service';
import {
type OptimizationConfiguration,
type OPTIMIZATION_PRESETS,
type OptimizationElements,
type OptimizationCondition,
type OptimizationMeasure,
@@ -16,6 +17,12 @@ import {
type OptimizationDirection,
} from './planning-objectives';
/** A text for one item and a text for several, each with a {count} placeholder. */
export interface PluralForms {
one: string;
other: string;
}
export interface AppTranslations {
locale: string;
bookedDays: {
@@ -32,11 +39,15 @@ export interface AppTranslations {
title: string;
description: string;
skipToPlan: string;
view: string;
configuration: string;
plan: string;
};
userInput: {
title: string;
description: string;
addVacationDay: string;
emptyBalances: string;
calculate: string;
durationEstimate: string;
durationUnits: { seconds: string; minutes: string };
@@ -103,17 +114,30 @@ export interface AppTranslations {
measures: Record<OptimizationMeasure, string>;
aggregations: Record<OptimizationAggregation, string>;
directions: Record<OptimizationDirection, string>;
plain: {
goals: Record<OptimizationDirection, string>;
intents: Record<keyof typeof OPTIMIZATION_PRESETS, string>;
count: string;
elements: Record<OptimizationElements, string>;
quantities: Record<OptimizationMeasure, Record<'sum' | 'maximum', string>>;
scopes: Record<OptimizationCondition, string>;
workingDays: PluralForms;
};
};
title: string;
subtitle: string;
active: string;
active: PluralForms;
moveRuleUp: string;
moveRuleDown: string;
dragRule: string;
ruleMoved: string;
priorityInfo: string;
ifThenTemplate: string;
ifThenEarned: string;
timeWindowTemplate: string;
dayCount: PluralForms;
summaryTypes: Record<SelectableDayType, string>;
summaryPlacement: Record<PlacementStrategy, string>;
editRule: string;
deleteRule: string;
addRule: string;
@@ -132,11 +156,24 @@ export interface AppTranslations {
cancel: string;
save: string;
add: string;
addRuleButton: string;
newIfThenRule: string;
newTimeWindowRule: string;
defaultNewRuleName: string;
defaultNewPeriodName: string;
import: {
title: string;
replaceStatement: string;
accept: string;
disabled: string;
invalidLink: string;
};
share: {
action: string;
title: string;
copied: string;
copyFailed: string;
invalidRule: string;
};
daysOfWeek: {
1: string;
2: string;
@@ -157,18 +194,29 @@ export interface AppTranslations {
statistics: {
open: string;
title: string;
leaveDays: string;
averageWorkSequence: string;
averageTimeOffPeriod: string;
longestTimeOffPeriod: string;
weekendConnectedHolidays: string;
earnedLeave: string;
earnedLeaveByRule: string;
leaveDaysUnit: string;
workingDays: string;
calendarDays: string;
partialPlan: string;
help: string;
leaveDays: string;
outOf: string;
unplaced: string;
unplacedDays: PluralForms;
lostDays: PluralForms;
lostHelp: string;
keptHelp: string;
daysOff: string;
weekendAndHolidayDays: PluralForms;
periods: string;
longestPeriod: PluralForms;
longestWorkSequence: string;
workedDays: PluralForms;
bridgedHolidays: string;
earnedLeave: string;
oneWorkdayWeeks: PluralForms;
oneWorkdayHelp: string;
onlyWorkday: string;
/** Units of the technical composition of an optimization rule. */
workingDays: string;
calendarDays: string;
};
calculationDate: string;
futureEntitlement: string;
@@ -188,7 +236,6 @@ export interface AppTranslations {
datePlaceholder: string;
};
details: {
intro: string;
balance: string;
available: string;
expires: string;
@@ -205,10 +252,11 @@ export interface AppTranslations {
};
explanation: {
breakTitle: string;
leaveDays: string;
freeDays: string;
daysOff: string;
wholeBreak: string;
/** The terms of a time-off period's sum; each follows its number. */
bookedDays: PluralForms;
leaveDays: PluralForms;
freeDays: PluralForms;
daysOff: PluralForms;
leaveUsed: string;
expires: string;
linkedRules: string;
@@ -219,7 +267,6 @@ export interface AppTranslations {
withoutDay: string;
withDay: string;
noChange: string;
priorityHelp: string;
tryDate: string;
plannedDate: string;
currentPlan: string;
@@ -227,20 +274,20 @@ export interface AppTranslations {
sameDate: string;
moveHelp: string;
comparisonUnavailable: string;
objectives: Record<string, { label: string; help: string }>;
objectives: Record<string, { label: string; help?: string }>;
preferenceHelp: Record<string, string | undefined>;
stages: Record<string, string>;
unavailable: Record<string, string | undefined>;
};
title: string;
invitation: string;
calendarHelp: string;
explanationHelp: string;
technicalDetails: string;
appliedRules: { title: string; entries: string };
timeOffPeriods: { title: string; count: string; help: string };
compareDates: string;
stopComparing: string;
daysPlaced: string;
daysGained: string;
longestWorkSequence: string;
legend: string;
invalidInput: string;
conflict: string;
@@ -261,14 +308,12 @@ export interface AppTranslations {
whyPlacement: string;
placementNavigation: string;
placement: string;
placements: string;
of: string;
first: string;
previous: string;
next: string;
last: string;
remaining: string;
balanceRemaining: string;
counterfactual: string;
counterfactualLoading: string;
counterfactualReady: string;
@@ -276,7 +321,6 @@ export interface AppTranslations {
retryCounterfactual: string;
eligible: string;
ineligible: string;
reason: string;
explanationError: string;
// Interruption codes are required in every language; conflict codes stay optional.
reasons: Record<InterruptionReasonCode, string> & Record<string, string | undefined>;
@@ -315,7 +359,6 @@ export interface AppTranslations {
yearRangeLabel: string;
};
loading: string;
weekdaysShort: string[];
}
import { translationsMap, availableLanguagesList } from '../i18n-registry';
@@ -378,10 +421,6 @@ export class TranslationService {
}
}
public optimizationSummary(configuration: OptimizationConfiguration): string {
return optimizationSummary(this.tr(), configuration);
}
public getLanguageName(langCode: string): string {
try {
// Using native Intl.DisplayNames to get name of language in its own language
+32 -58
View File
@@ -135,21 +135,23 @@ describe('UserInputService', () => {
expect(warn).toHaveBeenCalled();
});
it('should initialize with vacation days array', () => {
const vacations = service.vacationNumberSignal();
expect(Array.isArray(vacations)).toBe(true);
expect(vacations.length).toBeGreaterThan(0);
it('starts a first visit from an empty, unsaved balance list without drawing quantities', () => {
const random = vi.spyOn(Math, 'random');
expect(new UserInputService().vacationNumberSignal()).toEqual([]);
expect(random).not.toHaveBeenCalled();
expect(localStorage.getItem('leaveBalances')).toBeNull();
});
it('should have vacation days with valid properties', () => {
const vacations = service.vacationNumberSignal();
vacations.forEach((day) => {
expect(day.id).toBeDefined();
expect(day.type).toBeDefined();
expect(day.numberOfDays).toBeGreaterThanOrEqual(10);
expect(day.numberOfDays).toBeLessThanOrEqual(20);
expect(day.expiryDate).toBeInstanceOf(Date);
});
it('has nothing to plan only without a leave balance and without a declared non-working day', () => {
expect(service.nothingToPlan()).toBe(true);
service.toggleDeclaredDay('2024-01-02', 'cp');
expect(service.nothingToPlan()).toBe(false);
service.toggleDeclaredDay('2024-01-02', 'cp');
expect(service.nothingToPlan()).toBe(true);
service.updateBalances(() => [service.createVacationDay()]);
expect(service.nothingToPlan()).toBe(false);
localStorage.setItem('leaveBalances', '[]');
expect(new UserInputService().nothingToPlan()).toBe(true);
});
it('restores the saved balance order, identities, quantities, types, and calendar dates', () => {
@@ -240,32 +242,23 @@ describe('UserInputService', () => {
'mixed supported and unsupported records',
JSON.stringify([savedBalance, { ...savedBalance, type: 'any' }]),
],
])(
'deletes only unreadable balance data (%s) before using unsaved random defaults',
(_, saved) => {
vi.spyOn(console, 'warn').mockImplementation(() => {});
vi.spyOn(Math, 'random').mockReturnValue(0.5);
const unrelated = {
'theme.preference': '"dark"',
'app.language': '"fr"',
'calendarSettings.showWeekNumbers': 'true',
vacationRules: '[]',
'unrelated.entry': 'keep this value',
};
for (const [key, value] of Object.entries(unrelated)) localStorage.setItem(key, value);
localStorage.setItem('leaveBalances', saved);
])('deletes only unreadable balance data (%s) and starts from an empty list', (_, saved) => {
vi.spyOn(console, 'warn').mockImplementation(() => {});
const unrelated = {
'theme.preference': '"dark"',
'app.language': '"fr"',
'calendarSettings.showWeekNumbers': 'true',
vacationRules: '[]',
'unrelated.entry': 'keep this value',
};
for (const [key, value] of Object.entries(unrelated)) localStorage.setItem(key, value);
localStorage.setItem('leaveBalances', saved);
const balances = new UserInputService().vacationNumberSignal();
expect(balances.map((balance) => [balance.type, balance.numberOfDays])).toEqual([
[SelectableDayType.CP, 15],
[SelectableDayType.RTT, 15],
[SelectableDayType.OTHER, 15],
]);
expect(localStorage.getItem('leaveBalances')).toBeNull();
for (const [key, value] of Object.entries(unrelated))
expect(localStorage.getItem(key)).toBe(value);
},
);
expect(new UserInputService().vacationNumberSignal()).toEqual([]);
expect(localStorage.getItem('leaveBalances')).toBeNull();
for (const [key, value] of Object.entries(unrelated))
expect(localStorage.getItem(key)).toBe(value);
});
it('keeps saved data intact when browser storage temporarily cannot be read', () => {
const saved = JSON.stringify([savedBalance]);
@@ -275,30 +268,11 @@ describe('UserInputService', () => {
throw new DOMException('Storage is unavailable', 'SecurityError');
});
expect(new UserInputService().vacationNumberSignal()).toHaveLength(3);
expect(new UserInputService().vacationNumberSignal()).toEqual([]);
read.mockRestore();
expect(localStorage.getItem('leaveBalances')).toBe(saved);
});
it.each([
[0, 10],
[1 - Number.EPSILON, 20],
])('starts every balance at %s random draw with %s days', (draw, expected) => {
vi.spyOn(Math, 'random').mockReturnValue(draw);
const initialBalances = new UserInputService().vacationNumberSignal();
expect(initialBalances.map((balance) => balance.numberOfDays)).toEqual([
expected,
expected,
expected,
]);
expect(initialBalances.map((balance) => balance.type)).toEqual([
SelectableDayType.CP,
SelectableDayType.RTT,
SelectableDayType.OTHER,
]);
expect(localStorage.getItem('leaveBalances')).toBeNull();
});
it('should update vacation number signal', () => {
const newVacations: LeaveBalance[] = [
{
+6 -36
View File
@@ -1,4 +1,4 @@
import { Injectable, signal } from '@angular/core';
import { computed, Injectable, signal } from '@angular/core';
import { SelectableDayType } from './calendar-service';
import dayjs from 'dayjs';
import {
@@ -118,45 +118,13 @@ export class UserInputService {
try {
localStorage.removeItem('leaveBalances');
} catch {
// Keep the random fallback usable when browser storage is unavailable.
// Keep the empty list usable when browser storage is unavailable.
}
}
}
return undefined;
}
private getRandomNumber(): number {
return Math.floor(Math.random() * 11) + 10;
}
private getInitialValues(): LeaveBalance[] {
const availableDate = new Date();
return [
{
id: crypto.randomUUID(),
type: SelectableDayType.CP,
numberOfDays: this.getRandomNumber(),
availableDate,
// today + 365 days
expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
},
{
id: crypto.randomUUID(),
type: SelectableDayType.RTT,
numberOfDays: this.getRandomNumber(),
availableDate: new Date(availableDate),
expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
},
{
id: crypto.randomUUID(),
type: SelectableDayType.OTHER,
numberOfDays: this.getRandomNumber(),
availableDate: new Date(availableDate),
expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
},
];
}
public createVacationDay(): LeaveBalance {
return {
id: crypto.randomUUID(),
@@ -167,8 +135,10 @@ export class UserInputService {
};
}
readonly vacationNumberSignal = signal<LeaveBalance[]>(
this.getSavedValues() ?? this.getInitialValues(),
readonly vacationNumberSignal = signal<LeaveBalance[]>(this.getSavedValues() ?? []);
/** No leave balance and no declared non-working day: nothing is calculated until one is added. */
readonly nothingToPlan = computed(
() => !this.vacationNumberSignal().length && !this.declaredDays().length,
);
public updateBalances(updater: (balances: LeaveBalance[]) => LeaveBalance[]): void {
this.vacationNumberSignal.update(updater);
+295 -159
View File
@@ -3,30 +3,34 @@
"bookedDays": {
"enter": "Bereits gebuchte Tage bearbeiten",
"booked": "Bereits gebucht",
"help": "Wählen Sie CP, RTT, Andere oder Löschen und klicken oder ziehen Sie zwischen zwei Daten, auch über mehrere Monate. Loslassen speichert; Escape bricht ab. Tage mit dem gewählten Typ werden entfernt; andere Tage erhalten diesen Typ. Wochenenden und Feiertage werden übersprungen. Schraffierte Tage sind bereits gebucht und werden beim nächsten Berechnen berücksichtigt.",
"fixed": "Feste Benutzereingabe, ohne Abzug vom verbleibenden Guthaben oder Optimierungsentscheidung.",
"removed": "Eintrag entfernt",
"help": "Wählen Sie CP, RTT, Andere oder Löschen und klicken Sie auf einen Tag oder ziehen Sie zwischen zwei Daten, auch über mehrere Monate; Escape bricht ab. Ein Tag, der bereits den gewählten Typ hat, wird entfernt; die anderen erhalten ihn. Wochenenden und Feiertage werden übersprungen. Schraffierte Tage sind bereits gebucht: Die nächste Berechnung berücksichtigt sie.",
"fixed": "Die Berechnung verschiebt bereits gebuchte Tage nicht und zieht sie nicht von Ihren Guthaben ab.",
"removed": "Bereits gebuchter Tag entfernt",
"erase": "Löschen",
"rangeSaved": "Gespeicherte bereits gebuchte Tage: {count} ({type}).",
"rangeRemoved": "Entfernte Einträge: {count}."
"rangeRemoved": "Entfernte bereits gebuchte Tage: {count}."
},
"app": {
"title": "vac-optimizer",
"description": "Mehr Raum für freie Zeit.",
"skipToPlan": "Zum Urlaubsplan"
"skipToPlan": "Zum Urlaubsplan",
"view": "Ansicht",
"configuration": "Eingaben",
"plan": "Plan"
},
"userInput": {
"title": "Urlaub konfigurieren",
"description": "Wählen Sie den Planungszeitraum und fügen Sie jedes Urlaubskonto und seinen Gültigkeitszeitraum hinzu.",
"addVacationDay": "Urlaubskonto hinzufügen",
"emptyBalances": "Noch kein Urlaubskonto. Fügen Sie unten das erste hinzu.",
"calculate": "Plan berechnen",
"durationEstimate": "Ungefähre Wartezeit: {range} {unit}",
"durationEstimate": "Geschätzte Berechnungszeit: {range} {unit}",
"durationUnits": {
"seconds": "s",
"minutes": "min"
},
"remainingDaysWarning": "{count} verbleibende Urlaubstage:",
"deleteEntry": "Eintrag löschen",
"remainingDaysWarning": "{count} noch nicht gebuchte Urlaubstage:",
"deleteEntry": "Dieses Guthaben löschen",
"chooseDate": "Gültig bis",
"availableDate": "Verfügbar ab",
"days": "Tage",
@@ -38,11 +42,11 @@
"remainingHorizon": "Berechneter Plan vom {start} bis zum {end}.",
"remainingEarnedFrom": "Durch die Regel „{rule}“ erworbener Urlaub.",
"remainingSuggestions": {
"available-after-horizon": "Sie können den Planungszeitraum über das Verfügbarkeitsdatum hinaus verlängern und neu berechnen.",
"available-after-horizon": "Um es zu nutzen, verlängern Sie den Planungszeitraum über sein Verfügbarkeitsdatum hinaus und berechnen Sie dann neu.",
"no-working-date": "Prüfen Sie den Planungszeitraum und die Gültigkeitsdaten dieses Urlaubskontos.",
"all-dates-occupied": "Sie können den Zeitraum bei entsprechender Gültigkeit verlängern oder Ihre bereits gebuchten Tage und Regeln anpassen und neu berechnen.",
"preserved": "Keine Aktion nötig. Um die Nutzung anzufordern, fügen Sie eine Regel innerhalb der Gültigkeit hinzu und berechnen Sie neu.",
"calculation-incomplete": "Starten Sie die Berechnung erneut, wenn Sie die Planung abschließen möchten."
"all-dates-occupied": "Um es zu nutzen, ändern Sie Ihre bereits gebuchten Tage oder Ihre Regeln, oder verlängern Sie den Planungszeitraum, wenn dieses Guthaben danach noch gültig ist, und berechnen Sie dann neu.",
"preserved": "Nichts zu tun. Um es trotzdem zu buchen, fügen Sie eine Zeitfenster-Regel für Daten hinzu, an denen es nutzbar ist, und berechnen Sie neu.",
"calculation-incomplete": "Starten Sie die Berechnung erneut, damit sie vollständig abläuft."
}
},
"dayTypes": {
@@ -52,7 +56,7 @@
"cp": "CP",
"other": "Andere",
"today": "Heute",
"any": "Beliebig"
"any": "Beliebige Art"
},
"settings": {
"title": "Einstellungen",
@@ -69,33 +73,53 @@
"systemAppearance": "Aktuelles Systemdesign",
"planningHorizon": "Planungszeitraum",
"planningStart": "Startdatum (einschließlich)",
"lastPlanningDate": "Letzter Planungstag (einschließlich)",
"planningDatesHelp": "Wählen Sie beliebige Daten, auch vergangene. Der Kalender wird aktualisiert, wenn Sie Plan berechnen auswählen.",
"invalidDate": "Geben Sie zwei gültige Kalenderdaten ein.",
"horizonOrder": "Der letzte Planungstag muss am oder nach dem Startdatum liegen.",
"invalidHorizon": "Korrigieren Sie die Planungsdaten vor der Berechnung."
"lastPlanningDate": "Enddatum (einschließlich)",
"planningDatesHelp": "Vergangene Daten sind zulässig. Der Kalender wird bei der nächsten Berechnung aktualisiert.",
"invalidDate": "Geben Sie zwei gültige Daten ein.",
"horizonOrder": "Das Enddatum darf nicht vor dem Startdatum liegen.",
"invalidHorizon": "Korrigieren Sie zuerst die Daten des Planungszeitraums."
},
"rules": {
"title": "Planungsregeln",
"subtitle": "Urlaubsregeln konfigurieren",
"active": "aktiv",
"subtitle": "Was die Berechnung einhalten oder bevorzugen muss",
"active": {
"one": "{count} aktiv",
"other": "{count} aktiv"
},
"moveRuleUp": "Regel nach oben verschieben",
"moveRuleDown": "Regel nach unten verschieben",
"dragRule": "Zum Verschieben ziehen",
"ruleMoved": "{name}: Position {position} von {count}.",
"priorityInfo": "Die obersten Regeln haben Vorrang. Mit dem Griff oder den Pfeiltasten umsortieren.",
"ifThenTemplate": "Wenn {type} dann {placement}",
"timeWindowTemplate": "Zeitfenster {startDate} bis {endDate}",
"ifThenTemplate": "Wenn ein Feiertag auf einen <strong>{day}</strong> fällt, <strong>{placeDays}</strong> {placement} nehmen{earned}.",
"ifThenEarned": " und <strong>{earnedDays}</strong> erwerben",
"timeWindowTemplate": "<strong>{placeDays}</strong> zwischen dem <strong>{startDate}</strong> und dem <strong>{endDate}</strong> nehmen.",
"dayCount": {
"one": "{count} Tag {type}",
"other": "{count} Tage {type}"
},
"summaryTypes": {
"cp": "bezahlten Urlaub",
"rtt": "RTT",
"other": "der Art „Andere“",
"any": "beliebiger Art"
},
"summaryPlacement": {
"before": "direkt davor",
"after": "direkt danach",
"around": "auf beiden Seiten",
"auto": "bestmöglich rund um den Feiertag"
},
"editRule": "Regel bearbeiten",
"deleteRule": "Regel löschen",
"addRule": "Regel hinzufügen",
"place": "platzieren",
"place": "Nehmen",
"ruleName": "Regelname",
"holidayFalls": "Feiertag fällt auf",
"holidayFalls": "Wenn ein Feiertag auf einen",
"days": "Tage",
"type": "Typ",
"position": "Position",
"getBonus": "Bonus erhalten",
"getBonus": "erwerben",
"force": "Regelverbindlichkeit",
"obligation": "Verpflichtung",
"preference": "Präferenz",
@@ -104,25 +128,38 @@
"cancel": "Abbrechen",
"save": "Speichern",
"add": "Hinzufügen",
"addRuleButton": "Regel hinzufügen",
"newIfThenRule": "Neue Wenn-Dann-Regel",
"newIfThenRule": "Neue „Wenn … Dann“-Regel",
"newTimeWindowRule": "Neue Zeitfenster-Regel",
"defaultNewRuleName": "Neue Regel",
"defaultNewPeriodName": "Neuer Zeitraum",
"import": {
"title": "Geteilte Regeln",
"replaceStatement": "Diese Regeln ersetzen alle Ihre aktuellen Regeln ({count}). Ihre Urlaubskonten, Ihre bereits gebuchten Tage und Ihr Planungszeitraum bleiben unverändert.",
"accept": "Meine Regeln ersetzen",
"disabled": "Deaktiviert",
"invalidLink": "Dieser Freigabelink ist ungültig oder unvollständig. Ihre Regeln wurden nicht geändert."
},
"share": {
"action": "Meine Regeln teilen",
"title": "Meine VacOptimizer-Planungsregeln",
"copied": "Link kopiert",
"copyFailed": "Kopieren fehlgeschlagen",
"invalidRule": "Korrigieren Sie die Regel „{rule}“, um Ihre Regeln zu teilen."
},
"daysOfWeek": {
"0": "Sonntag",
"1": "Montag",
"2": "Dienstag",
"3": "Mittwoch",
"4": "Donnerstag",
"5": "Freitag",
"6": "Samstag",
"0": "Sonntag"
"6": "Samstag"
},
"placement": {
"before": "davor",
"after": "danach",
"around": "darum herum",
"auto": "automatisch"
"auto": "Automatisch (beste Wahl)"
},
"optimization": {
"newRule": "Neue Optimierungsregel",
@@ -130,34 +167,34 @@
"elementsLabel": "Planungselemente",
"conditionsLabel": "Bedingungen (alle müssen erfüllt sein)",
"measureLabel": "Messgröße",
"aggregationLabel": "Aggregation",
"directionLabel": "Richtung",
"thresholdLabel": "Präferenzschwelle in Arbeitstagen",
"thresholdSummary": "Präferenzschwelle: {count} Arbeitstage",
"aggregationLabel": "Berechnungsart",
"directionLabel": "Ziel",
"thresholdLabel": "Schwelle in Arbeitstagen",
"thresholdSummary": "Schwelle: {count} Arbeitstage",
"summary": "{direction} {aggregation}: {measure} — {elements}{conditions}.",
"invalidConfiguration": "Wählen Sie passende Elemente, Bedingungen, Messgrößen und Aggregationen sowie bei Bedarf eine positive ganzzahlige Tagesschwelle.",
"invalidConfiguration": "Diese Kombination ist nicht möglich. Ändern Sie die Elemente, Bedingungen, Messgröße oder Berechnungsart; die Schwelle muss, falls vorhanden, eine positive ganze Zahl sein.",
"nameRequired": "Geben Sie einen Regelnamen ein.",
"elements": {
"leave-balances": "Urlaubsguthaben",
"public-holiday-weeks": "Feiertagswochen",
"time-off-periods": "Arbeitsfreie Zeiträume",
"work-sequences": "Arbeitsfolgen",
"leave-placements": "Geplante Urlaubstage"
"work-sequences": "Arbeitsphasen",
"leave-placements": "Gebuchte Urlaubstage"
},
"conditions": {
"at-risk": "Vom Verfall bedroht",
"complete": "Vollständig",
"internal": "Intern",
"non-empty": "Nicht leer",
"supporting": "Unterstützend"
"at-risk": "Verfällt im Planungszeitraum",
"complete": "Ganz genommen",
"internal": "Zwischen zwei Auszeiten",
"non-empty": "Mindestens ein Arbeitstag",
"supporting": "Auf einem Guthaben, das nach dem Planungszeitraum verfällt"
},
"measures": {
"unplaced-quantity": "Nicht eingeplante Menge",
"public-holiday-week-value": "Wert der Feiertagswochen",
"non-working-day-gain": "Gewinn arbeitsfreier Tage",
"work-sequence-length": "Länge der Arbeitsfolgen",
"work-sequence-deficit": "Defizit der Arbeitsfolgen",
"placement-count": "Anzahl der Platzierungen"
"unplaced-quantity": "Nicht gebuchte Tage",
"public-holiday-week-value": "Punkte der Wochen mit Feiertag",
"non-working-day-gain": "Wochenend- und Feiertage inklusive",
"work-sequence-length": "Aufeinanderfolgende Arbeitstage",
"work-sequence-deficit": "Fehlende Tage bis zur Schwelle",
"placement-count": "Anzahl gebuchter Tage"
},
"aggregations": {
"sum": "Summe",
@@ -167,6 +204,65 @@
"directions": {
"minimize": "Minimieren",
"maximize": "Maximieren"
},
"plain": {
"goals": {
"minimize": "{quantity} verringern",
"maximize": "{quantity} erhöhen"
},
"intents": {
"unplacedAtRisk": "Tage einplanen, die im Planungszeitraum verfallen, damit möglichst wenige verloren gehen",
"holidayWeekValue": "Die ganze Woche freinehmen, wenn sie einen Feiertag enthält, vor allem wenn er mitten in der Woche liegt",
"nonWorkingDayGain": "Urlaub an Wochenenden und Feiertage anschließen, um möglichst viele freie Tage zu gewinnen, ohne dafür Urlaub zu nehmen",
"longestWorkSequence": "Urlaub so verteilen, dass die längste Arbeitsphase ohne Urlaub kürzer wird",
"shortSequenceDeficit": "Kurze Arbeitsphasen mit weniger als {threshold} zwischen zwei Auszeiten vermeiden",
"supportingPlacements": "Möglichst wenige Tage nehmen, die erst nach dem Planungszeitraum verfallen, um sie für später aufzuheben"
},
"count": "Anzahl der {elements}{scope}",
"elements": {
"leave-balances": "Urlaubsguthaben",
"public-holiday-weeks": "Feiertagswochen",
"time-off-periods": "Auszeiten",
"work-sequences": "Arbeitsphasen",
"leave-placements": "genommenen Urlaubstage"
},
"quantities": {
"unplaced-quantity": {
"sum": "Ungenutzte Urlaubstage{scope}",
"maximum": "Höchste Zahl ungenutzter Tage auf einem Guthaben{scope}"
},
"public-holiday-week-value": {
"sum": "Punkte der Feiertagswochen{scope} (je Feiertag 1 am Montag oder Freitag bis 3 am Mittwoch)",
"maximum": "Punkte der besten Feiertagswoche{scope} (je Feiertag 1 am Montag oder Freitag bis 3 am Mittwoch)"
},
"non-working-day-gain": {
"sum": "Wochenend- und Feiertage in den Auszeiten",
"maximum": "Wochenend- und Feiertage in der Auszeit mit den meisten davon"
},
"work-sequence-length": {
"sum": "Summe der Arbeitstage{scope}",
"maximum": "Länge der längsten Arbeitsphase{scope}"
},
"work-sequence-deficit": {
"sum": "Fehlende Tage von Arbeitsphasen{scope} bis zur Mindestlänge von {threshold}",
"maximum": "Höchste Zahl fehlender Tage einer Arbeitsphase{scope} bis zur Mindestlänge von {threshold}"
},
"placement-count": {
"sum": "Anzahl der genommenen Urlaubstage{scope}",
"maximum": "Vorhandensein mindestens eines genommenen Urlaubstags{scope}"
}
},
"scopes": {
"at-risk": " mit Verfall im Planungszeitraum",
"complete": " ohne Arbeitstag",
"supporting": " als Ergänzung aus Guthaben mit Verfall nach dem Planungszeitraum",
"non-empty": " mit mindestens einem Arbeitstag",
"internal": " zwischen zwei Auszeiten"
},
"workingDays": {
"one": "{count} Arbeitstag",
"other": "{count} Arbeitstagen"
}
}
}
},
@@ -174,30 +270,56 @@
"statistics": {
"open": "Statistik",
"title": "Planstatistik",
"leaveDays": "Neu geplante Urlaubstage",
"averageWorkSequence": "Durchschnittliche Arbeitsphase",
"averageTimeOffPeriod": "Durchschnittliche Ruhephase",
"longestTimeOffPeriod": "Längste Ruhephase",
"weekendConnectedHolidays": "Feiertage mit Wochenendanschluss",
"workingDays": "Arbeitstage",
"calendarDays": "Kalendertage",
"partialPlan": "Teilplan",
"help": "Statistik des berechneten Plans. Bereits gebuchte Tage prägen Ruhe- und Arbeitsphasen, ohne das verbleibende Guthaben erneut zu verbrauchen.",
"earnedLeave": "Erworbener Urlaub vor Verbrauch",
"leaveDaysUnit": "Tage",
"earnedLeaveByRule": "Erworbener Urlaub nach Regel"
"help": "Bereits gebuchte Tage zählen zu Ihren freien Zeiträumen, nicht zu den Tagen, die noch zu nehmen sind.",
"leaveDays": "Eingeplante Urlaubstage",
"outOf": "von {total}",
"unplaced": "Nicht eingeplante Urlaubstage",
"unplacedDays": {
"one": "{count} Tag nicht eingeplant",
"other": "{count} Tage nicht eingeplant"
},
"lostDays": {
"one": "davon {count} verloren",
"other": "davon {count} verloren"
},
"lostHelp": "Ein verlorener Tag verfällt, bevor er genommen werden konnte.",
"keptHelp": "Nichts geht verloren: Der Verfall liegt nach dem Planungszeitraum.",
"daysOff": "Freie Tage insgesamt",
"weekendAndHolidayDays": {
"one": "davon {count} Wochenend- oder Feiertag",
"other": "davon {count} Wochenend- und Feiertage"
},
"periods": "Freie Zeiträume",
"longestPeriod": {
"one": "der längste: {count} Tag",
"other": "der längste: {count} Tage"
},
"longestWorkSequence": "Längste Phase ohne Urlaub",
"workedDays": {
"one": "Arbeitstag",
"other": "Arbeitstage"
},
"bridgedHolidays": "Feiertage mit Brücke zum Wochenende",
"earnedLeave": "Durch Ihre Regeln erworbene Tage",
"oneWorkdayWeeks": {
"one": "{count} Woche mit nur einem Arbeitstag",
"other": "{count} Wochen mit nur einem Arbeitstag"
},
"oneWorkdayHelp": "Für einen einzigen Tag in einer ganzen Woche zur Arbeit zu kommen, ist selten wünschenswert.",
"onlyWorkday": "Einziger Arbeitstag",
"workingDays": "Arbeitstage",
"calendarDays": "Kalendertage"
},
"calculationDate": "Berechnungsdatum",
"futureEntitlement": "Erzeugter künftiger Anspruch",
"includedEntitlement": "Anspruch bereits in den gemeldeten Guthaben enthalten",
"futureEntitlement": "Erworbene Tage",
"includedEntitlement": "Erworbene Tage, bereits in Ihren Guthaben enthalten",
"title": "Ihr optimiertes Jahr",
"daysPlaced": "Eingeplante Urlaubstage",
"daysGained": "Gewonnene arbeitsfreie Tage",
"longestWorkSequence": "Längste Arbeitsphase",
"invitation": "Fügen Sie Ihre Urlaubskonten hinzu und berechnen Sie dann den Plan, um ihn hier zu sehen.",
"legend": "Kalenderlegende",
"invalidInput": "Die Planungsdaten sind ungültig.",
"conflict": "Die Verpflichtungen können nicht gemeinsam erfüllt werden.",
"incomplete": "Die Berechnung wurde vor Abschluss aller Qualitätsstufen beendet.",
"invalidInput": "Die Berechnung konnte nicht starten: Einige Eingaben müssen korrigiert werden.",
"conflict": "Ihre Verpflichtungen lassen sich nicht alle gleichzeitig erfüllen.",
"incomplete": "Die Berechnung wurde vor dem Ende beendet.",
"cancel": "Abbrechen",
"cancelling": "Berechnung wird abgebrochen…",
"progress": {
@@ -215,42 +337,39 @@
"cancelled": "Berechnung abgebrochen",
"cancelledPartial": "Berechnung abgebrochen — Teilplan",
"connectionLost": "Verbindung zum Server verloren. Mit „Plan berechnen“ erneut versuchen.",
"error": "Bei der Planung ist ein unerwarteter Fehler aufgetreten.",
"error": "Bei der Berechnung ist ein unerwarteter Fehler aufgetreten.",
"complete": "Plan berechnet.",
"whyPlacement": "Ihre Urlaubstage verstehen",
"placementNavigation": "Navigation der Platzierungserklärungen",
"placementNavigation": "Von einem Urlaubstag zum nächsten wechseln",
"placement": "Urlaubstag",
"placements": "Platzierungen",
"of": "von",
"first": "Erste Platzierung",
"previous": "Vorherige Platzierung",
"next": "Nächste Platzierung",
"last": "Letzte Platzierung",
"remaining": "Ungenutzte Tage im endgültigen Plan",
"balanceRemaining": "verbleibend",
"counterfactual": "Alternative Termine",
"counterfactualLoading": "Alle Daten im Horizont werden analysiert…",
"counterfactualReady": "Alternative Termine sind bereit.",
"counterfactualError": "Alternative Termine konnten nicht berechnet werden.",
"first": "Erster Urlaubstag",
"previous": "Vorheriger Urlaubstag",
"next": "Nächster Urlaubstag",
"last": "Letzter Urlaubstag",
"remaining": "Nicht gebuchte Tage dieses Guthabens",
"counterfactual": "Verglichenes Datum",
"counterfactualLoading": "Die anderen möglichen Daten werden geprüft…",
"counterfactualReady": "Sie können jetzt andere Daten vergleichen.",
"counterfactualError": "Die anderen Daten konnten nicht geprüft werden.",
"retryCounterfactual": "Datumsanalyse erneut versuchen",
"eligible": "Geeignet",
"ineligible": "Nicht geeignet",
"reason": "Grund",
"eligible": "Verfügbar",
"ineligible": "Nicht verfügbar",
"explanationError": "Die Erklärung konnte nicht erstellt werden.",
"reasons": {
"user-cancelled": "Die Berechnung wurde vom Benutzer abgebrochen.",
"deadline": "Die Planung wurde am Zeitlimit beendet, bevor alle Qualitätsstufen abgeschlossen waren.",
"connection-lost": "Die Verbindung zum Planungsserver ging verloren.",
"stale-calculation": "Die Planung wurde beendet, weil eine neuere Berechnung gestartet wurde.",
"worker-error": "Der isolierte Planungsprozess ist unerwartet fehlgeschlagen.",
"worker-unavailable": "Die Planung konnte nicht gestartet werden, weil die isolierte Ausführung nicht verfügbar ist.",
"planner-error": "Bei der Planung ist ein unerwarteter Fehler aufgetreten.",
"user-cancelled": "Sie haben die Berechnung abgebrochen.",
"deadline": "Die Berechnung hat ihr Zeitlimit erreicht, bevor alle Stufen abgeschlossen waren.",
"connection-lost": "Die Verbindung zum Server wurde unterbrochen.",
"stale-calculation": "Diese Berechnung wurde beendet, weil eine neuere gestartet wurde.",
"worker-error": "Die Berechnung ist unerwartet fehlgeschlagen.",
"worker-unavailable": "Die Berechnung konnte nicht starten.",
"planner-error": "Bei der Berechnung ist ein unerwarteter Fehler aufgetreten.",
"explanation-error": "Ein unerwarteter Fehler hat die Erklärung unterbrochen.",
"earned-entitlement-order": "Erworbener Urlaub stand erst nach seinem letzten zusammengefassten Freizeitzeitraum zur Verfügung.",
"typed-capacity": "Die Verpflichtungen erfordern mehr Urlaub einer Art, als verfügbar ist.",
"horizon-bottleneck": "Der Planungszeitraum enthält für mindestens eine Verpflichtung keine geeigneten Daten.",
"earned-entitlement-bottleneck": "Erworbener Urlaub steht nicht früh genug zur Verfügung, um alle Verpflichtungen zu erfüllen.",
"joint-date-conflict": "Die von den Verpflichtungen verlangten Daten können nicht gemeinsam erfüllt werden."
"earned-entitlement-order": "Erworbene Tage werden erst nach dem Ende der Auszeit verfügbar, die sie erwirbt, und damit zu spät für Ihre Verpflichtungen.",
"typed-capacity": "Ihre Verpflichtungen brauchen mehr Tage einer Urlaubsart, als Ihre Guthaben enthalten.",
"horizon-bottleneck": "Mindestens eine Verpflichtung hat im Planungszeitraum kein mögliches Datum.",
"earned-entitlement-bottleneck": "Erworbene Tage kommen zu spät, um alle Ihre Verpflichtungen zu erfüllen.",
"joint-date-conflict": "Ihre Verpflichtungen verlangen Daten, die sich gegenseitig ausschließen."
},
"validationReasons": {
"balances": "Urlaubsguthaben müssen als Liste übergeben werden.",
@@ -260,7 +379,7 @@
"balance-quantity": "Ein Urlaubsguthaben braucht eine nicht negative ganze Zahl an Tagen.",
"balance-availability": "Ein Urlaubsguthaben hat ein ungültiges Verfügbarkeitsdatum.",
"balance-expiry": "Ein Urlaubsguthaben braucht ein gültiges Verfallsdatum.",
"balance-dates": "Ein Urlaubsguthaben muss spätestens zu seinem Verfallsdatum verfügbar sein.",
"balance-dates": "Das Verfügbarkeitsdatum eines Urlaubsguthabens darf nicht nach seinem Verfallsdatum liegen.",
"rules": "Planungsregeln müssen als Liste übergeben werden.",
"rule-id": "Einer Planungsregel fehlt die Kennung.",
"duplicate-rule-id": "Zwei Planungsregeln haben dieselbe Kennung.",
@@ -268,92 +387,112 @@
"rule-type": "Eine Planungsregel hat einen nicht unterstützten Typ.",
"rule-quantity": "Eine Planungsregel braucht eine nicht negative ganze Zahl an Tagen.",
"rule-selector": "Eine Planungsregel hat eine ungültige Urlaubsart.",
"rule-window": "Eine Zeitfenster-Regel braucht ein Startdatum, das nicht nach dem Enddatum liegt.",
"rule-window": "Das Startdatum einer Zeitfenster-Regel darf nicht nach dem Enddatum liegen.",
"rule-weekday": "Eine Wenn-Dann-Regel braucht einen gültigen Wochentag.",
"rule-mode": "Eine Wenn-Dann-Regel hat eine nicht unterstützte Platzierung.",
"earned-quantity": "Eine Wenn-Dann-Regel braucht eine nicht negative ganze Zahl an Bonustagen.",
"earned-type": "Eine Wenn-Dann-Regel braucht CP, RTT oder Andere als Bonusart.",
"invalid-optimization-configuration": "Wählen Sie passende Elemente, Bedingungen, Messgrößen und Aggregationen sowie bei Bedarf eine positive ganzzahlige Tagesschwelle.",
"earned-quantity": "Eine Wenn-Dann-Regel braucht eine nicht negative ganze Zahl erworbener Tage.",
"earned-type": "Eine Wenn-Dann-Regel braucht CP, RTT oder Andere als Art der erworbenen Tage.",
"invalid-optimization-configuration": "Diese Kombination ist nicht möglich. Ändern Sie die Elemente, Bedingungen, Messgröße oder Berechnungsart; die Schwelle muss, falls vorhanden, eine positive ganze Zahl sein.",
"unsupported-optimization-configuration": "Diese Regel kombiniert unvereinbare Planungselemente und Messgrößen.",
"horizon": "Der Planungszeitraum ist erforderlich.",
"horizon-start": "Der Beginn des Planungszeitraums muss ein gültiges Kalenderdatum sein.",
"horizon-end": "Das Ende des Planungszeitraums muss ein gültiges Kalenderdatum sein.",
"horizon-order": "Der Planungszeitraum muss vor seinem Ende beginnen.",
"deadline": "Das Zeitlimit der Planung muss eine endliche, nicht negative Zahl sein.",
"declared-days": "Die angegebenen arbeitsfreien Tage sind ungültig."
"declared-days": "Die bereits gebuchten Tage sind ungültig."
},
"conflictDetails": "Warum kein Plan die Verpflichtungen erfüllt",
"conflictDetails": "Warum kein Plan alle Verpflichtungen erfüllt",
"conflictingRules": "Konfligierende Regeln",
"bottleneck": "Engpass",
"incompleteDetails": "Vor dem Abbruch abgeschlossene Schritte",
"incumbentExplanation": "Dies erklärt den besten gültigen Zwischenstand; spätere Qualitätsstufen wurden nicht abgeschlossen.",
"bottleneck": "Ursache der Blockade",
"incompleteDetails": "Wo die Berechnung angehalten hat",
"incumbentExplanation": "Dieser Plan ist der beste, der vor dem Abbruch gefunden wurde. Er kann noch verbessert werden.",
"completedStages": "Abgeschlossene Schritte",
"uncompletedStages": "Unterbrochene oder nicht gestartete Schritte",
"uncompletedStages": "Nicht abgeschlossene Schritte",
"none": "Keine",
"currentPlacement": "Aktuell erklärte Platzierung",
"currentPlacement": "Erklärter Urlaubstag",
"explainedPeriod": "Erklärter Freizeitzeitraum",
"outsideHorizon": "Kontextdatum außerhalb des Planungshorizonts",
"calendarHelp": "Wählen Sie einen Urlaubstag, um seinen Beitrag zum Plan zu sehen.",
"explanationHelp": "Sehen Sie Ihre Auszeit und den Beitrag jedes Tages.",
"outsideHorizon": "Außerhalb des Planungszeitraums",
"calendarHelp": "Wählen Sie einen Urlaubstag, um zu sehen, was er zum Plan beiträgt.",
"explanationHelp": "Für jeden gebuchten Tag: seine Auszeit und was er verändert.",
"technicalDetails": "Berechnungsdetails",
"appliedRules": {
"title": "Angewendete Regeln",
"entries": "Einträge"
},
"timeOffPeriods": {
"title": "Ihre freien Zeiträume",
"count": "Zeiträume",
"help": "Die zu nehmenden Tage, Zeitraum für Zeitraum. Wählen Sie einen aus, um ihn im Kalender anzuzeigen."
},
"compareDates": "Andere Termine vergleichen",
"stopComparing": "Datumsvergleich schließen",
"explanation": {
"breakTitle": "Ihre Auszeit",
"leaveDays": "eingesetzte Urlaubstage",
"freeDays": "Wochenend- und Feiertage",
"daysOff": "freie Tage am Stück",
"wholeBreak": "Diese Zahlen gelten für die gesamte Auszeit einschließlich des ausgewählten Tages.",
"breakTitle": "Freier Zeitraum",
"bookedDays": {
"one": "bereits gebuchter Tag",
"other": "bereits gebuchte Tage"
},
"leaveDays": {
"one": "gebuchter Urlaubstag",
"other": "gebuchte Urlaubstage"
},
"freeDays": {
"one": "Wochenend- oder Feiertag",
"other": "Wochenend- und Feiertage"
},
"daysOff": {
"one": "freier Tag",
"other": "freie Tage am Stück"
},
"leaveUsed": "Dieses Datum nutzt 1 Tag aus „{balance}“.",
"expires": "Dieses Guthaben ist nutzbar bis",
"linkedRules": "Zugehörige Regeln:",
"atRiskContribution": "Schützt Urlaub, der zu verfallen droht.",
"linkedRules": "Regeln hinter diesem Tag:",
"atRiskContribution": "Verhindert den Verlust von Urlaub, der im Planungszeitraum verfällt.",
"impact": "Was dieser Tag verändert",
"impactHelp": "Vergleichen Sie den gesamten Plan mit und ohne diesen Urlaubstag. Alle anderen Urlaubstermine bleiben gleich; nur geänderte Werte werden angezeigt.",
"impactHelp": "Der gesamte Plan mit und ohne diesen Urlaubstag; andere Daten bleiben unverändert. Nur geänderte Summen werden angezeigt.",
"criterion": "Im gesamten Plan",
"withoutDay": "Ohne diesen Tag",
"withDay": "Mit diesem Tag",
"noChange": "Diese Werte sind gleich. Regeln und die letzten Entscheidungskriterien (Verfall des Guthabens, dann Datum) können die Auswahl weiterhin beeinflussen.",
"priorityHelp": "Verpflichtungen werden gemeinsam erfüllt. Aktive Präferenzen werden in Ihrer Regelreihenfolge verglichen. Nur diese Regeln führen zu neuen Urlaubstagen; früherer Verfall und dann frühere Daten entscheiden bei Gleichstand.",
"noChange": "Keine Summe ändert sich. Bei Gleichstand bevorzugt die Berechnung das Guthaben, das am frühesten verfällt, dann das frühere Datum.",
"tryDate": "Anderes Datum testen",
"plannedDate": "Derzeit geplant für:",
"currentPlan": "Aktueller Plan",
"alternative": "Mit diesem Datum",
"sameDate": "Dies ist das geplante Datum. Wählen Sie oben ein anderes Datum, um den Unterschied zu sehen.",
"moveHelp": "Verschieben Sie probeweise diesen Tag. Alle anderen Urlaubstermine bleiben gleich.",
"comparisonUnavailable": "Der Vergleich für das ursprüngliche Datum ist nicht verfügbar. Daher lässt sich die Änderung nicht anzeigen.",
"moveHelp": "Probieren Sie ein anderes Datum für diesen Tag. Andere Urlaubstage bleiben unverändert.",
"comparisonUnavailable": "Der Unterschied zum geplanten Datum konnte nicht berechnet werden.",
"objectives": {
"obligation-validity": {
"label": "Unerfüllte Verpflichtungen",
"help": "Anzahl nicht erfüllter Pflichtregeln. Ein gültiger Plan hat den Wert null."
"label": "Nicht erfüllte Verpflichtungen",
"help": "Ein gültiger Plan hat keine."
},
"unplaced-at-risk": {
"label": "Noch nicht genutzte Tage mit Verfallsrisiko",
"help": "Ungenutzte Tage, die im Planungszeitraum verfallen. Weniger ist besser."
"label": "Tage, die ungebucht verfallen",
"help": "Sie verfallen im Planungszeitraum. Weniger ist besser."
},
"preference": {
"label": "Präferenz: {rule}",
"help": "Tage oder vollständig erfüllte Regeln, je nach Regel. Mehr ist besser."
},
"holiday-week-value": {
"label": "Priorität für Feiertagswochen (Punkte)",
"help": "Gewichteter Wert: Feiertage am Mittwoch zählen 3, Dienstag/Donnerstag 2, Montag/Freitag 1. Höher ist besser."
"label": "Ganze Wochen um einen Feiertag herum (Punkte)",
"help": "Ein Feiertag am Mittwoch zählt 3 Punkte, am Dienstag oder Donnerstag 2, am Montag oder Freitag 1. Mehr ist besser."
},
"non-working-day-gain": {
"label": "Wochenend- und Feiertage in Ihren Auszeiten",
"label": "Wochenend- und Feiertage in Ihren freien Zeiträumen",
"help": "Freie Tage ohne Urlaubsverbrauch. Mehr ist besser."
},
"longest-work-sequence": {
"label": "Meiste Arbeitstage zwischen Urlaubstagen",
"help": "Wochenenden und Feiertage zählen nicht mit. Weniger ist besser."
"label": "Längste Strecke ohne Urlaub",
"help": "In Arbeitstagen. Weniger ist besser."
},
"short-sequence-deficit": {
"label": "Abzug für kurze Arbeitsphasen",
"help": "Jede Lücke von 1–4 Arbeitstagen zwischen Urlaubstagen addiert die bis 5 fehlenden Tage. Niedriger ist besser."
"label": "Zu kurze Arbeitsphasen (fehlende Tage)",
"help": "Bei jeder Rückkehr zur Arbeit von weniger als 5 Arbeitstagen zwischen zwei Auszeiten die Tage, die bis 5 fehlen. Weniger ist besser."
},
"supporting-placements": {
"label": "Tage aus später verfallenden Guthaben",
"help": "Urlaub, der über diesen Planungszeitraum hinaus aufgespart werden könnte. Weniger ist besser."
"label": "Gebuchte Tage, die für später hätten aufgehoben werden können",
"help": "Ihr Guthaben verfällt erst nach dem Planungszeitraum. Weniger ist besser."
},
"balance-expiry": {
"label": "Früher verfallenden Urlaub zuerst nutzen",
@@ -364,8 +503,7 @@
"help": "Letztes Kriterium, wenn alle anderen Kriterien gleich sind."
},
"optimization": {
"label": "{rule}: {summary}",
"help": "Diese Optimierungspräferenz bewertet ihre gespeicherte Konfiguration. Aktive Präferenzen werden in der angezeigten Reihenfolge verglichen; frühere haben Vorrang."
"label": "{rule} — {summary}"
}
},
"stages": {
@@ -378,50 +516,49 @@
},
"unavailable": {
"non-working": "Dieser Tag ist bereits frei (Wochenende oder Feiertag). Urlaub ist nicht nötig.",
"declared-day": "Sie haben diesen Tag bereits als arbeitsfrei festgelegt. Wählen Sie einen anderen Arbeitstag.",
"declared-day": "Sie haben diesen Tag bereits gebucht. Wählen Sie einen anderen Arbeitstag.",
"occupied": "Hier ist bereits ein anderer Urlaubstag geplant. Wählen Sie einen freien Arbeitstag.",
"unavailable": "Dieses Urlaubsguthaben kann an diesem Datum nicht verwendet werden.",
"expired": "Dieses Datum liegt nach dem Verfall des Urlaubsguthabens.",
"expired": "Das Guthaben ist an diesem Datum bereits verfallen.",
"type-incompatible": "Diese Urlaubsart kann an diesem Datum nicht verwendet werden.",
"rule-invalid": "Dieses Datum würde eine Planungsregel verletzen.",
"invalid-optimization-configuration": "Wählen Sie passende Elemente, Bedingungen, Messgrößen und Aggregationen sowie bei Bedarf eine positive ganzzahlige Tagesschwelle.",
"rule-invalid": "An diesem Datum würde dieser Tag nicht mehr den Regeln entsprechen, die ihn gebucht haben.",
"invalid-optimization-configuration": "Diese Kombination ist nicht möglich. Ändern Sie die Elemente, Bedingungen, Messgröße oder Berechnungsart; die Schwelle muss, falls vorhanden, eine positive ganze Zahl sein.",
"unsupported-optimization-configuration": "Diese Regel kombiniert unvereinbare Planungselemente und Messgrößen."
},
"preferenceHelp": {
"time_window": "Urlaubstage im bevorzugten Zeitraum. Mehr ist besser.",
"if_then": "Vollständig erfüllte Vorkommen dieser Regel. Mehr ist besser."
"time_window": "Urlaubstage im gewünschten Zeitraum. Mehr ist besser.",
"if_then": "Feiertage, bei denen die Regel vollständig angewendet wird. Mehr ist besser."
}
},
"details": {
"intro": "Die linke Spalte zeigt den Plan ohne diesen Urlaubstag. Die rechte zeigt den aktuellen Plan.",
"balance": "Urlaubsguthaben",
"available": "Verfügbar ab",
"expires": "Verfällt am",
"criteria": "Die Prioritäten des Planers",
"criteriaHelp": "Von oben nach unten lesen: Der erste Unterschied hat Vorrang. Wählen Sie ein Kriterium, um seine Berechnung zu sehen.",
"firstDifference": "Erster Unterschied",
"criteriaHelp": "Die Kriterien werden von oben nach unten verglichen: Das erste, das sich unterscheidet, entscheidet. Öffnen Sie ein Kriterium, um zu sehen, wie es gezählt wird.",
"firstDifference": "Entscheidendes Kriterium",
"higher": "Höher ist besser",
"lower": "Niedriger ist besser",
"tieBreaks": "Wenn die obigen Werte gleich sind",
"audit": "Rohdaten · zur Fehlersuche",
"auditHelp": "Ursprüngliche Werte, Kennungen und Beiträge aus dieser Berechnung.",
"supporting": "Dieser Tag nutzt Urlaub, der über den Planungszeitraum hinaus aufgespart werden könnte, um Ihre Auszeiten zu verbessern.",
"auditHelp": "Interne Werte und Kennungen dieser Berechnung.",
"supporting": "Dieser Tag hätte für später aufgehoben werden können: Er wird hier gebucht, um Ihre freien Zeiträume zu verbessern.",
"remainingReasons": {
"unavoidable-expiry": "Am {expiry} abgelaufen, vor dem Planungsbeginn am {start}. In diesem Zeitraum nicht nutzbar.",
"available-after-horizon": "Erst ab dem {available} verfügbar, nach dem letzten Planungstag am {end}.",
"no-working-date": "Kein Arbeitstag liegt sowohl im Planungszeitraum als auch zwischen Verfügbarkeits- und Ablaufdatum.",
"all-dates-occupied": "Alle Arbeitstage, an denen dieses Urlaubskonto nutzbar ist, sind bereits durch geplanten Urlaub oder gebuchte Tage belegt.",
"preserved": "Für später aufbewahrt: Das Urlaubskonto läuft nach dem Planungszeitraum ab und die Berechnung hat gemäß Ihren Prioritäten keine zusätzliche Platzierung ausgewählt.",
"active-priorities": "Die Berechnung hat dieses Urlaubskonto gemäß Ihren aktiven Regeln ungenutzt gelassen. Ändern Sie die Regeln oder ihre Reihenfolge, um einen anderen Plan anzufordern.",
"calculation-incomplete": "Die Berechnung wurde vor Abschluss der Planung unterbrochen. Die Nichtnutzung ist keine endgültige Entscheidung.",
"not-established": "Diese Berechnung hat keinen genauen Grund für die Nichtnutzung ermittelt."
"unavoidable-expiry": "Am {expiry} verfallen, vor dem Beginn des Planungszeitraums am {start}. Er konnte nicht gebucht werden.",
"available-after-horizon": "Erst ab dem {available} verfügbar, nach dem Ende des Planungszeitraums ({end}).",
"no-working-date": "Kein Arbeitstag im Planungszeitraum liegt in der Gültigkeit dieses Guthabens.",
"all-dates-occupied": "Alle Arbeitstage, an denen dieses Guthaben nutzbar ist, sind bereits durch anderen Urlaub belegt.",
"preserved": "Für später aufgehoben: Es verfällt erst nach dem Planungszeitraum, und eine Buchung hätte den Plan nach Ihren Regeln nicht verbessert.",
"active-priorities": "Ihre aktiven Regeln haben nicht dazu geführt, dass diese Tage gebucht werden. Ändern Sie die Regeln oder ihre Reihenfolge, um einen anderen Plan zu erhalten.",
"calculation-incomplete": "Die Berechnung wurde vor dem Ende beendet: Diese Tage hätten möglicherweise gebucht werden können.",
"not-established": "Die Berechnung sagt nicht, warum diese Tage nicht gebucht sind."
}
},
"comparison": {
"title": "Daten vergleichen",
"preview": "Nur eine Vorschau. Ihr Plan bleibt unverändert.",
"nearby": "Verfügbare Termine in der Nähe",
"noAlternatives": "Dieser Urlaubstag kann auf kein anderes Datum gelegt werden. Sie können trotzdem ein Datum prüfen, um den Grund zu sehen.",
"noAlternatives": "Dieser Urlaubstag kann an keinem anderen Datum gebucht werden. Geben Sie ein Datum ein, um den Grund zu sehen.",
"chooseDate": "Wählen Sie oben ein Datum, um die Änderungen zu sehen.",
"dateRange": "Planungszeitraum:",
"invalidDate": "Wählen Sie ein gültiges Datum im oben angegebenen Planungszeitraum.",
@@ -453,6 +590,5 @@
"switchToMultiYearViewLabel": "Monat und Jahr auswählen",
"yearRangeLabel": "{start} bis {end}"
},
"loading": "Wird geladen...",
"weekdaysShort": ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"]
"loading": "Wird berechnet…"
}
+303 -167
View File
@@ -3,30 +3,34 @@
"bookedDays": {
"enter": "Edit already booked days",
"booked": "Already booked",
"help": "Choose CP, RTT, Other or Erase, then click or drag between dates, including across months. Release to save; Escape cancels. Each day already matching the chosen type is cleared; other days receive that type. Weekends and public holidays are skipped. Hatching marks already booked days, applied on the next calculation.",
"fixed": "Fixed user input, with no remaining balance debit or optimization decision.",
"removed": "Declaration removed",
"help": "Choose CP, RTT, Other or Erase, then click a day or drag between two dates, including across months; Escape cancels. A day that already has the chosen type is cleared, and the others take it. Weekends and public holidays are skipped. Hatched days are already booked: the next calculation takes them into account.",
"fixed": "The calculation does not move already booked days and does not deduct them from your balances.",
"removed": "Already booked day removed",
"erase": "Erase",
"rangeSaved": "Saved already booked days: {count} ({type}).",
"rangeRemoved": "Removed declarations: {count}."
"rangeRemoved": "Already booked days removed: {count}."
},
"app": {
"title": "vac-optimizer",
"description": "Make more room for time off.",
"skipToPlan": "Skip to your plan"
"skipToPlan": "Skip to your plan",
"view": "View",
"configuration": "Setup",
"plan": "Plan"
},
"userInput": {
"title": "Configure your leave",
"description": "Choose a planning period, then add each leave balance and its validity period.",
"addVacationDay": "Add leave balance",
"emptyBalances": "No leave balance yet. Add your first one below.",
"calculate": "Calculate plan",
"durationEstimate": "Approximate wait: {range} {unit}",
"durationEstimate": "Estimated calculation time: {range} {unit}",
"durationUnits": {
"seconds": "s",
"minutes": "min"
},
"remainingDaysWarning": "{count} leave day{plural} remaining:",
"deleteEntry": "Delete entry",
"remainingDaysWarning": "{count} leave day{plural} not yet booked:",
"deleteEntry": "Delete this balance",
"chooseDate": "Expires on",
"availableDate": "Available from",
"days": "Days",
@@ -38,21 +42,21 @@
"remainingHorizon": "Calculated plan from {start} through {end}.",
"remainingEarnedFrom": "Leave earned through the rule “{rule}”.",
"remainingSuggestions": {
"available-after-horizon": "You can extend the planning period beyond its availability date, then recalculate.",
"available-after-horizon": "To use it, extend the planning period beyond its availability date, then recalculate.",
"no-working-date": "Check the planning period and this balance’s validity dates.",
"all-dates-occupied": "You can extend the period if validity allows, or adjust your already booked days and rules, then recalculate.",
"preserved": "No action needed. To request its use, add a rule within its validity period, then recalculate.",
"calculation-incomplete": "Run the calculation again if you want it to finish planning."
"all-dates-occupied": "To use it, change your already booked days or your rules, or extend the planning period if this balance is still valid after it, then recalculate.",
"preserved": "Nothing to do. To book it anyway, add an imposed period covering dates when it can be used, then recalculate.",
"calculation-incomplete": "Run the calculation again so that it completes."
}
},
"dayTypes": {
"weekend": "Weekend",
"closedDay": "Public Holiday",
"closedDay": "Public holiday",
"rtt": "RTT",
"cp": "Paid Leave",
"cp": "Paid leave",
"other": "Other",
"today": "Today",
"any": "Any"
"any": "Any type"
},
"settings": {
"title": "Settings",
@@ -69,33 +73,53 @@
"systemAppearance": "Current system appearance",
"planningHorizon": "Planning period",
"planningStart": "Start date (inclusive)",
"lastPlanningDate": "Last planning date (inclusive)",
"planningDatesHelp": "Choose any dates, including past dates. Your calendar updates when you select Calculate plan.",
"invalidDate": "Enter two valid calendar dates.",
"horizonOrder": "The last planning date must be on or after the start date.",
"invalidHorizon": "Correct the planning dates before calculating."
"lastPlanningDate": "End date (inclusive)",
"planningDatesHelp": "Past dates are accepted. The calendar updates at the next calculation.",
"invalidDate": "Enter two valid dates.",
"horizonOrder": "The end date cannot be before the start date.",
"invalidHorizon": "Correct the planning period dates first."
},
"rules": {
"title": "Planning rules",
"subtitle": "Manage optimization rules",
"active": "active",
"subtitle": "What the calculation must respect or prefer",
"active": {
"one": "{count} active",
"other": "{count} active"
},
"moveRuleUp": "Move rule up",
"moveRuleDown": "Move rule down",
"dragRule": "Drag to reorder",
"ruleMoved": "{name}: position {position} of {count}.",
"priorityInfo": "Rules at the top have higher priority. Reorder with the handle or arrow buttons.",
"ifThenTemplate": "If a holiday falls on a <strong>{day}</strong>, place <strong>{placeDays}</strong> day(s) <strong>{placeType}</strong> <strong>{placement}</strong> and get <strong>{rewardDays}</strong> day(s) <strong>{rewardType}</strong> as a bonus.",
"timeWindowTemplate": "Place <strong>{placeDays}</strong> day(s) <strong>{placeType}</strong> between <strong>{startDate}</strong> and <strong>{endDate}</strong>.",
"ifThenTemplate": "If a public holiday falls on a <strong>{day}</strong>, take <strong>{placeDays}</strong> {placement}{earned}.",
"ifThenEarned": " and earn <strong>{earnedDays}</strong>",
"timeWindowTemplate": "Take <strong>{placeDays}</strong> between <strong>{startDate}</strong> and <strong>{endDate}</strong>.",
"dayCount": {
"one": "{count} day {type}",
"other": "{count} days {type}"
},
"summaryTypes": {
"cp": "of paid leave",
"rtt": "of RTT",
"other": "of Other leave",
"any": "of any leave type"
},
"summaryPlacement": {
"before": "right before it",
"after": "right after it",
"around": "on both sides of it",
"auto": "around it where it helps most"
},
"editRule": "Edit rule",
"deleteRule": "Delete rule",
"addRule": "Add a rule",
"place": "Place",
"place": "Take",
"ruleName": "Rule name",
"holidayFalls": "Holiday falls on a",
"holidayFalls": "If a public holiday falls on a",
"days": "Days",
"type": "Type",
"position": "Position",
"getBonus": "Get as bonus",
"getBonus": "Earn",
"force": "Rule force",
"obligation": "Obligation",
"preference": "Preference",
@@ -104,60 +128,73 @@
"cancel": "Cancel",
"save": "Save",
"add": "Add",
"addRuleButton": "Add Rule",
"newIfThenRule": "New \"If ... Then\" Rule",
"newTimeWindowRule": "New Imposed Period",
"defaultNewRuleName": "New Rule",
"defaultNewPeriodName": "New Period",
"newIfThenRule": "New \"If … Then\" rule",
"newTimeWindowRule": "New imposed period",
"defaultNewRuleName": "New rule",
"defaultNewPeriodName": "New period",
"import": {
"title": "Shared rules",
"replaceStatement": "These rules will replace all your current rules ({count}). Your leave balances, already booked days and planning period stay as they are.",
"accept": "Replace my rules",
"disabled": "Disabled",
"invalidLink": "This share link is invalid or incomplete. Your rules have not changed."
},
"share": {
"action": "Share my rules",
"title": "My VacOptimizer planning rules",
"copied": "Link copied",
"copyFailed": "Copy failed",
"invalidRule": "Fix the rule “{rule}” to share your rules."
},
"daysOfWeek": {
"0": "Sunday",
"1": "Monday",
"2": "Tuesday",
"3": "Wednesday",
"4": "Thursday",
"5": "Friday",
"6": "Saturday",
"0": "Sunday"
"6": "Saturday"
},
"placement": {
"before": "Before",
"after": "After",
"around": "Around",
"auto": "Auto (Best choice)"
"auto": "Automatic (best choice)"
},
"optimization": {
"newRule": "New Optimization Rule",
"defaultName": "Loss prevention",
"newRule": "New optimization rule",
"defaultName": "Avoid losing days",
"elementsLabel": "Planning elements",
"conditionsLabel": "Conditions (all must match)",
"measureLabel": "Measure",
"aggregationLabel": "Aggregation",
"directionLabel": "Direction",
"thresholdLabel": "Preference threshold in working days",
"thresholdSummary": "preference threshold: {count} working days",
"aggregationLabel": "Calculation mode",
"directionLabel": "Goal",
"thresholdLabel": "Threshold in working days",
"thresholdSummary": "threshold: {count} working days",
"summary": "{direction} {aggregation}: {measure} — {elements}{conditions}.",
"invalidConfiguration": "Choose compatible planning elements, conditions, measure and aggregation, with a positive whole-day threshold when needed.",
"invalidConfiguration": "This combination is not possible. Change the elements, conditions, measure or calculation mode; the threshold, if there is one, must be a positive whole number.",
"nameRequired": "Enter a rule name.",
"elements": {
"leave-balances": "Leave balances",
"public-holiday-weeks": "Public-holiday weeks",
"time-off-periods": "Time-off periods",
"work-sequences": "Work sequences",
"leave-placements": "Leave placements"
"work-sequences": "Work periods",
"leave-placements": "Booked leave days"
},
"conditions": {
"at-risk": "At risk of expiry",
"complete": "Complete",
"internal": "Internal",
"non-empty": "Non-empty",
"supporting": "Supporting"
"at-risk": "Expiring within the planning period",
"complete": "Taken in full",
"internal": "Between two time-off periods",
"non-empty": "At least one working day",
"supporting": "On a balance expiring after the planning period"
},
"measures": {
"unplaced-quantity": "Unplaced quantity",
"public-holiday-week-value": "Public-holiday week value",
"non-working-day-gain": "Non-working-day gain",
"work-sequence-length": "Work-sequence length",
"work-sequence-deficit": "Work-sequence deficit",
"placement-count": "Placement count"
"unplaced-quantity": "Days not booked",
"public-holiday-week-value": "Points of weeks with a public holiday",
"non-working-day-gain": "Weekend and public-holiday days included",
"work-sequence-length": "Consecutive working days",
"work-sequence-deficit": "Days missing to reach the threshold",
"placement-count": "Number of days booked"
},
"aggregations": {
"sum": "Sum",
@@ -167,6 +204,65 @@
"directions": {
"minimize": "Minimize",
"maximize": "Maximize"
},
"plain": {
"goals": {
"minimize": "Reduce {quantity}",
"maximize": "Increase {quantity}"
},
"intents": {
"unplacedAtRisk": "Take the days that expire within the planning period, to lose as few as possible",
"holidayWeekValue": "Take the whole week off when it contains a public holiday, especially if the holiday falls midweek",
"nonWorkingDayGain": "Attach leave to weekends and public holidays, to gain as many days off as possible without taking them as leave",
"longestWorkSequence": "Spread leave out to shorten the longest stretch of work without leave",
"shortSequenceDeficit": "Avoid going back to work for fewer than {threshold} between two time-off periods",
"supportingPlacements": "Take as few as possible of the days that only expire after the planning period, to keep them for later"
},
"count": "the number of {elements}{scope}",
"elements": {
"leave-balances": "leave balances",
"public-holiday-weeks": "public-holiday weeks",
"time-off-periods": "time-off periods",
"work-sequences": "work periods",
"leave-placements": "leave days taken"
},
"quantities": {
"unplaced-quantity": {
"sum": "unused leave days{scope}",
"maximum": "the largest number of unused days left on one balance{scope}"
},
"public-holiday-week-value": {
"sum": "the points of public-holiday weeks{scope}, each holiday scoring from 1 (Monday, Friday) to 3 (Wednesday)",
"maximum": "the points of the best public-holiday week{scope}, each holiday scoring from 1 (Monday, Friday) to 3 (Wednesday)"
},
"non-working-day-gain": {
"sum": "weekend days and public holidays within time-off periods",
"maximum": "weekend days and public holidays in the time-off period with the most of them"
},
"work-sequence-length": {
"sum": "the total of working days{scope}",
"maximum": "the longest work period{scope}"
},
"work-sequence-deficit": {
"sum": "the days missing from work periods{scope} to reach {threshold}",
"maximum": "the largest number of days missing from one work period{scope} to reach {threshold}"
},
"placement-count": {
"sum": "the number of leave days taken{scope}",
"maximum": "the presence of at least one leave day taken{scope}"
}
},
"scopes": {
"at-risk": " expiring within the planning period",
"complete": " taken off entirely",
"supporting": " as extras from balances expiring after the planning period",
"non-empty": " of at least one working day",
"internal": " between two time-off periods"
},
"workingDays": {
"one": "{count} working day",
"other": "{count} working days"
}
}
}
},
@@ -174,30 +270,56 @@
"statistics": {
"open": "Statistics",
"title": "Plan statistics",
"leaveDays": "New leave days",
"averageWorkSequence": "Average work sequence",
"averageTimeOffPeriod": "Average time-off period",
"longestTimeOffPeriod": "Longest time-off period",
"weekendConnectedHolidays": "Public holidays connected to a weekend",
"workingDays": "working days",
"calendarDays": "calendar days",
"partialPlan": "Partial plan",
"help": "Statistics for the calculated plan. Already booked days shape breaks and working stretches without consuming remaining balances.",
"earnedLeave": "Earned leave before use",
"leaveDaysUnit": "days",
"earnedLeaveByRule": "Earned leave by rule"
"help": "Days already booked count in your time-off periods, not in the days to take.",
"leaveDays": "Leave days taken",
"outOf": "of {total}",
"unplaced": "Leave days not taken",
"unplacedDays": {
"one": "{count} day not taken",
"other": "{count} days not taken"
},
"lostDays": {
"one": "{count} of them lost",
"other": "{count} of them lost"
},
"lostHelp": "A lost day expires before it could be taken.",
"keptHelp": "Nothing is lost: expiry falls after the planning period.",
"daysOff": "Total days off",
"weekendAndHolidayDays": {
"one": "including {count} weekend day or public holiday",
"other": "including {count} weekend days and public holidays"
},
"periods": "Time-off periods",
"longestPeriod": {
"one": "the longest: {count} day",
"other": "the longest: {count} days"
},
"longestWorkSequence": "Longest stretch without leave",
"workedDays": {
"one": "working day",
"other": "working days"
},
"bridgedHolidays": "Public holidays bridged to a weekend",
"earnedLeave": "Days earned through your rules",
"oneWorkdayWeeks": {
"one": "{count} week with a single working day",
"other": "{count} weeks with a single working day"
},
"oneWorkdayHelp": "Coming in for a single day in a whole week is rarely desirable.",
"onlyWorkday": "Only working day",
"workingDays": "working days",
"calendarDays": "calendar days"
},
"calculationDate": "Calculation date",
"futureEntitlement": "Future entitlement generated",
"includedEntitlement": "Entitlement already included in reported balances",
"futureEntitlement": "Days earned",
"includedEntitlement": "Days earned, already counted in your balances",
"title": "Your optimized year",
"daysPlaced": "Leave days placed",
"daysGained": "Non-working days gained",
"longestWorkSequence": "Longest work sequence",
"invitation": "Add your leave balances, then calculate the plan to see it here.",
"legend": "Calendar legend",
"invalidInput": "The planning input is invalid.",
"conflict": "The obligations cannot be satisfied together.",
"incomplete": "Calculation stopped before all quality stages completed.",
"invalidInput": "The calculation could not start: some inputs need correcting.",
"conflict": "Your obligations cannot all be met at the same time.",
"incomplete": "The calculation stopped before the end.",
"cancel": "Cancel",
"cancelling": "Cancelling…",
"progress": {
@@ -215,42 +337,39 @@
"cancelled": "Calculation cancelled",
"cancelledPartial": "Calculation cancelled — partial plan",
"connectionLost": "Connection to the server lost. Use “Calculate plan” to try again.",
"error": "The planner encountered an unexpected error.",
"error": "The calculation hit an unexpected error.",
"complete": "Plan calculated.",
"whyPlacement": "Understand your leave days",
"placementNavigation": "Placement explanation navigation",
"placementNavigation": "Go from one leave day to another",
"placement": "Leave day",
"placements": "placements",
"of": "of",
"first": "First placement",
"previous": "Previous placement",
"next": "Next placement",
"last": "Last placement",
"remaining": "Unused days in the final plan",
"balanceRemaining": "remaining",
"counterfactual": "Date alternatives",
"counterfactualLoading": "Analyzing every date in the horizon…",
"counterfactualReady": "Date alternatives are ready.",
"counterfactualError": "Date alternatives could not be calculated.",
"first": "First leave day",
"previous": "Previous leave day",
"next": "Next leave day",
"last": "Last leave day",
"remaining": "Days not booked on this balance",
"counterfactual": "Compared date",
"counterfactualLoading": "Checking the other possible dates…",
"counterfactualReady": "You can now compare other dates.",
"counterfactualError": "The other dates could not be checked.",
"retryCounterfactual": "Retry date analysis",
"eligible": "Eligible",
"ineligible": "Ineligible",
"reason": "Reason",
"eligible": "Available",
"ineligible": "Unavailable",
"explanationError": "The explanation could not be produced.",
"reasons": {
"user-cancelled": "The calculation was cancelled by the user.",
"deadline": "Planning stopped at its time limit before all quality stages completed.",
"connection-lost": "The connection to the planning server was lost.",
"stale-calculation": "Planning stopped because a newer calculation started.",
"worker-error": "The planning worker failed unexpectedly.",
"worker-unavailable": "Planning could not start because isolated execution is unavailable.",
"planner-error": "The planner encountered an unexpected error.",
"user-cancelled": "You cancelled the calculation.",
"deadline": "The calculation reached its time limit before completing all its stages.",
"connection-lost": "The connection to the server was lost.",
"stale-calculation": "This calculation stopped because a more recent one started.",
"worker-error": "The calculation failed unexpectedly.",
"worker-unavailable": "The calculation could not start.",
"planner-error": "The calculation hit an unexpected error.",
"explanation-error": "An unexpected error interrupted the explanation.",
"earned-entitlement-order": "Earned leave became available only after its final merged time-off period.",
"typed-capacity": "The obligations require more leave of one type than is available.",
"horizon-bottleneck": "The planning period contains no eligible dates for at least one obligation.",
"earned-entitlement-bottleneck": "Earned leave is not available early enough to satisfy every obligation.",
"joint-date-conflict": "The dates required by the obligations cannot be satisfied together."
"earned-entitlement-order": "Days earned only become available after the end of the time-off period that earns them, too late for your obligations.",
"typed-capacity": "Your obligations need more days of one leave type than your balances contain.",
"horizon-bottleneck": "At least one obligation has no possible date in the planning period.",
"earned-entitlement-bottleneck": "Days earned arrive too late to meet all your obligations.",
"joint-date-conflict": "Your obligations require dates that conflict with each other."
},
"validationReasons": {
"balances": "Leave balances must be provided as a list.",
@@ -260,7 +379,7 @@
"balance-quantity": "A leave balance needs a non-negative whole number of days.",
"balance-availability": "A leave balance has an invalid availability date.",
"balance-expiry": "A leave balance needs a valid expiry date.",
"balance-dates": "A leave balance must become available on or before its expiry date.",
"balance-dates": "A leave balance’s availability date cannot be after its expiry date.",
"rules": "Planning rules must be provided as a list.",
"rule-id": "A planning rule is missing its identifier.",
"duplicate-rule-id": "Two planning rules share the same identifier.",
@@ -268,92 +387,112 @@
"rule-type": "A planning rule has an unsupported type.",
"rule-quantity": "A planning rule needs a non-negative whole number of days.",
"rule-selector": "A planning rule has an invalid leave type.",
"rule-window": "An imposed period needs a start date on or before its end date.",
"rule-window": "An imposed period’s start date cannot be after its end date.",
"rule-weekday": "An \"If ... Then\" rule needs a valid weekday.",
"rule-mode": "An \"If ... Then\" rule has an unsupported placement.",
"earned-quantity": "An \"If ... Then\" rule needs a non-negative whole number of bonus days.",
"earned-type": "An \"If ... Then\" rule needs CP, RTT, or Other as its bonus type.",
"invalid-optimization-configuration": "Choose compatible planning elements, conditions, measure and aggregation, with a positive whole-day threshold when needed.",
"earned-quantity": "An \"If ... Then\" rule needs a non-negative whole number of earned days.",
"earned-type": "An \"If ... Then\" rule needs CP, RTT, or Other as the type of its earned days.",
"invalid-optimization-configuration": "This combination is not possible. Change the elements, conditions, measure or calculation mode; the threshold, if there is one, must be a positive whole number.",
"unsupported-optimization-configuration": "This rule uses an unsupported combination of planning elements and measures.",
"horizon": "The planning period is required.",
"horizon-start": "The planning period start must be a valid calendar date.",
"horizon-end": "The planning period end must be a valid calendar date.",
"horizon-order": "The planning period must start before it ends.",
"deadline": "The planning time limit must be a finite, non-negative number.",
"declared-days": "The declared non-working days are invalid."
"declared-days": "The already booked days are invalid."
},
"conflictDetails": "Why no plan can satisfy the obligations",
"conflictDetails": "Why no plan meets all your obligations",
"conflictingRules": "Conflicting rules",
"bottleneck": "Bottleneck",
"incompleteDetails": "What completed before calculation stopped",
"incumbentExplanation": "This explains the best valid incumbent; later quality stages did not complete.",
"bottleneck": "Cause of the blockage",
"incompleteDetails": "Where the calculation stopped",
"incumbentExplanation": "This plan is the best one found before the calculation stopped. It can still be improved.",
"completedStages": "Completed stages",
"uncompletedStages": "Interrupted or unstarted stages",
"uncompletedStages": "Unfinished stages",
"none": "None",
"currentPlacement": "Current explained placement",
"currentPlacement": "Leave day explained",
"explainedPeriod": "Explained time-off period",
"outsideHorizon": "Context date outside the planning horizon",
"calendarHelp": "Select a leave day to see its contribution to your plan.",
"explanationHelp": "See the break you get and what each day changes.",
"outsideHorizon": "Outside the planning period",
"calendarHelp": "Select a leave day to see what it contributes to the plan.",
"explanationHelp": "For each booked day: its time-off period and what it changes.",
"technicalDetails": "Calculation details",
"appliedRules": {
"title": "Rules applied",
"entries": "Entries"
},
"timeOffPeriods": {
"title": "Your time-off periods",
"count": "Periods",
"help": "The days to take, period by period. Choose one to show it in the calendar."
},
"compareDates": "Compare other dates",
"stopComparing": "Close date comparison",
"explanation": {
"breakTitle": "Your break",
"leaveDays": "leave days used",
"freeDays": "weekend & holiday days",
"daysOff": "days off in a row",
"wholeBreak": "These totals cover the whole break, including the selected day.",
"leaveUsed": "This date uses 1 day from {balance}.",
"breakTitle": "Time-off period",
"bookedDays": {
"one": "already booked day",
"other": "already booked days"
},
"leaveDays": {
"one": "leave day booked",
"other": "leave days booked"
},
"freeDays": {
"one": "weekend or public-holiday day",
"other": "weekend and public-holiday days"
},
"daysOff": {
"one": "day off",
"other": "days off in a row"
},
"leaveUsed": "This date uses 1 day from “{balance}”.",
"expires": "Use this balance by",
"linkedRules": "Linked rules:",
"atRiskContribution": "Protects leave at risk of expiry.",
"linkedRules": "Rules behind this day:",
"atRiskContribution": "This day prevents losing leave that expires within the planning period.",
"impact": "What this day changes",
"impactHelp": "Compare the whole plan with and without this day of leave. All other leave dates stay the same; only changed totals are shown.",
"impactHelp": "The whole plan, with and without this leave day; other dates do not move. Only the totals that change are shown.",
"criterion": "Across your plan",
"withoutDay": "Without this day",
"withDay": "With this day",
"noChange": "These totals are unchanged. Rules and the final tie-breakers (balance expiry, then date) can still affect the choice.",
"priorityHelp": "Obligations are satisfied together. Active preferences are compared in your rule order. Only those rules drive new placements; earlier expiry and then dates break equal results.",
"noChange": "No total changes. On a tie, the calculation prefers the balance that expires earliest, then the earlier date.",
"tryDate": "Try another date",
"plannedDate": "Currently planned for:",
"currentPlan": "Current plan",
"alternative": "With this date",
"sameDate": "This is the planned date. Choose another date above to see the difference.",
"moveHelp": "Try moving this one day. All other leave dates stay the same.",
"comparisonUnavailable": "The comparison for the original date is unavailable, so the change cannot be shown.",
"moveHelp": "Try another date for this day. Other leave days do not move.",
"comparisonUnavailable": "The difference from the planned date could not be calculated.",
"objectives": {
"obligation-validity": {
"label": "Unmet obligations",
"help": "Number of required obligations left unsatisfied. A valid plan has zero."
"help": "A valid plan has none."
},
"unplaced-at-risk": {
"label": "Leave left at risk of expiry",
"help": "Unused days expiring within the planning period. Fewer is better."
"label": "Days that expire unbooked",
"help": "They expire within the planning period. Fewer is better."
},
"preference": {
"label": "Preference: {rule}",
"help": "Days or complete rule matches, depending on the rule. More is better."
"help": "Days or fully applied rules, depending on the rule. More is better."
},
"holiday-week-value": {
"label": "Holiday-week priority (points)",
"help": "Weighted score: Wednesday holidays count 3, Tuesday/Thursday 2, Monday/Friday 1. Higher is better."
"label": "Whole weeks taken around a public holiday (points)",
"help": "A holiday on Wednesday is worth 3 points, Tuesday or Thursday 2, Monday or Friday 1. More is better."
},
"non-working-day-gain": {
"label": "Weekend & holiday days in your breaks",
"label": "Weekend and public-holiday days in your time-off periods",
"help": "Days off that use no leave. More is better."
},
"longest-work-sequence": {
"label": "Most working days between leave days",
"help": "Weekends and public holidays are not counted. Fewer is better."
"label": "Longest stretch without leave",
"help": "In working days. Fewer is better."
},
"short-sequence-deficit": {
"label": "Penalty for short work gaps",
"help": "Each gap of 1–4 working days between leave days adds the days missing to reach 5. Lower is better."
"label": "Work stretches that are too short (days missing)",
"help": "For each return to work of fewer than 5 working days between two time-off periods, the days missing to reach 5. Fewer is better."
},
"supporting-placements": {
"label": "Days used from later-expiring balances",
"help": "Leave that could be saved beyond this planning period. Fewer is better."
"label": "Booked days that could have been kept for later",
"help": "Their balance only expires after the planning period. Fewer is better."
},
"balance-expiry": {
"label": "Earlier-expiring leave first",
@@ -364,8 +503,7 @@
"help": "Final tie-breaker when all other criteria are equal."
},
"optimization": {
"label": "{rule}: {summary}",
"help": "This optimization preference evaluates its saved configuration. Active preferences follow the displayed order; earlier preferences win before later ones."
"label": "{rule} — {summary}"
}
},
"stages": {
@@ -378,50 +516,49 @@
},
"unavailable": {
"non-working": "This is already a day off (weekend or public holiday). No leave is needed.",
"declared-day": "You already declared this day as non-working. Choose another working day.",
"declared-day": "You have already booked this day. Choose another working day.",
"occupied": "Another leave day is already planned here. Choose a free working day.",
"unavailable": "This leave balance cannot be used on this date.",
"expired": "This date is after the leave balance expires.",
"expired": "The balance has already expired on this date.",
"type-incompatible": "This leave type cannot be used on this date.",
"rule-invalid": "Using this date would break a planning rule.",
"invalid-optimization-configuration": "Choose compatible planning elements, conditions, measure and aggregation, with a positive whole-day threshold when needed.",
"rule-invalid": "On this date, this day would no longer meet the rules that booked it.",
"invalid-optimization-configuration": "This combination is not possible. Change the elements, conditions, measure or calculation mode; the threshold, if there is one, must be a positive whole number.",
"unsupported-optimization-configuration": "This rule uses an unsupported combination of planning elements and measures."
},
"preferenceHelp": {
"time_window": "Leave days in this preferred period. More is better.",
"if_then": "Complete matches for this rule. More is better."
"time_window": "Leave days within the requested period. More is better.",
"if_then": "Public holidays where the rule is fully applied. More is better."
}
},
"details": {
"intro": "The left column shows the plan without this leave day. The right shows the current plan.",
"balance": "Leave balance",
"available": "Available from",
"expires": "Expires on",
"criteria": "The planner’s priorities",
"criteriaHelp": "Read from top to bottom: the first difference takes priority. Select a criterion to see how it is calculated.",
"firstDifference": "First difference",
"criteriaHelp": "The calculation compares the criteria from top to bottom: the first one that differs decides. Open a criterion to see how it is counted.",
"firstDifference": "Deciding criterion",
"higher": "Higher is better",
"lower": "Lower is better",
"tieBreaks": "If the totals above are equal",
"audit": "Raw data · for debugging",
"auditHelp": "Original values, identifiers and contributions from this calculation.",
"supporting": "This day uses leave that could be saved beyond the planning period to improve your breaks.",
"auditHelp": "Internal values and identifiers of this calculation.",
"supporting": "This day could have been kept for later: it is booked here to improve your time off.",
"remainingReasons": {
"unavoidable-expiry": "Expired on {expiry}, before the plan starts on {start}. It cannot be placed in this period.",
"available-after-horizon": "Available only from {available}, after the last planning date, {end}.",
"no-working-date": "No working day falls within both the planning period and its availability and expiry dates.",
"all-dates-occupied": "All working days on which this balance can be used are already occupied by planned leave or already booked days.",
"preserved": "Kept for later: it expires after the planning period and the calculation retained no additional placement under your priorities.",
"active-priorities": "The calculation kept this balance unused under your active planning rules. Change the rules or their order to request a different plan.",
"calculation-incomplete": "The calculation was interrupted before planning finished. Leaving it unused is not a final decision.",
"not-established": "This calculation did not establish a precise reason for leaving it unused."
"unavoidable-expiry": "Expired on {expiry}, before the planning period starts on {start}. It could not be booked.",
"available-after-horizon": "Only available from {available}, after the end of the planning period ({end}).",
"no-working-date": "No working day in the planning period falls within this balance’s validity.",
"all-dates-occupied": "All the working days when this balance can be used are already taken by other leave.",
"preserved": "Kept for later: it expires only after the planning period, and booking it would not have improved the plan according to your rules.",
"active-priorities": "Your active rules did not lead to booking these days. Change the rules or their order to get a different plan.",
"calculation-incomplete": "The calculation stopped before the end: these days might have been booked.",
"not-established": "The calculation does not say why these days are not booked."
}
},
"comparison": {
"title": "Compare dates",
"preview": "Preview only. Your plan stays unchanged.",
"nearby": "Nearby available dates",
"noAlternatives": "No other date can use this leave day. You can still check a date to see why.",
"noAlternatives": "This leave day cannot be booked on any other date. Enter one to see why.",
"chooseDate": "Choose a date above to see what would change.",
"dateRange": "Planning period:",
"invalidDate": "Choose a valid date within the planning period shown above.",
@@ -453,6 +590,5 @@
"switchToMultiYearViewLabel": "Choose month and year",
"yearRangeLabel": "{start} to {end}"
},
"loading": "Calculating...",
"weekdaysShort": ["M", "T", "W", "T", "F", "S", "S"]
"loading": "Calculating…"
}
+299 -163
View File
@@ -3,30 +3,34 @@
"bookedDays": {
"enter": "Editar días ya reservados",
"booked": "Ya reservado",
"help": "Elija CP, RTT, Otro o Borrar y haga clic o arrastre entre fechas, incluso de varios meses. Suelte para guardar; Escape cancela. Cada día que ya tenga el tipo elegido se borra; los demás reciben ese tipo. Se omiten fines de semana y festivos. El rayado indica los días ya reservados, que se aplican en el próximo cálculo.",
"fixed": "Entrada fija del usuario, sin descontar el saldo restante ni decisión de optimización.",
"removed": "Declaración eliminada",
"help": "Elija CP, RTT, Otro o Borrar y haga clic en un día o arrastre entre dos fechas, incluso de varios meses; Escape cancela. Un día que ya tenga el tipo elegido se borra; los demás lo reciben. Se omiten fines de semana y festivos. Los días rayados ya están reservados: el próximo cálculo los tiene en cuenta.",
"fixed": "El cálculo no mueve los días ya reservados ni los descuenta de sus saldos.",
"removed": "Día ya reservado eliminado",
"erase": "Borrar",
"rangeSaved": "Días ya reservados guardados: {count} ({type}).",
"rangeRemoved": "Declaraciones eliminadas: {count}."
"rangeRemoved": "Días ya reservados eliminados: {count}."
},
"app": {
"title": "vac-optimizer",
"description": "Más espacio para descansar.",
"skipToPlan": "Ir a tu plan"
"skipToPlan": "Ir a tu plan",
"view": "Vista",
"configuration": "Configurar",
"plan": "Plan"
},
"userInput": {
"title": "Configura tus vacaciones",
"description": "Elige el período de planificación y añade cada saldo de vacaciones y su periodo de validez.",
"addVacationDay": "Añadir saldo de vacaciones",
"emptyBalances": "Todavía no hay ningún saldo de vacaciones. Añade el primero más abajo.",
"calculate": "Calcular plan",
"durationEstimate": "Espera aproximada: {range} {unit}",
"durationEstimate": "Tiempo de cálculo estimado: {range} {unit}",
"durationUnits": {
"seconds": "s",
"minutes": "min"
},
"remainingDaysWarning": "{count} día{plural} de permiso restante{plural}:",
"deleteEntry": "Eliminar entrada",
"remainingDaysWarning": "{count} día{plural} de permiso sin reservar:",
"deleteEntry": "Eliminar este saldo",
"chooseDate": "Caduca el",
"availableDate": "Disponible desde",
"days": "Días",
@@ -38,11 +42,11 @@
"remainingHorizon": "Plan calculado del {start} al {end}.",
"remainingEarnedFrom": "Permiso obtenido gracias a la regla «{rule}».",
"remainingSuggestions": {
"available-after-horizon": "Puedes ampliar el período planificado más allá de su fecha de disponibilidad y volver a calcular.",
"no-working-date": "Comprueba el período planificado y las fechas de validez de este saldo.",
"all-dates-occupied": "Puedes ampliar el período si la validez lo permite, o ajustar los días ya reservados y tus reglas, y volver a calcular.",
"preserved": "No es necesario hacer nada. Para solicitar su uso, añade una regla dentro de su período de validez y vuelve a calcular.",
"calculation-incomplete": "Repite el cálculo si quieres que termine la planificación."
"available-after-horizon": "Para usarlo, amplía el período de planificación más allá de su fecha de disponibilidad y vuelve a calcular.",
"no-working-date": "Comprueba el período de planificación y las fechas de validez de este saldo.",
"all-dates-occupied": "Para usarlo, cambia tus días ya reservados o tus reglas, o amplía el período de planificación si este saldo sigue siendo válido después, y vuelve a calcular.",
"preserved": "No hay nada que hacer. Para reservarlo igualmente, añade un período impuesto en fechas en las que se pueda usar y vuelve a calcular.",
"calculation-incomplete": "Repite el cálculo para que termine."
}
},
"dayTypes": {
@@ -52,7 +56,7 @@
"cp": "Vacaciones pagadas",
"other": "Otro",
"today": "Hoy",
"any": "Cualquier"
"any": "Cualquier tipo"
},
"settings": {
"title": "Ajustes",
@@ -69,33 +73,53 @@
"systemAppearance": "Apariencia actual del sistema",
"planningHorizon": "Período de planificación",
"planningStart": "Fecha de inicio (incluida)",
"lastPlanningDate": "Última fecha de planificación (incluida)",
"planningDatesHelp": "Elige cualquier fecha, incluso pasada. El calendario se actualiza al seleccionar Calcular plan.",
"lastPlanningDate": "Fecha de fin (incluida)",
"planningDatesHelp": "Se aceptan fechas pasadas. El calendario se actualiza en el próximo cálculo.",
"invalidDate": "Introduce dos fechas válidas.",
"horizonOrder": "La última fecha de planificación debe ser igual o posterior a la fecha de inicio.",
"invalidHorizon": "Corrige las fechas de planificación antes de calcular."
"horizonOrder": "La fecha de fin no puede ser anterior a la de inicio.",
"invalidHorizon": "Corrige primero las fechas del período de planificación."
},
"rules": {
"title": "Reglas de planificación",
"subtitle": "Gestionar reglas de optimización",
"active": "activas",
"subtitle": "Lo que el cálculo debe respetar o priorizar",
"active": {
"one": "{count} activa",
"other": "{count} activas"
},
"moveRuleUp": "Subir regla",
"moveRuleDown": "Bajar regla",
"dragRule": "Arrastrar para reordenar",
"ruleMoved": "{name}: posición {position} de {count}.",
"priorityInfo": "Las reglas de arriba tienen prioridad. Reordénalas con el tirador o las flechas.",
"ifThenTemplate": "Si un día festivo cae en <strong>{day}</strong>, colocar <strong>{placeDays}</strong> día(s) <strong>{placeType}</strong> <strong>{placement}</strong> y obtener <strong>{rewardDays}</strong> día(s) <strong>{rewardType}</strong> de bonificación.",
"timeWindowTemplate": "Colocar <strong>{placeDays}</strong> día(s) <strong>{placeType}</strong> entre el <strong>{startDate}</strong> y el <strong>{endDate}</strong>.",
"ifThenTemplate": "Si un festivo cae en <strong>{day}</strong>, tomar <strong>{placeDays}</strong> {placement}{earned}.",
"ifThenEarned": " y ganar <strong>{earnedDays}</strong>",
"timeWindowTemplate": "Tomar <strong>{placeDays}</strong> entre el <strong>{startDate}</strong> y el <strong>{endDate}</strong>.",
"dayCount": {
"one": "{count} día {type}",
"other": "{count} días {type}"
},
"summaryTypes": {
"cp": "de vacaciones pagadas",
"rtt": "de RTT",
"other": "de tipo Otro",
"any": "de cualquier tipo"
},
"summaryPlacement": {
"before": "justo antes",
"after": "justo después",
"around": "a ambos lados",
"auto": "alrededor donde más convenga"
},
"editRule": "Editar regla",
"deleteRule": "Eliminar regla",
"addRule": "Añadir una regla",
"place": "Colocar",
"place": "Tomar",
"ruleName": "Nombre de la regla",
"holidayFalls": "Día festivo cae en",
"holidayFalls": "Si un festivo cae en un",
"days": "Días",
"type": "Tipo",
"position": "Posición",
"getBonus": "Obtener en bonificación",
"getBonus": "Ganar",
"force": "Fuerza de la regla",
"obligation": "Obligación",
"preference": "Preferencia",
@@ -104,60 +128,73 @@
"cancel": "Cancelar",
"save": "Guardar",
"add": "Añadir",
"addRuleButton": "Añadir",
"newIfThenRule": "Nueva regla \"Si ... Entonces\"",
"newIfThenRule": "Nueva regla «Si … Entonces»",
"newTimeWindowRule": "Nuevo período impuesto",
"defaultNewRuleName": "Nueva regla",
"defaultNewPeriodName": "Nuevo período",
"import": {
"title": "Reglas compartidas",
"replaceStatement": "Estas reglas reemplazarán todas tus reglas actuales ({count}). Tus saldos, tus días ya reservados y tu período de planificación no cambian.",
"accept": "Reemplazar mis reglas",
"disabled": "Desactivada",
"invalidLink": "Este enlace compartido no es válido o está incompleto. Tus reglas no han cambiado."
},
"share": {
"action": "Compartir mis reglas",
"title": "Mis reglas de planificación de VacOptimizer",
"copied": "Enlace copiado",
"copyFailed": "No se pudo copiar",
"invalidRule": "Corrige la regla «{rule}» para compartir tus reglas."
},
"daysOfWeek": {
"0": "Domingo",
"1": "Lunes",
"2": "Martes",
"3": "Miércoles",
"4": "Jueves",
"5": "Viernes",
"6": "Sábado",
"0": "Domingo"
"6": "Sábado"
},
"placement": {
"before": "Antes",
"after": "Después",
"around": "Alrededor",
"auto": "Auto (Mejor opción)"
"auto": "Automático (mejor opción)"
},
"optimization": {
"newRule": "Nueva regla de Optimización",
"defaultName": "Prevención de pérdidas",
"newRule": "Nueva regla de optimización",
"defaultName": "Evitar perder días",
"elementsLabel": "Elementos del plan",
"conditionsLabel": "Condiciones (deben cumplirse todas)",
"measureLabel": "Medida",
"aggregationLabel": "Agregación",
"directionLabel": "Dirección",
"thresholdLabel": "Umbral de preferencia en días laborables",
"thresholdSummary": "umbral de preferencia: {count} días laborables",
"aggregationLabel": "Modo de cálculo",
"directionLabel": "Objetivo",
"thresholdLabel": "Umbral en días laborables",
"thresholdSummary": "umbral: {count} días laborables",
"summary": "{direction} {aggregation}: {measure} — {elements}{conditions}.",
"invalidConfiguration": "Elija elementos, condiciones, medidas y agregaciones compatibles, con un umbral entero positivo cuando sea necesario.",
"invalidConfiguration": "Esta combinación no es posible. Cambia los elementos, las condiciones, la medida o el modo de cálculo; el umbral, si lo hay, debe ser un entero positivo.",
"nameRequired": "Introduzca un nombre para la regla.",
"elements": {
"leave-balances": "Saldos de vacaciones",
"public-holiday-weeks": "Semanas con festivos",
"time-off-periods": "Períodos sin trabajo",
"work-sequences": "Secuencias de trabajo",
"leave-placements": "Vacaciones colocadas"
"time-off-periods": "Períodos de descanso",
"work-sequences": "Períodos de trabajo",
"leave-placements": "Días de permiso reservados"
},
"conditions": {
"at-risk": "En riesgo de caducar",
"complete": "Completas",
"internal": "Internas",
"non-empty": "No vacías",
"supporting": "De apoyo"
"at-risk": "Que vencen dentro del período de planificación",
"complete": "Tomadas enteras",
"internal": "Entre dos períodos de descanso",
"non-empty": "Al menos un día laborable",
"supporting": "De un saldo que vence después del período de planificación"
},
"measures": {
"unplaced-quantity": "Cantidad no colocada",
"public-holiday-week-value": "Valor de las semanas festivas",
"non-working-day-gain": "Ganancia de días sin trabajo",
"work-sequence-length": "Longitud de las secuencias de trabajo",
"work-sequence-deficit": "Déficit de las secuencias de trabajo",
"placement-count": "Número de colocaciones"
"unplaced-quantity": "Días sin reservar",
"public-holiday-week-value": "Puntos de las semanas con festivo",
"non-working-day-gain": "Días de fin de semana y festivos incluidos",
"work-sequence-length": "Días laborables seguidos",
"work-sequence-deficit": "Días que faltan para llegar al umbral",
"placement-count": "Número de días reservados"
},
"aggregations": {
"sum": "Suma",
@@ -167,6 +204,65 @@
"directions": {
"minimize": "Minimizar",
"maximize": "Maximizar"
},
"plain": {
"goals": {
"minimize": "Reducir {quantity}",
"maximize": "Aumentar {quantity}"
},
"intents": {
"unplacedAtRisk": "Tomar los días que vencen durante el período de planificación, para perder el menor número posible",
"holidayWeekValue": "Tomar la semana entera cuando incluye un festivo, sobre todo si cae a mitad de semana",
"nonWorkingDayGain": "Pegar las vacaciones a los fines de semana y festivos, para ganar el máximo de días libres sin tomarlos como vacaciones",
"longestWorkSequence": "Repartir las vacaciones para acortar el tramo más largo de trabajo sin vacaciones",
"shortSequenceDeficit": "Evitar volver al trabajo durante menos de {threshold} entre dos períodos de descanso",
"supportingPlacements": "Tomar el menor número posible de días que solo vencen después del período de planificación, para guardarlos para más adelante"
},
"count": "el número de {elements}{scope}",
"elements": {
"leave-balances": "saldos de vacaciones",
"public-holiday-weeks": "semanas con festivo",
"time-off-periods": "períodos de descanso",
"work-sequences": "períodos de trabajo",
"leave-placements": "días de permiso tomados"
},
"quantities": {
"unplaced-quantity": {
"sum": "los días sin usar{scope}",
"maximum": "el mayor número de días sin usar de un mismo saldo{scope}"
},
"public-holiday-week-value": {
"sum": "los puntos de las semanas con festivo{scope}, de 1 por festivo en lunes o viernes a 3 en miércoles",
"maximum": "los puntos de la mejor semana con festivo{scope}, de 1 por festivo en lunes o viernes a 3 en miércoles"
},
"non-working-day-gain": {
"sum": "los días de fin de semana y festivos incluidos en los períodos de descanso",
"maximum": "los días de fin de semana y festivos del período de descanso que más tiene"
},
"work-sequence-length": {
"sum": "el total de días trabajados{scope}",
"maximum": "el período de trabajo más largo{scope}"
},
"work-sequence-deficit": {
"sum": "los días que faltan a los períodos de trabajo{scope} para llegar a {threshold}",
"maximum": "el mayor número de días que le faltan a un período de trabajo{scope} para llegar a {threshold}"
},
"placement-count": {
"sum": "el número de días de permiso tomados{scope}",
"maximum": "la presencia de al menos un día de permiso tomado{scope}"
}
},
"scopes": {
"at-risk": " con vencimiento dentro del período de planificación",
"complete": " sin ningún día trabajado",
"supporting": " como extra de saldos con vencimiento posterior al período de planificación",
"non-empty": " de al menos un día laborable",
"internal": " entre dos períodos de descanso"
},
"workingDays": {
"one": "{count} día laborable",
"other": "{count} días laborables"
}
}
}
},
@@ -174,30 +270,56 @@
"statistics": {
"open": "Estadísticas",
"title": "Estadísticas del plan",
"leaveDays": "Nuevos días de permiso",
"averageWorkSequence": "Secuencia de trabajo media",
"averageTimeOffPeriod": "Período de descanso medio",
"longestTimeOffPeriod": "Período de descanso más largo",
"weekendConnectedHolidays": "Festivos conectados con un fin de semana",
"workingDays": "días laborables",
"calendarDays": "días naturales",
"partialPlan": "Plan parcial",
"help": "Estadísticas del plan calculado. Los días ya reservados definen los períodos de descanso y trabajo sin consumir de nuevo los saldos restantes.",
"earnedLeave": "Permisos adquiridos antes de su uso",
"leaveDaysUnit": "días",
"earnedLeaveByRule": "Permisos adquiridos por regla"
"help": "Los días ya reservados cuentan en tus periodos de descanso, no en los días por tomar.",
"leaveDays": "Días de vacaciones tomados",
"outOf": "de {total}",
"unplaced": "Días de vacaciones sin tomar",
"unplacedDays": {
"one": "{count} día sin tomar",
"other": "{count} días sin tomar"
},
"lostDays": {
"one": "{count} de ellos perdido",
"other": "{count} de ellos perdidos"
},
"lostHelp": "Un día perdido vence antes de poder tomarse.",
"keptHelp": "No se pierde nada: el vencimiento cae después del período de planificación.",
"daysOff": "Días de descanso en total",
"weekendAndHolidayDays": {
"one": "incluido {count} día de fin de semana o festivo",
"other": "incluidos {count} días de fin de semana y festivos"
},
"periods": "Periodos de descanso",
"longestPeriod": {
"one": "el más largo: {count} día",
"other": "el más largo: {count} días"
},
"longestWorkSequence": "Tramo más largo sin vacaciones",
"workedDays": {
"one": "día trabajado",
"other": "días trabajados"
},
"bridgedHolidays": "Festivos que hacen puente",
"earnedLeave": "Días ganados gracias a tus reglas",
"oneWorkdayWeeks": {
"one": "{count} semana con un solo día trabajado",
"other": "{count} semanas con un solo día trabajado"
},
"oneWorkdayHelp": "Ir a trabajar un solo día en toda una semana rara vez es deseable.",
"onlyWorkday": "Único día trabajado",
"workingDays": "días laborables",
"calendarDays": "días naturales"
},
"calculationDate": "Fecha del cálculo",
"futureEntitlement": "Derecho futuro generado",
"includedEntitlement": "Derecho ya incluido en los saldos declarados",
"futureEntitlement": "Días ganados",
"includedEntitlement": "Días ganados, ya incluidos en tus saldos",
"title": "Tu año optimizado",
"daysPlaced": "Días de vacaciones asignados",
"daysGained": "Días no laborables ganados",
"longestWorkSequence": "Período de trabajo más largo",
"invitation": "Añade tus saldos de vacaciones y calcula el plan para verlo aquí.",
"legend": "Leyenda del calendario",
"invalidInput": "Los datos de planificación no son válidos.",
"conflict": "Las obligaciones no se pueden satisfacer juntas.",
"incomplete": "El cálculo se detuvo antes de completar todas las etapas de calidad.",
"invalidInput": "El cálculo no ha podido empezar: hay datos que corregir.",
"conflict": "Tus obligaciones no pueden cumplirse todas a la vez.",
"incomplete": "El cálculo se detuvo antes del final.",
"cancel": "Cancelar",
"cancelling": "Cancelando…",
"progress": {
@@ -215,42 +337,39 @@
"cancelled": "Cálculo cancelado",
"cancelledPartial": "Cálculo cancelado — plan parcial",
"connectionLost": "Se perdió la conexión con el servidor. Use «Calcular plan» para intentarlo de nuevo.",
"error": "El planificador encontró un error inesperado.",
"error": "El cálculo ha encontrado un error inesperado.",
"complete": "Plan calculado.",
"whyPlacement": "Entender tus días de permiso",
"placementNavigation": "Navegación por las explicaciones de las asignaciones",
"placementNavigation": "Pasar de un día de permiso a otro",
"placement": "Día de permiso",
"placements": "asignaciones",
"of": "de",
"first": "Primera asignación",
"previous": "Asignación anterior",
"next": "Asignación siguiente",
"last": "Última asignación",
"remaining": "Días sin usar en el plan final",
"balanceRemaining": "restantes",
"counterfactual": "Fechas alternativas",
"counterfactualLoading": "Analizando cada fecha del horizonte…",
"counterfactualReady": "Las fechas alternativas están listas.",
"counterfactualError": "No se pudieron calcular las fechas alternativas.",
"first": "Primer día de permiso",
"previous": "Día de permiso anterior",
"next": "Día de permiso siguiente",
"last": "Último día de permiso",
"remaining": "Días sin reservar en este saldo",
"counterfactual": "Fecha comparada",
"counterfactualLoading": "Comprobando las demás fechas posibles…",
"counterfactualReady": "Ya puedes comparar otras fechas.",
"counterfactualError": "No se pudieron comprobar las demás fechas.",
"retryCounterfactual": "Reintentar el análisis de fechas",
"eligible": "Válida",
"ineligible": "No válida",
"reason": "Motivo",
"eligible": "Disponible",
"ineligible": "No disponible",
"explanationError": "No se pudo generar la explicación.",
"reasons": {
"user-cancelled": "El usuario canceló el cálculo.",
"deadline": "La planificación se detuvo al alcanzar su límite de tiempo, antes de completar todas las etapas de calidad.",
"connection-lost": "Se perdió la conexión con el servidor de planificación.",
"stale-calculation": "La planificación se detuvo porque comenzó un cálculo más reciente.",
"worker-error": "El proceso de cálculo aislado falló de forma inesperada.",
"worker-unavailable": "No se pudo iniciar la planificación porque la ejecución aislada no está disponible.",
"planner-error": "El planificador encontró un error inesperado.",
"user-cancelled": "Has cancelado el cálculo.",
"deadline": "El cálculo alcanzó su límite de tiempo antes de completar todas sus etapas.",
"connection-lost": "Se perdió la conexión con el servidor.",
"stale-calculation": "El cálculo se detuvo porque empezó otro más reciente.",
"worker-error": "El cálculo falló de forma inesperada.",
"worker-unavailable": "El cálculo no ha podido empezar.",
"planner-error": "El cálculo ha encontrado un error inesperado.",
"explanation-error": "Un error inesperado interrumpió la explicación.",
"earned-entitlement-order": "El permiso obtenido solo estuvo disponible después de su último período de descanso combinado.",
"typed-capacity": "Las obligaciones requieren más permisos de un tipo de los que hay disponibles.",
"horizon-bottleneck": "El período de planificación no contiene fechas válidas para al menos una obligación.",
"earned-entitlement-bottleneck": "El permiso obtenido no está disponible con la antelación suficiente para cumplir todas las obligaciones.",
"joint-date-conflict": "Las fechas que exigen las obligaciones no se pueden cumplir a la vez."
"earned-entitlement-order": "Los días ganados solo están disponibles después del final del período de descanso que los genera, demasiado tarde para tus obligaciones.",
"typed-capacity": "Tus obligaciones necesitan más días de un tipo de permiso de los que contienen tus saldos.",
"horizon-bottleneck": "Al menos una obligación no tiene ninguna fecha posible en el período de planificación.",
"earned-entitlement-bottleneck": "Los días ganados llegan demasiado tarde para cumplir todas tus obligaciones.",
"joint-date-conflict": "Tus obligaciones exigen fechas incompatibles entre sí."
},
"validationReasons": {
"balances": "Los saldos de permisos deben proporcionarse como una lista.",
@@ -260,7 +379,7 @@
"balance-quantity": "Un saldo de permisos necesita un número entero de días no negativo.",
"balance-availability": "Un saldo de permisos tiene una fecha de disponibilidad no válida.",
"balance-expiry": "Un saldo de permisos necesita una fecha de vencimiento válida.",
"balance-dates": "Un saldo de permisos debe estar disponible a más tardar en su fecha de vencimiento.",
"balance-dates": "La fecha de disponibilidad de un saldo de vacaciones no puede ser posterior a su fecha de vencimiento.",
"rules": "Las reglas de planificación deben proporcionarse como una lista.",
"rule-id": "A una regla de planificación le falta su identificador.",
"duplicate-rule-id": "Dos reglas de planificación tienen el mismo identificador.",
@@ -268,92 +387,112 @@
"rule-type": "Una regla de planificación tiene un tipo no admitido.",
"rule-quantity": "Una regla de planificación necesita un número entero de días no negativo.",
"rule-selector": "Una regla de planificación tiene un tipo de permiso no válido.",
"rule-window": "Un período impuesto necesita una fecha de inicio que no sea posterior a la de fin.",
"rule-window": "La fecha de inicio de un período impuesto no puede ser posterior a su fecha de fin.",
"rule-weekday": "Una regla «Si … Entonces» necesita un día de la semana válido.",
"rule-mode": "Una regla «Si … Entonces» tiene una colocación no admitida.",
"earned-quantity": "Una regla «Si … Entonces» necesita un número entero de días de bonificación no negativo.",
"earned-type": "Una regla «Si … Entonces» necesita Vacaciones pagadas, RTT u Otro como tipo de bonificación.",
"invalid-optimization-configuration": "Elija elementos, condiciones, medidas y agregaciones compatibles, con un umbral entero positivo cuando sea necesario.",
"earned-quantity": "Una regla «Si … Entonces» necesita un número entero no negativo de días ganados.",
"earned-type": "Una regla «Si … Entonces» necesita Vacaciones pagadas, RTT u Otro como tipo de los días ganados.",
"invalid-optimization-configuration": "Esta combinación no es posible. Cambia los elementos, las condiciones, la medida o el modo de cálculo; el umbral, si lo hay, debe ser un entero positivo.",
"unsupported-optimization-configuration": "Esta regla combina elementos del plan y medidas incompatibles.",
"horizon": "El período de planificación es obligatorio.",
"horizon-start": "El inicio del período de planificación debe ser una fecha de calendario válida.",
"horizon-end": "El final del período de planificación debe ser una fecha de calendario válida.",
"horizon-order": "El período de planificación debe empezar antes de terminar.",
"deadline": "El límite de tiempo de la planificación debe ser un número finito no negativo.",
"declared-days": "Los días no laborables declarados no son válidos."
"declared-days": "Los días ya reservados no son válidos."
},
"conflictDetails": "Por qué ningún plan satisface las obligaciones",
"conflictDetails": "Por qué ningún plan cumple todas las obligaciones",
"conflictingRules": "Reglas en conflicto",
"bottleneck": "Cuello de botella",
"incompleteDetails": "Lo completado antes de detener el cálculo",
"incumbentExplanation": "Esto explica el mejor plan válido encontrado; las etapas de calidad posteriores no se completaron.",
"bottleneck": "Causa del bloqueo",
"incompleteDetails": "Hasta dónde llegó el cálculo",
"incumbentExplanation": "Este plan es el mejor encontrado antes de detener el cálculo. Aún puede mejorarse.",
"completedStages": "Etapas completadas",
"uncompletedStages": "Etapas interrumpidas o no iniciadas",
"none": "Ninguno",
"currentPlacement": "Asignación explicada actualmente",
"uncompletedStages": "Etapas no terminadas",
"none": "Ninguna",
"currentPlacement": "Día de permiso explicado",
"explainedPeriod": "Período de descanso explicado",
"outsideHorizon": "Fecha de contexto fuera del horizonte de planificación",
"calendarHelp": "Selecciona un día de permiso para ver su aportación al plan.",
"explanationHelp": "Consulta tu descanso y qué cambia con cada día.",
"outsideHorizon": "Fuera del período de planificación",
"calendarHelp": "Selecciona un día de permiso para ver qué aporta al plan.",
"explanationHelp": "Para cada día reservado: su período de descanso y lo que cambia.",
"technicalDetails": "Detalles del cálculo",
"appliedRules": {
"title": "Reglas aplicadas",
"entries": "Elementos"
},
"timeOffPeriods": {
"title": "Tus periodos de descanso",
"count": "Periodos",
"help": "Los días que pedir, periodo a periodo. Elige uno para verlo en el calendario."
},
"compareDates": "Comparar otras fechas",
"stopComparing": "Cerrar comparación",
"explanation": {
"breakTitle": "Tu descanso",
"leaveDays": "días de permiso usados",
"freeDays": "días de fin de semana y festivos",
"daysOff": "días libres seguidos",
"wholeBreak": "Estos totales corresponden a todo el descanso, incluido el día seleccionado.",
"breakTitle": "Período de descanso",
"bookedDays": {
"one": "día ya reservado",
"other": "días ya reservados"
},
"leaveDays": {
"one": "día de permiso reservado",
"other": "días de permiso reservados"
},
"freeDays": {
"one": "día de fin de semana o festivo",
"other": "días de fin de semana y festivos"
},
"daysOff": {
"one": "día libre",
"other": "días libres seguidos"
},
"leaveUsed": "Esta fecha usa 1 día del saldo «{balance}».",
"expires": "Usa este saldo hasta el",
"linkedRules": "Reglas vinculadas:",
"atRiskContribution": "Protege permisos que podrían vencer.",
"linkedRules": "Reglas que originan este día:",
"atRiskContribution": "Evita perder permisos que vencen dentro del período de planificación.",
"impact": "Qué cambia con este día",
"impactHelp": "Compara todo el plan con y sin este día de permiso. Las demás fechas no cambian; solo se muestran los totales que varían.",
"criterion": "En todo tu plan",
"withoutDay": "Sin este día",
"withDay": "Con este día",
"noChange": "Estos totales son iguales. Las reglas y los últimos criterios de desempate (vencimiento del saldo y después fecha) aún pueden influir en la elección.",
"priorityHelp": "Las obligaciones se resuelven conjuntamente. Las preferencias activas se comparan en el orden de sus reglas. Solo esas reglas añaden vacaciones; la caducidad y luego las fechas resuelven los empates.",
"noChange": "Ningún total cambia. En caso de empate, el cálculo prefiere el saldo que vence antes y, después, la fecha anterior.",
"tryDate": "Probar otra fecha",
"plannedDate": "Fecha prevista actualmente:",
"plannedDate": "Fecha prevista:",
"currentPlan": "Plan actual",
"alternative": "Con esta fecha",
"sameDate": "Esta es la fecha prevista. Elige otra fecha arriba para ver la diferencia.",
"moveHelp": "Prueba a mover este día. Las demás fechas de permiso no cambian.",
"comparisonUnavailable": "La comparación de la fecha original no está disponible, por lo que no se puede mostrar el cambio.",
"moveHelp": "Prueba otra fecha para este día. Los demás días de permiso no cambian.",
"comparisonUnavailable": "No se pudo calcular la diferencia con la fecha prevista.",
"objectives": {
"obligation-validity": {
"label": "Obligaciones sin cumplir",
"help": "Número de reglas obligatorias incumplidas. Un plan válido tiene cero."
"help": "Un plan válido no tiene ninguna."
},
"unplaced-at-risk": {
"label": "Días sin usar que podrían vencer",
"help": "Días sin planificar que vencen durante el período. Menos es mejor."
"label": "Días que vencen sin reservar",
"help": "Vencen dentro del período de planificación. Menos es mejor."
},
"preference": {
"label": "Preferencia: {rule}",
"help": "Días o coincidencias completas, según la regla. Más es mejor."
"help": "Días o reglas completas, según la regla. Más es mejor."
},
"holiday-week-value": {
"label": "Prioridad de semanas con festivos (puntos)",
"help": "Puntuación ponderada: festivos en miércoles valen 3, martes/jueves 2 y lunes/viernes 1. Más es mejor."
"label": "Semanas completas con festivo (puntos)",
"help": "Un festivo en miércoles vale 3 puntos; en martes o jueves, 2; en lunes o viernes, 1. Más es mejor."
},
"non-working-day-gain": {
"label": "Fines de semana y festivos en tus descansos",
"label": "Días de fin de semana y festivos en tus periodos de descanso",
"help": "Días libres sin gastar permisos. Más es mejor."
},
"longest-work-sequence": {
"label": "Máximo de días laborables entre permisos",
"help": "No se cuentan fines de semana ni festivos. Menos es mejor."
"label": "Tramo más largo sin vacaciones",
"help": "En días laborables. Menos es mejor."
},
"short-sequence-deficit": {
"label": "Penalización por tramos cortos de trabajo",
"help": "Cada tramo de 1–4 días laborables entre permisos suma los días que faltan para llegar a 5. Menos es mejor."
"label": "Vueltas al trabajo demasiado cortas (días que faltan)",
"help": "Por cada vuelta al trabajo de menos de 5 días laborables entre dos períodos de descanso, los días que faltan para llegar a 5. Menos es mejor."
},
"supporting-placements": {
"label": "Días usados de saldos que vencen más tarde",
"help": "Permisos que podrían guardarse más allá de este período. Menos es mejor."
"label": "Días reservados que podrían guardarse para más tarde",
"help": "Su saldo solo vence después del período de planificación. Menos es mejor."
},
"balance-expiry": {
"label": "Primero los permisos que vencen antes",
@@ -364,8 +503,7 @@
"help": "Último desempate cuando los demás criterios son iguales."
},
"optimization": {
"label": "{rule}: {summary}",
"help": "Esta preferencia de optimización evalúa su configuración guardada. Las preferencias activas siguen el orden mostrado; las anteriores tienen prioridad."
"label": "{rule} — {summary}"
}
},
"stages": {
@@ -378,50 +516,49 @@
},
"unavailable": {
"non-working": "Ya es un día libre (fin de semana o festivo). No hace falta pedir permiso.",
"declared-day": "Ya has declarado este día como no laborable. Elige otro día laborable.",
"declared-day": "Ya has reservado este día. Elige otro día laborable.",
"occupied": "Ya hay otro permiso previsto aquí. Elige un día laborable disponible.",
"unavailable": "Este saldo de permisos no se puede usar en esta fecha.",
"expired": "Esta fecha es posterior al vencimiento del saldo.",
"expired": "El saldo ya había vencido en esta fecha.",
"type-incompatible": "Este tipo de permiso no se puede usar en esta fecha.",
"rule-invalid": "Usar esta fecha incumpliría una regla del plan.",
"invalid-optimization-configuration": "Elija elementos, condiciones, medidas y agregaciones compatibles, con un umbral entero positivo cuando sea necesario.",
"rule-invalid": "En esta fecha, este día ya no cumpliría las reglas que lo reservaron.",
"invalid-optimization-configuration": "Esta combinación no es posible. Cambia los elementos, las condiciones, la medida o el modo de cálculo; el umbral, si lo hay, debe ser un entero positivo.",
"unsupported-optimization-configuration": "Esta regla combina elementos del plan y medidas incompatibles."
},
"preferenceHelp": {
"time_window": "Días de permiso dentro del período preferido. Más es mejor.",
"if_then": "Coincidencias completas de esta regla. Más es mejor."
"time_window": "Días de permiso dentro del período pedido. Más es mejor.",
"if_then": "Festivos en los que la regla se aplica por completo. Más es mejor."
}
},
"details": {
"intro": "La columna izquierda muestra el plan sin este día de permiso. La derecha muestra el plan actual.",
"balance": "Saldo de permisos",
"available": "Disponible desde",
"expires": "Vence el",
"criteria": "Las prioridades del cálculo",
"criteriaHelp": "Lee de arriba abajo: la primera diferencia tiene prioridad. Selecciona un criterio para ver cómo se calcula.",
"firstDifference": "Primera diferencia",
"criteriaHelp": "Los criterios se comparan de arriba abajo: decide el primero que difiera. Abre un criterio para ver cómo se cuenta.",
"firstDifference": "Criterio decisivo",
"higher": "Más es mejor",
"lower": "Menos es mejor",
"tieBreaks": "Si los totales anteriores son iguales",
"audit": "Datos sin procesar · depuración",
"auditHelp": "Valores, identificadores y contribuciones originales de este cálculo.",
"supporting": "Este día usa permisos que podrían guardarse más allá del período planificado para mejorar tus descansos.",
"auditHelp": "Valores e identificadores internos de este cálculo.",
"supporting": "Este día podría haberse guardado para más tarde: se reserva aquí para mejorar tus periodos de descanso.",
"remainingReasons": {
"unavoidable-expiry": "Caducó el {expiry}, antes del inicio del plan el {start}. No puede colocarse en este período.",
"available-after-horizon": "Disponible solo a partir del {available}, después de la última fecha del plan, el {end}.",
"no-working-date": "Ningún día laborable está dentro del período planificado y entre sus fechas de disponibilidad y caducidad.",
"all-dates-occupied": "Todos los días laborables en los que puede utilizarse este saldo ya están ocupados por permisos planificados o días ya reservados.",
"preserved": "Guardado para más adelante: caduca después del período planificado y el cálculo no seleccionó ninguna colocación adicional según tus prioridades.",
"active-priorities": "El cálculo conservó este saldo sin utilizar según tus reglas activas. Cambia las reglas o su orden para solicitar otro plan.",
"calculation-incomplete": "El cálculo se interrumpió antes de terminar la planificación. Su falta de uso no es una decisión definitiva.",
"not-established": "Este cálculo no determinó un motivo preciso para dejarlo sin utilizar."
"unavoidable-expiry": "Venció el {expiry}, antes del inicio del plan el {start}. No se pudo reservar.",
"available-after-horizon": "Disponible solo a partir del {available}, después del final del período de planificación ({end}).",
"no-working-date": "Ningún día laborable del período de planificación cae dentro de la validez de este saldo.",
"all-dates-occupied": "Todos los días laborables en los que este saldo puede usarse ya están ocupados por otros permisos.",
"preserved": "Guardado para más tarde: vence solo después del período de planificación, y reservarlo no habría mejorado el plan según tus reglas.",
"active-priorities": "Tus reglas activas no han llevado a reservar estos días. Cambia las reglas o su orden para obtener otro plan.",
"calculation-incomplete": "El cálculo se detuvo antes del final: quizá estos días sí se habrían reservado.",
"not-established": "El cálculo no indica por qué estos días no están reservados."
}
},
"comparison": {
"title": "Comparar fechas",
"preview": "Solo una vista previa. Tu plan no cambia.",
"nearby": "Fechas cercanas disponibles",
"noAlternatives": "No hay otra fecha disponible para este día de permiso. Puedes comprobar una fecha para ver el motivo.",
"noAlternatives": "Este día de permiso no se puede reservar en ninguna otra fecha. Introduce una para ver el motivo.",
"chooseDate": "Elige una fecha arriba para ver qué cambiaría.",
"dateRange": "Período planificado:",
"invalidDate": "Elige una fecha válida dentro del período indicado arriba.",
@@ -453,6 +590,5 @@
"switchToMultiYearViewLabel": "Elegir mes y año",
"yearRangeLabel": "{start} a {end}"
},
"loading": "Calculando...",
"weekdaysShort": ["L", "M", "M", "J", "V", "S", "D"]
"loading": "Calculando…"
}
+313 -177
View File
@@ -3,30 +3,34 @@
"bookedDays": {
"enter": "Modifier les jours déjà posés",
"booked": "Déjà posé",
"help": "Choisissez CP, RTT, Autre ou Effacer, puis cliquez ou faites glisser entre deux dates, même sur plusieurs mois. Relâchez pour enregistrer ; Échap annule. Chaque jour du type choisi est retiré ; les autres prennent ce type. Week-ends et jours fériés sont ignorés. Les hachures indiquent les jours déjà posés, pris en compte au prochain calcul.",
"fixed": "Saisie utilisateur fixe, sans débit du solde restant ni décision d’optimisation.",
"removed": "Déclaration supprimée",
"help": "Choisissez CP, RTT, Autre ou Effacer, puis cliquez sur un jour ou faites glisser entre deux dates, même sur plusieurs mois ; Échap annule. Un jour qui a déjà le type choisi est retiré, les autres le prennent. Les week-ends et jours fériés sont ignorés. Les jours hachurés sont déjà posés : le prochain calcul en tient compte.",
"fixed": "Le calcul ne déplace pas les jours déjà posés et ne les déduit pas de vos soldes.",
"removed": "Jour déjà posé retiré",
"erase": "Effacer",
"rangeSaved": "Jours déjà posés enregistrés : {count} ({type}).",
"rangeRemoved": "Déclarations supprimées : {count}."
"rangeRemoved": "Jours déjà posés retirés : {count}."
},
"app": {
"title": "vac-optimizer",
"description": "Faites plus de place aux vacances.",
"skipToPlan": "Aller à votre planning"
"skipToPlan": "Aller à votre planning",
"view": "Affichage",
"configuration": "Réglages",
"plan": "Planning"
},
"userInput": {
"title": "Configurez vos congés",
"description": "Choisissez la période à planifier, puis ajoutez chaque solde de congés et sa période de validité.",
"addVacationDay": "Ajouter un solde de congés",
"emptyBalances": "Aucun solde de congés pour l’instant. Ajoutez le premier ci-dessous.",
"calculate": "Calculer le planning",
"durationEstimate": "Attente indicative : {range} {unit}",
"durationEstimate": "Temps de calcul estimé : {range} {unit}",
"durationUnits": {
"seconds": "s",
"minutes": "min"
},
"remainingDaysWarning": "{count} jour{plural} de congé restant{plural} :",
"deleteEntry": "Supprimer l’entrée",
"remainingDaysWarning": "{count} jour{plural} de congé non posé{plural} :",
"deleteEntry": "Supprimer ce solde",
"chooseDate": "Expire le",
"availableDate": "Disponible à partir du",
"days": "Jours",
@@ -38,21 +42,21 @@
"remainingHorizon": "Planning calculé du {start} au {end}.",
"remainingEarnedFrom": "Congés gagnés grâce à la règle « {rule} ».",
"remainingSuggestions": {
"available-after-horizon": "Vous pouvez prolonger la période planifiée au-delà de sa date de disponibilité, puis recalculer.",
"no-working-date": "Vérifiez la période planifiée et les dates de validité de ce solde.",
"all-dates-occupied": "Vous pouvez élargir la période si la validité le permet, ou ajuster vos jours déjà posés et vos règles, puis recalculer.",
"preserved": "Aucune action nécessaire. Pour demander son utilisation, ajoutez une règle sur une période où il est utilisable, puis recalculez.",
"calculation-incomplete": "Relancez le calcul si vous souhaitez qu’il termine la planification."
"available-after-horizon": "Pour l’utiliser, prolongez la période à planifier au-delà de sa date de disponibilité, puis recalculez.",
"no-working-date": "Vérifiez la période à planifier et les dates de validité de ce solde.",
"all-dates-occupied": "Pour l’utiliser, modifiez vos jours déjà posés ou vos règles, ou allongez la période à planifier si ce solde est encore valable après, puis recalculez.",
"preserved": "Rien à faire. Pour le poser quand même, ajoutez une période imposée à des dates où il est utilisable, puis recalculez.",
"calculation-incomplete": "Relancez le calcul pour qu’il aille jusqu’au bout."
}
},
"dayTypes": {
"weekend": "Week-end",
"closedDay": "Jour Férié",
"closedDay": "Jour férié",
"rtt": "RTT",
"cp": "Congé Payé",
"cp": "Congé payé",
"other": "Autre",
"today": "Aujourd'hui",
"any": "N'importe"
"today": "Aujourd’hui",
"any": "Tout type"
},
"settings": {
"title": "Paramètres",
@@ -69,33 +73,53 @@
"systemAppearance": "Apparence actuelle du système",
"planningHorizon": "Période à planifier",
"planningStart": "Date de début (incluse)",
"lastPlanningDate": "Dernière date de planification (incluse)",
"planningDatesHelp": "Choisissez vos dates, même passées. Le calendrier est mis à jour lorsque vous cliquez sur Calculer le planning.",
"invalidDate": "Saisissez deux dates calendaires valides.",
"horizonOrder": "La dernière date de planification doit être égale ou postérieure à la date de début.",
"invalidHorizon": "Corrigez les dates de planification avant de calculer."
"lastPlanningDate": "Date de fin (incluse)",
"planningDatesHelp": "Les dates passées sont acceptées. Le calendrier se met à jour au prochain calcul.",
"invalidDate": "Saisissez deux dates valides.",
"horizonOrder": "La date de fin ne peut pas précéder la date de début.",
"invalidHorizon": "Corrigez d’abord les dates de la période à planifier."
},
"rules": {
"title": "Règles de planification",
"subtitle": "Gérer les règles d'optimisation",
"active": "actives",
"subtitle": "Ce que le calcul doit respecter ou privilégier",
"active": {
"one": "{count} active",
"other": "{count} actives"
},
"moveRuleUp": "Monter la règle",
"moveRuleDown": "Descendre la règle",
"dragRule": "Glisser pour réordonner",
"ruleMoved": "{name} : position {position} sur {count}.",
"priorityInfo": "Les règles du haut sont prioritaires. Réorganisez-les avec la poignée ou les flèches.",
"ifThenTemplate": "Si un jour férié tombe un <strong>{day}</strong>, placer <strong>{placeDays}</strong> jour(s) <strong>{placeType}</strong> <strong>{placement}</strong> et obtenir <strong>{rewardDays}</strong> jour(s) <strong>{rewardType}</strong> en bonus.",
"timeWindowTemplate": "Placer <strong>{placeDays}</strong> jour(s) <strong>{placeType}</strong> entre le <strong>{startDate}</strong> et le <strong>{endDate}</strong>.",
"ifThenTemplate": "Si un jour férié tombe un <strong>{day}</strong>, poser <strong>{placeDays}</strong> {placement}{earned}.",
"ifThenEarned": " et gagner <strong>{earnedDays}</strong>",
"timeWindowTemplate": "Poser <strong>{placeDays}</strong> entre le <strong>{startDate}</strong> et le <strong>{endDate}</strong>.",
"dayCount": {
"one": "{count} jour {type}",
"other": "{count} jours {type}"
},
"summaryTypes": {
"cp": "de congés payés",
"rtt": "de RTT",
"other": "de type Autre",
"any": "de congé de tout type"
},
"summaryPlacement": {
"before": "juste avant",
"after": "juste après",
"around": "de part et d’autre",
"auto": "au meilleur moment autour de ce jour"
},
"editRule": "Modifier la règle",
"deleteRule": "Supprimer la règle",
"addRule": "Ajouter une règle",
"place": "Placer",
"place": "Poser",
"ruleName": "Nom de la règle",
"holidayFalls": "Jour férié tombe un",
"holidayFalls": "Si un jour férié tombe un",
"days": "Jours",
"type": "Type",
"position": "Position",
"getBonus": "Obtenir en bonus",
"getBonus": "Gagner",
"force": "Force de la règle",
"obligation": "Obligation",
"preference": "Préférence",
@@ -104,60 +128,73 @@
"cancel": "Annuler",
"save": "Enregistrer",
"add": "Ajouter",
"addRuleButton": "Ajouter",
"newIfThenRule": "Nouvelle Règle \"Si ... Alors\"",
"newTimeWindowRule": "Nouvelle Période Imposée",
"defaultNewRuleName": "Nouvelle Règle",
"defaultNewPeriodName": "Nouvelle Période",
"newIfThenRule": "Nouvelle règle « Si … Alors »",
"newTimeWindowRule": "Nouvelle période imposée",
"defaultNewRuleName": "Nouvelle règle",
"defaultNewPeriodName": "Nouvelle période",
"import": {
"title": "Règles partagées",
"replaceStatement": "Ces règles remplaceront toutes vos règles actuelles ({count}). Vos soldes, vos jours déjà posés et votre période à planifier ne changent pas.",
"accept": "Remplacer mes règles",
"disabled": "Désactivée",
"invalidLink": "Ce lien de partage est invalide ou incomplet. Vos règles n’ont pas changé."
},
"share": {
"action": "Partager mes règles",
"title": "Mes règles de planification VacOptimizer",
"copied": "Lien copié",
"copyFailed": "Copie impossible",
"invalidRule": "Corrigez la règle « {rule} » pour partager vos règles."
},
"daysOfWeek": {
"0": "Dimanche",
"1": "Lundi",
"2": "Mardi",
"3": "Mercredi",
"4": "Jeudi",
"5": "Vendredi",
"6": "Samedi",
"0": "Dimanche"
"6": "Samedi"
},
"placement": {
"before": "Avant",
"after": "Après",
"around": "Autour",
"auto": "Auto (Meilleur choix)"
"auto": "Automatique (meilleur choix)"
},
"optimization": {
"newRule": "Nouvelle règle d’Optimisation",
"defaultName": "Prévention des pertes",
"newRule": "Nouvelle règle d’optimisation",
"defaultName": "Éviter de perdre des jours",
"elementsLabel": "Éléments du planning",
"conditionsLabel": "Conditions (toutes doivent être vérifiées)",
"measureLabel": "Mesure",
"aggregationLabel": "Agrégation",
"directionLabel": "Direction",
"thresholdLabel": "Seuil de préférence en jours ouvrés",
"thresholdSummary": "seuil de préférence : {count} jours ouvrés",
"aggregationLabel": "Mode de calcul",
"directionLabel": "Objectif",
"thresholdLabel": "Seuil en jours ouvrés",
"thresholdSummary": "seuil : {count} jours ouvrés",
"summary": "{direction} {aggregation} : {measure} — {elements}{conditions}.",
"invalidConfiguration": "Choisissez des éléments, conditions, une mesure et une agrégation compatibles, avec un seuil entier positif si nécessaire.",
"invalidConfiguration": "Cette combinaison n’est pas possible. Changez les éléments, les conditions, la mesure ou le mode de calcul ; le seuil, s’il y en a un, doit être un entier positif.",
"nameRequired": "Saisissez un nom de règle.",
"elements": {
"leave-balances": "Soldes de congés",
"public-holiday-weeks": "Semaines avec jour férié",
"time-off-periods": "Périodes non travaillées",
"work-sequences": "Séquences de travail",
"leave-placements": "Congés placés"
"time-off-periods": "Périodes de repos",
"work-sequences": "Périodes de travail",
"leave-placements": "Jours posés"
},
"conditions": {
"at-risk": "À risque d’expiration",
"complete": "Complètes",
"internal": "Internes",
"non-empty": "Non vides",
"supporting": "D’appui"
"at-risk": "Expirant pendant la période planifiée",
"complete": "Prises en entier",
"internal": "Entre deux périodes de repos",
"non-empty": "D’au moins un jour ouvré",
"supporting": "Sur un solde expirant après la période planifiée"
},
"measures": {
"unplaced-quantity": "Quantité non placée",
"public-holiday-week-value": "Valeur des semaines fériées",
"non-working-day-gain": "Gain de jours non travaillés",
"work-sequence-length": "Longueur des séquences de travail",
"work-sequence-deficit": "Déficit des séquences de travail",
"placement-count": "Nombre de placements"
"unplaced-quantity": "Jours non posés",
"public-holiday-week-value": "Points des semaines avec jour férié",
"non-working-day-gain": "Jours de week-end et fériés inclus",
"work-sequence-length": "Jours travaillés d’affilée",
"work-sequence-deficit": "Jours manquants pour atteindre le seuil",
"placement-count": "Nombre de jours posés"
},
"aggregations": {
"sum": "Somme",
@@ -167,6 +204,65 @@
"directions": {
"minimize": "Minimiser",
"maximize": "Maximiser"
},
"plain": {
"goals": {
"minimize": "Réduire {quantity}",
"maximize": "Augmenter {quantity}"
},
"intents": {
"unplacedAtRisk": "Poser les jours qui expirent pendant la période planifiée, pour en perdre le moins possible",
"holidayWeekValue": "Prendre la semaine entière quand elle contient un jour férié, surtout s’il tombe en milieu de semaine",
"nonWorkingDayGain": "Coller les congés aux week-ends et aux jours fériés, pour gagner un maximum de jours de repos sans les poser",
"longestWorkSequence": "Répartir les congés pour raccourcir la plus longue période de travail sans congé",
"shortSequenceDeficit": "Éviter de reprendre le travail pour moins de {threshold} entre deux périodes de repos",
"supportingPlacements": "Poser le moins possible de jours qui n’expirent qu’après la période planifiée, afin de les garder pour plus tard"
},
"count": "le nombre de {elements}{scope}",
"elements": {
"leave-balances": "soldes de congés",
"public-holiday-weeks": "semaines avec un jour férié",
"time-off-periods": "périodes de repos",
"work-sequences": "périodes de travail",
"leave-placements": "jours posés"
},
"quantities": {
"unplaced-quantity": {
"sum": "les jours non posés{scope}",
"maximum": "le plus grand nombre de jours non posés d’un même solde{scope}"
},
"public-holiday-week-value": {
"sum": "les points des semaines avec un jour férié{scope}, chaque férié valant de 1 point (lundi, vendredi) à 3 points (mercredi)",
"maximum": "les points de la meilleure des semaines avec un jour férié{scope}, chaque férié valant de 1 point (lundi, vendredi) à 3 points (mercredi)"
},
"non-working-day-gain": {
"sum": "les jours de week-end et fériés compris dans les périodes de repos",
"maximum": "les jours de week-end et fériés de la période de repos qui en compte le plus"
},
"work-sequence-length": {
"sum": "le total des jours travaillés{scope}",
"maximum": "la plus longue période de travail{scope}"
},
"work-sequence-deficit": {
"sum": "les jours qui manquent aux périodes de travail{scope} pour atteindre {threshold}",
"maximum": "le plus grand nombre de jours qui manquent à une période de travail{scope} pour atteindre {threshold}"
},
"placement-count": {
"sum": "le nombre de jours posés{scope}",
"maximum": "la présence d’au moins un jour posé{scope}"
}
},
"scopes": {
"at-risk": " expirant pendant la période planifiée",
"complete": " prises en entier",
"supporting": " en plus sur des soldes expirant après la période planifiée",
"non-empty": " d’au moins un jour ouvré",
"internal": " entre deux périodes de repos"
},
"workingDays": {
"one": "{count} jour ouvré",
"other": "{count} jours ouvrés"
}
}
}
},
@@ -174,30 +270,56 @@
"statistics": {
"open": "Statistiques",
"title": "Statistiques du planning",
"leaveDays": "Nouveaux jours de congé posés",
"averageWorkSequence": "Séquence de travail moyenne",
"averageTimeOffPeriod": "Période de repos moyenne",
"longestTimeOffPeriod": "Plus longue période de repos",
"weekendConnectedHolidays": "Jours fériés reliés à un week-end",
"workingDays": "jours ouvrés",
"calendarDays": "jours calendaires",
"partialPlan": "Planning partiel",
"help": "Statistiques du planning calculé. Les jours déjà posés contribuent aux périodes de repos et de travail sans consommer à nouveau les soldes.",
"earnedLeave": "Congés acquis avant consommation",
"leaveDaysUnit": "jours",
"earnedLeaveByRule": "Congés acquis par règle"
"help": "Les jours déjà posés comptent dans vos périodes de repos, pas dans les jours à poser.",
"leaveDays": "Jours de congé posés",
"outOf": "sur {total}",
"unplaced": "Jours non posés",
"unplacedDays": {
"one": "{count} jour non posé",
"other": "{count} jours non posés"
},
"lostDays": {
"one": "dont {count} perdu",
"other": "dont {count} perdus"
},
"lostHelp": "Un jour perdu expire avant d’avoir pu être posé.",
"keptHelp": "Rien n’est perdu : l’expiration tombe après la période planifiée.",
"daysOff": "Jours de repos au total",
"weekendAndHolidayDays": {
"one": "dont {count} jour de week-end ou férié",
"other": "dont {count} jours de week-end et fériés"
},
"periods": "Périodes de repos",
"longestPeriod": {
"one": "la plus longue : {count} jour",
"other": "la plus longue : {count} jours"
},
"longestWorkSequence": "Plus longue période sans congé",
"workedDays": {
"one": "jour travaillé",
"other": "jours travaillés"
},
"bridgedHolidays": "Jours fériés qui font un pont",
"earnedLeave": "Jours gagnés grâce à vos règles",
"oneWorkdayWeeks": {
"one": "{count} semaine à un seul jour travaillé",
"other": "{count} semaines à un seul jour travaillé"
},
"oneWorkdayHelp": "Venir travailler un seul jour dans une semaine entière est rarement souhaitable.",
"onlyWorkday": "Seul jour travaillé",
"workingDays": "jours ouvrés",
"calendarDays": "jours calendaires"
},
"calculationDate": "Date du calcul",
"futureEntitlement": "Droit futur généré",
"includedEntitlement": "Droit déjà inclus dans les soldes reportés",
"futureEntitlement": "Jours gagnés",
"includedEntitlement": "Jours gagnés, déjà comptés dans vos soldes",
"title": "Votre année optimisée",
"daysPlaced": "Jours de congé placés",
"daysGained": "Jours non travaillés gagnés",
"longestWorkSequence": "Plus longue période travaillée",
"invitation": "Ajoutez vos soldes de congés puis calculez le planning pour l’afficher ici.",
"legend": "Légende du calendrier",
"invalidInput": "Les données de planification sont invalides.",
"conflict": "Les obligations ne peuvent pas être satisfaites ensemble.",
"incomplete": "Le calcul s’est arrêté avant la fin des critères de qualité.",
"invalidInput": "Le calcul n’a pas pu démarrer : des saisies sont à corriger.",
"conflict": "Vos obligations ne peuvent pas toutes être respectées en même temps.",
"incomplete": "Le calcul s’est arrêté avant la fin.",
"cancel": "Annuler",
"cancelling": "Annulation en cours…",
"progress": {
@@ -213,44 +335,41 @@
"overrun": "Plus long que prévu"
},
"cancelled": "Calcul annulé",
"cancelledPartial": "Calcul annulé — plan partiel",
"cancelledPartial": "Calcul annulé — planning partiel",
"connectionLost": "Connexion au serveur perdue. Utilisez « Calculer le planning » pour réessayer.",
"error": "Le planificateur a rencontré une erreur inattendue.",
"complete": "Plan calculé.",
"error": "Le calcul a rencontré une erreur inattendue.",
"complete": "Planning calculé.",
"whyPlacement": "Comprendre vos jours de congé",
"placementNavigation": "Navigation entre les explications des placements",
"placementNavigation": "Passer d’un jour de congé à l’autre",
"placement": "Jour de congé",
"placements": "placements",
"of": "sur",
"first": "Premier placement",
"previous": "Placement précédent",
"next": "Placement suivant",
"last": "Dernier placement",
"remaining": "Jours non utilisés dans le planning final",
"balanceRemaining": "restants",
"counterfactual": "Dates alternatives",
"counterfactualLoading": "Analyse de chaque date de l’horizon…",
"counterfactualReady": "Les dates alternatives sont prêtes.",
"counterfactualError": "Les dates alternatives n’ont pas pu être calculées.",
"first": "Premier jour de congé",
"previous": "Jour de congé précédent",
"next": "Jour de congé suivant",
"last": "Dernier jour de congé",
"remaining": "Jours non posés sur ce solde",
"counterfactual": "Date comparée",
"counterfactualLoading": "Analyse des autres dates possibles…",
"counterfactualReady": "Vous pouvez maintenant comparer d’autres dates.",
"counterfactualError": "Les autres dates n’ont pas pu être analysées.",
"retryCounterfactual": "Relancer l’analyse des dates",
"eligible": "Éligible",
"ineligible": "Inéligible",
"reason": "Raison",
"eligible": "Disponible",
"ineligible": "Indisponible",
"explanationError": "L’explication n’a pas pu être produite.",
"reasons": {
"user-cancelled": "Le calcul a été annulé par l’utilisateur.",
"deadline": "La planification s’est arrêtée à sa limite de temps avant la fin de tous les critères de qualité.",
"connection-lost": "La connexion au serveur de planification a été perdue.",
"stale-calculation": "La planification s’est arrêtée parce qu’un calcul plus récent a démarré.",
"worker-error": "Le processus de calcul isolé a échoué de manière inattendue.",
"worker-unavailable": "La planification n’a pas pu démarrer car l’exécution isolée est indisponible.",
"planner-error": "Le planificateur a rencontré une erreur inattendue.",
"user-cancelled": "Vous avez annulé le calcul.",
"deadline": "Le calcul a atteint sa limite de temps avant d’avoir terminé toutes ses étapes.",
"connection-lost": "La connexion au serveur a été perdue.",
"stale-calculation": "Ce calcul s’est arrêté parce qu’un calcul plus récent a démarré.",
"worker-error": "Le calcul a échoué de manière inattendue.",
"worker-unavailable": "Le calcul n’a pas pu démarrer.",
"planner-error": "Le calcul a rencontré une erreur inattendue.",
"explanation-error": "Une erreur inattendue a interrompu l’explication.",
"earned-entitlement-order": "Les congés gagnés ne sont devenus disponibles qu’après leur dernière période de repos regroupée.",
"typed-capacity": "Les obligations exigent plus de congés d’un même type que le solde disponible.",
"horizon-bottleneck": "La période à planifier ne contient aucune date éligible pour au moins une obligation.",
"earned-entitlement-bottleneck": "Des congés gagnés ne sont pas disponibles assez tôt pour satisfaire toutes les obligations.",
"joint-date-conflict": "Les dates exigées par les obligations ne peuvent pas être satisfaites ensemble."
"earned-entitlement-order": "Des jours gagnés ne sont disponibles qu’après la fin de la période de repos qui les fait gagner, trop tard pour vos obligations.",
"typed-capacity": "Vos obligations demandent plus de jours d’un type de congé que vos soldes n’en contiennent.",
"horizon-bottleneck": "Au moins une obligation n’a aucune date possible dans la période à planifier.",
"earned-entitlement-bottleneck": "Des jours gagnés arrivent trop tard pour respecter toutes vos obligations.",
"joint-date-conflict": "Vos obligations exigent des dates incompatibles entre elles."
},
"validationReasons": {
"balances": "Les soldes de congés doivent être fournis sous forme de liste.",
@@ -260,7 +379,7 @@
"balance-quantity": "Un solde de congés doit avoir un nombre entier de jours positif ou nul.",
"balance-availability": "Un solde de congés a une date de disponibilité invalide.",
"balance-expiry": "Un solde de congés doit avoir une date d’expiration valide.",
"balance-dates": "Un solde de congés doit être disponible au plus tard à sa date d’expiration.",
"balance-dates": "La date de disponibilité d’un solde de congés ne peut pas dépasser sa date d’expiration.",
"rules": "Les règles de planification doivent être fournies sous forme de liste.",
"rule-id": "Une règle de planification n’a pas d’identifiant.",
"duplicate-rule-id": "Deux règles de planification ont le même identifiant.",
@@ -268,92 +387,112 @@
"rule-type": "Une règle de planification a un type non pris en charge.",
"rule-quantity": "Une règle de planification doit avoir un nombre entier de jours positif ou nul.",
"rule-selector": "Une règle de planification a un type de congé invalide.",
"rule-window": "Une période imposée doit avoir une date de début qui ne dépasse pas sa date de fin.",
"rule-window": "La date de début d’une période imposée ne peut pas dépasser sa date de fin.",
"rule-weekday": "Une règle « Si … Alors » doit avoir un jour de la semaine valide.",
"rule-mode": "Une règle « Si … Alors » a un placement non pris en charge.",
"earned-quantity": "Une règle « Si … Alors » doit avoir un nombre entier de jours bonus positif ou nul.",
"earned-type": "Une règle « Si … Alors » doit avoir CP, RTT ou Autre comme type de bonus.",
"invalid-optimization-configuration": "Choisissez des éléments, conditions, une mesure et une agrégation compatibles, avec un seuil entier positif si nécessaire.",
"earned-quantity": "Une règle « Si … Alors » doit avoir un nombre entier de jours gagnés positif ou nul.",
"earned-type": "Une règle « Si … Alors » doit avoir CP, RTT ou Autre comme type des jours gagnés.",
"invalid-optimization-configuration": "Cette combinaison n’est pas possible. Changez les éléments, les conditions, la mesure ou le mode de calcul ; le seuil, s’il y en a un, doit être un entier positif.",
"unsupported-optimization-configuration": "Cette règle combine des éléments du planning et des mesures incompatibles.",
"horizon": "La période à planifier est obligatoire.",
"horizon-start": "Le début de la période à planifier doit être une date valide du calendrier.",
"horizon-end": "La fin de la période à planifier doit être une date valide du calendrier.",
"horizon-order": "Le début de la période à planifier doit précéder sa fin.",
"deadline": "La limite de temps de la planification doit être un nombre fini positif ou nul.",
"declared-days": "Les jours non travaillés déclarés sont invalides."
"declared-days": "Les jours déjà posés sont invalides."
},
"conflictDetails": "Pourquoi aucun plan ne satisfait les obligations",
"conflictDetails": "Pourquoi aucun planning ne respecte toutes vos obligations",
"conflictingRules": "Règles en conflit",
"bottleneck": "Goulot d’étranglement",
"incompleteDetails": "Étapes terminées avant l’arrêt du calcul",
"incumbentExplanation": "Cette explication concerne le meilleur plan valide trouvé ; les étapes de qualité suivantes ne sont pas terminées.",
"bottleneck": "Cause du blocage",
"incompleteDetails": "Où le calcul s’est arrêté",
"incumbentExplanation": "Ce planning est le meilleur trouvé avant l’arrêt du calcul. Il peut encore être amélioré.",
"completedStages": "Étapes terminées",
"uncompletedStages": "Étapes interrompues ou non démarrées",
"none": "Aucun",
"currentPlacement": "Placement expliqué actuellement",
"uncompletedStages": "Étapes non terminées",
"none": "Aucune",
"currentPlacement": "Jour de congé expliqué",
"explainedPeriod": "Période de repos expliquée",
"outsideHorizon": "Date de contexte hors de l’horizon de planification",
"calendarHelp": "Sélectionnez un jour de congé pour voir son apport au planning.",
"explanationHelp": "Découvrez votre pause et ce que chaque jour change.",
"outsideHorizon": "Hors de la période planifiée",
"calendarHelp": "Sélectionnez un jour de congé pour voir ce qu’il apporte au planning.",
"explanationHelp": "Pour chaque jour posé : sa période de repos et ce qu’il change.",
"technicalDetails": "Détails du calcul",
"appliedRules": {
"title": "Règles appliquées",
"entries": "Éléments"
},
"timeOffPeriods": {
"title": "Vos périodes de repos",
"count": "Périodes",
"help": "Les jours à poser, période par période. Choisissez-en une pour l’afficher dans le calendrier."
},
"compareDates": "Comparer d’autres dates",
"stopComparing": "Fermer la comparaison",
"explanation": {
"breakTitle": "Votre pause",
"leaveDays": "jours de congé posés",
"freeDays": "jours de week-end et fériés",
"daysOff": "jours de repos consécutifs",
"wholeBreak": "Ces totaux concernent toute la pause, y compris le jour sélectionné.",
"leaveUsed": "Cette date utilise 1 jour du solde « {balance} ».",
"expires": "Solde à utiliser au plus tard le",
"linkedRules": "Règles liées :",
"atRiskContribution": "Protège des congés à risque d’expiration.",
"breakTitle": "Période de repos",
"bookedDays": {
"one": "jour déjà posé",
"other": "jours déjà posés"
},
"leaveDays": {
"one": "jour de congé posé",
"other": "jours de congé posés"
},
"freeDays": {
"one": "jour de week-end ou férié",
"other": "jours de week-end et fériés"
},
"daysOff": {
"one": "jour de repos",
"other": "jours de repos consécutifs"
},
"leaveUsed": "Ce jour est pris sur le solde « {balance} ».",
"expires": "À utiliser au plus tard le",
"linkedRules": "Règles à l’origine de ce jour :",
"atRiskContribution": "Ce jour évite de perdre un congé qui expire pendant la période planifiée.",
"impact": "Ce que ce jour change",
"impactHelp": "Comparez tout le planning avec et sans ce jour de congé. Les autres dates restent identiques ; seuls les totaux qui changent sont affichés.",
"impactHelp": "Le planning entier, avec et sans ce jour de congé ; les autres dates ne bougent pas. Seuls les totaux qui changent sont affichés.",
"criterion": "Sur tout le planning",
"withoutDay": "Sans ce jour",
"withDay": "Avec ce jour",
"noChange": "Ces totaux sont identiques. Les règles et les derniers critères de départage (expiration du solde, puis date) peuvent encore influencer le choix.",
"priorityHelp": "Les obligations sont résolues conjointement. Les préférences actives sont comparées dans l’ordre de vos règles. Seules ces règles déclenchent des placements ; l’expiration puis les dates départagent les résultats égaux.",
"noChange": "Aucun total ne change. À égalité, le calcul préfère le solde qui expire le plus tôt, puis la date la plus proche.",
"tryDate": "Essayer une autre date",
"plannedDate": "Date actuellement prévue :",
"plannedDate": "Date prévue :",
"currentPlan": "Planning actuel",
"alternative": "Avec cette date",
"sameDate": "C’est la date prévue. Choisissez une autre date ci-dessus pour voir la différence.",
"moveHelp": "Essayez de déplacer ce jour. Les autres dates de congé restent identiques.",
"comparisonUnavailable": "La comparaison pour la date initiale est indisponible ; la différence ne peut donc pas être affichée.",
"moveHelp": "Essayez une autre date pour ce jour. Les autres jours de congé ne bougent pas.",
"comparisonUnavailable": "La différence avec la date prévue n’a pas pu être calculée.",
"objectives": {
"obligation-validity": {
"label": "Obligations non satisfaites",
"help": "Nombre de règles obligatoires non respectées. Un plan valide en compte zéro."
"label": "Obligations non respectées",
"help": "Un planning valide n’en compte aucune."
},
"unplaced-at-risk": {
"label": "Congés risquant d’expirer sans être utilisés",
"help": "Jours non posés expirant pendant la période planifiée. Moins, c’est mieux."
"label": "Jours qui expirent sans être posés",
"help": "Ils expirent pendant la période planifiée. Moins, c’est mieux."
},
"preference": {
"label": "Préférence : {rule}",
"help": "Jours ou occurrences complètes, selon la règle. Plus, c’est mieux."
"help": "Jours posés ou jours fériés traités, selon la règle. Plus, c’est mieux."
},
"holiday-week-value": {
"label": "Priorité des semaines avec jours fériés (points)",
"help": "Score pondéré : un férié le mercredi vaut 3, mardi/jeudi 2, lundi/vendredi 1. Plus, c’est mieux."
"label": "Semaines entières prises autour d’un jour férié (points)",
"help": "Un férié le mercredi vaut 3 points, le mardi ou le jeudi 2, le lundi ou le vendredi 1. Plus, c’est mieux."
},
"non-working-day-gain": {
"label": "Jours de week-end et fériés dans vos pauses",
"help": "Jours de repos sans utiliser de congé. Plus, c’est mieux."
"label": "Jours de week-end et fériés dans vos périodes de repos",
"help": "Des jours de repos sans poser de congé. Plus, c’est mieux."
},
"longest-work-sequence": {
"label": "Maximum de jours travaillés entre congés",
"help": "Week-ends et jours fériés exclus. Moins, c’est mieux."
"label": "Plus longue période sans congé",
"help": "En jours travaillés. Moins, c’est mieux."
},
"short-sequence-deficit": {
"label": "Pénalité pour les courtes reprises du travail",
"help": "Chaque reprise de 1 à 4 jours travaillés entre congés ajoute les jours manquants pour atteindre 5. Moins, c’est mieux."
"label": "Reprises du travail trop courtes (jours manquants)",
"help": "Pour chaque reprise de moins de 5 jours travaillés entre deux périodes de repos, les jours qui manquent pour arriver à 5. Moins, c’est mieux."
},
"supporting-placements": {
"label": "Jours utilisés sur des soldes expirant plus tard",
"help": "Congés qui pourraient être conservés au-delà de la période planifiée. Moins, c’est mieux."
"label": "Jours posés qui auraient pu être gardés pour plus tard",
"help": "Leur solde n’expire qu’après la période planifiée. Moins, c’est mieux."
},
"balance-expiry": {
"label": "Soldes expirant le plus tôt d’abord",
@@ -364,8 +503,7 @@
"help": "Dernier départage lorsque tous les autres critères sont égaux."
},
"optimization": {
"label": "{rule}: {summary}",
"help": "Cette préférence d’optimisation évalue sa configuration enregistrée. Les préférences actives suivent l’ordre affiché ; les premières passent avant les suivantes."
"label": "{rule} — {summary}"
}
},
"stages": {
@@ -378,50 +516,49 @@
},
"unavailable": {
"non-working": "C’est déjà un jour de repos (week-end ou jour férié). Aucun congé à poser.",
"declared-day": "Vous avez déjà déclaré ce jour comme non travaillé. Choisissez un autre jour travaillé.",
"declared-day": "Vous avez déjà posé ce jour. Choisissez un autre jour travaillé.",
"occupied": "Un autre congé est déjà prévu ici. Choisissez un jour travaillé libre.",
"unavailable": "Ce solde de congés ne peut pas être utilisé à cette date.",
"expired": "Cette date dépasse la date d’expiration du solde.",
"expired": "Le solde a déjà expiré à cette date.",
"type-incompatible": "Ce type de congé ne peut pas être utilisé à cette date.",
"rule-invalid": "Utiliser cette date ne respecterait pas une règle du planning.",
"invalid-optimization-configuration": "Choisissez des éléments, conditions, une mesure et une agrégation compatibles, avec un seuil entier positif si nécessaire.",
"rule-invalid": "À cette date, ce jour ne respecterait plus les règles qui l’ont fait poser.",
"invalid-optimization-configuration": "Cette combinaison n’est pas possible. Changez les éléments, les conditions, la mesure ou le mode de calcul ; le seuil, s’il y en a un, doit être un entier positif.",
"unsupported-optimization-configuration": "Cette règle combine des éléments du planning et des mesures incompatibles."
},
"preferenceHelp": {
"time_window": "Jours de congé dans cette période souhaitée. Plus, c’est mieux.",
"if_then": "Occurrences complètes de cette règle. Plus, c’est mieux."
"time_window": "Jours posés dans la période demandée. Plus, c’est mieux.",
"if_then": "Jours fériés pour lesquels la règle est entièrement appliquée. Plus, c’est mieux."
}
},
"details": {
"intro": "La colonne de gauche montre le planning sans ce jour de congé. Celle de droite montre le planning actuel.",
"balance": "Solde de congés",
"available": "Disponible à partir du",
"expires": "Expire le",
"criteria": "Les priorités du calcul",
"criteriaHelp": "Lisez de haut en bas : la première différence est prioritaire. Sélectionnez un critère pour comprendre son calcul.",
"firstDifference": "Première différence",
"criteriaHelp": "Le calcul compare les critères de haut en bas : le premier qui diffère décide. Ouvrez un critère pour voir comment il est compté.",
"firstDifference": "Critère décisif",
"higher": "Plus, c’est mieux",
"lower": "Moins, c’est mieux",
"tieBreaks": "Si les totaux ci-dessus sont égaux",
"audit": "Données brutes · débogage",
"auditHelp": "Valeurs, identifiants et contributions d’origine de ce calcul.",
"supporting": "Ce jour utilise des congés qui pourraient être conservés au-delà de la période planifiée pour améliorer vos pauses.",
"auditHelp": "Valeurs et identifiants internes de ce calcul.",
"supporting": "Ce jour aurait pu être gardé pour plus tard : il est posé ici pour améliorer vos périodes de repos.",
"remainingReasons": {
"unavoidable-expiry": "Expiré le {expiry}, avant le début du planning le {start}. Il ne peut pas être posé dans cette période.",
"available-after-horizon": "Disponible seulement à partir du {available}, après la dernière date du planning, le {end}.",
"no-working-date": "Aucun jour ouvré ne se trouve à la fois dans la période planifiée et entre ses dates de disponibilité et d’expiration.",
"all-dates-occupied": "Tous les jours ouvrés où ce solde est utilisable sont déjà occupés par des congés calculés ou des jours déjà posés.",
"preserved": "Conservé pour plus tard : il expire après la période planifiée et le calcul n’a pas retenu de pose supplémentaire selon vos priorités.",
"active-priorities": "Le calcul a conservé ce solde inutilisé selon vos règles actives. Modifiez les règles ou leur ordre pour demander un autre planning.",
"calculation-incomplete": "Le calcul a été interrompu avant de terminer la planification. Sa non-utilisation n’est pas une décision définitive.",
"not-established": "La raison précise de sa non-utilisation n’a pas été établie par ce calcul."
"unavoidable-expiry": "Expiré le {expiry}, avant le début de la période planifiée ({start}) : il ne pouvait pas être posé.",
"available-after-horizon": "Disponible seulement à partir du {available}, après la fin de la période planifiée ({end}).",
"no-working-date": "Aucun jour ouvré de la période planifiée ne tombe pendant la validité de ce solde.",
"all-dates-occupied": "Tous les jours ouvrés où ce solde est utilisable sont déjà pris par d’autres congés.",
"preserved": "Gardé pour plus tard : il n’expire qu’après la période planifiée, et le poser n’aurait pas amélioré le planning selon vos règles.",
"active-priorities": "Vos règles actives n’ont pas conduit à poser ces jours. Changez les règles ou leur ordre pour obtenir un autre planning.",
"calculation-incomplete": "Le calcul s’est arrêté avant la fin : ces jours auraient peut-être été posés.",
"not-established": "Le calcul n’indique pas pourquoi ces jours ne sont pas posés."
}
},
"comparison": {
"title": "Comparer les dates",
"preview": "Simulation uniquement. Votre planning reste inchangé.",
"nearby": "Dates proches disponibles",
"noAlternatives": "Aucune autre date ne permet de poser ce jour. Vous pouvez vérifier une date pour comprendre pourquoi.",
"noAlternatives": "Ce jour ne peut être posé à aucune autre date. Saisissez-en une pour savoir pourquoi.",
"chooseDate": "Choisissez une date ci-dessus pour voir ce qui changerait.",
"dateRange": "Période planifiée :",
"invalidDate": "Choisissez une date valide dans la période indiquée ci-dessus.",
@@ -453,6 +590,5 @@
"switchToMultiYearViewLabel": "Choisir le mois et l’année",
"yearRangeLabel": "{start} à {end}"
},
"loading": "Calcul en cours...",
"weekdaysShort": ["L", "M", "M", "J", "V", "S", "D"]
"loading": "Calcul en cours…"
}
+2
View File
@@ -107,6 +107,8 @@ html {
html {
scrollbar-gutter: stable;
// Keeps elements focused or scrolled to above the app's bottom bar, measured in app.ts.
scroll-padding-bottom: var(--action-bar-height, 0px);
}
body {
+64
View File
@@ -0,0 +1,64 @@
import type { ComponentFixture } from '@angular/core/testing';
/** Drives the rule dialog, which Material renders in an overlay outside the panel's fixture. */
export const ruleDialog = () => document.querySelector<HTMLElement>('mat-dialog-container');
function openDialog(): HTMLElement {
const dialog = ruleDialog();
if (!dialog) throw new Error('The rule dialog is not open');
return dialog;
}
export function dialogField(label: string, index = 0): HTMLElement {
const field = Array.from(openDialog().querySelectorAll<HTMLElement>('mat-form-field')).filter(
(candidate) => candidate.querySelector('mat-label')?.textContent?.trim() === label,
)[index];
if (!field) throw new Error(`Missing labelled control: ${label}`);
return field;
}
export function dialogButton(text: string): HTMLButtonElement {
const button = Array.from(openDialog().querySelectorAll<HTMLButtonElement>('button')).find(
(candidate) => candidate.textContent?.trim() === text,
);
if (!button) throw new Error(`Missing dialog button: ${text}`);
return button;
}
export async function typeInDialog(
fixture: ComponentFixture<unknown>,
label: string,
value: string,
index = 0,
) {
const input = dialogField(label, index).querySelector<HTMLInputElement>('input')!;
input.value = value;
input.dispatchEvent(new Event('input', { bubbles: true }));
await fixture.whenStable();
}
export async function chooseInDialog(
fixture: ComponentFixture<unknown>,
label: string,
text: string,
index = 0,
) {
const control = dialogField(label, index).querySelector<HTMLElement>('mat-select');
if (!control) throw new Error(`Missing select: ${label}`);
control.click();
await fixture.whenStable();
const option = Array.from(document.querySelectorAll<HTMLElement>('mat-option')).find(
(candidate) => candidate.textContent?.trim() === text,
);
if (!option) throw new Error(`Missing option: ${text}`);
option.click();
await fixture.whenStable();
// A multiple select stays open; its transparent backdrop is not the dialog's own.
document.querySelector<HTMLElement>('.cdk-overlay-transparent-backdrop')?.click();
await fixture.whenStable();
}
export async function clickDialogButton(fixture: ComponentFixture<unknown>, text: string) {
dialogButton(text).click();
await fixture.whenStable();
}