Author SHA1 Message Date
nessarandClaude Fable 5.2 eddf6532af chore(lint): keep the planner core's modules behind their entry point
CI / build (pull_request) Successful in 21s
CI / security (pull_request) Successful in 46s
CI / images (pull_request) Successful in 59s
CI / build (push) Successful in 33s
CI / validate (push) Successful in 41s
CI / security (push) Successful in 57s
CI / benchmark (push) Successful in 1m22s
CI / test (push) Successful in 3m23s
CI / required (push) Successful in 1s
CI / policy (pull_request) Successful in 17s
CI / validate (pull_request) Successful in 49s
CI / benchmark (pull_request) Successful in 1m1s
CI / test (pull_request) Successful in 3m47s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 21s
CI / images (push) Successful in 53s
The modules export their internals to each other, which would let a
spec or a service import them and freeze them. no-restricted-imports now
refuses leave-planner-core/* outside the folder and its entry point.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3BMPwb4HePhnBX7BwU
2026-11-30 18:16:53 +01:00
nessarandClaude Fable 5.2 9be4493518 refactor(planning): split the planner core into modules
leave-planner.core.ts held the whole planning algorithm in 5814 counted
lines. Its 239 declarations move, unchanged, to 16 modules under
leave-planner-core/, cut along the call graph so no module imports
another in a cycle. The file stays as the entry point: the two drivers
and the same 58 exported names, so no importer and no documented command
changes.

A script sliced the original by declaration, so each body is identical;
only export keywords and import lines are new, and Prettier re-wrapped
three signatures. Timed against the previous commit, interleaved, best
of 15: loaded year 1.010, three years 1.004, default rules 0.995.

This clears the last max-lines warning.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3BMPwb4HePhnBX7BwU
2026-11-30 18:16:53 +01:00
nessarandClaude Fable 5.2 ba3cd11087 test(planning): pin the earned-type reason of an IF_THEN rule
CI / build (pull_request) Successful in 30s
CI / security (pull_request) Successful in 1m34s
CI / images (pull_request) Successful in 1m6s
CI / required (push) Canceled after 0s
CI / validate (push) Canceled after 18s
CI / test (push) Canceled after 18s
CI / benchmark (push) Canceled after 19s
CI / security (push) Canceled after 20s
CI / build (push) Canceled after 20s
CI / policy (pull_request) Successful in 20s
CI / validate (pull_request) Successful in 38s
CI / benchmark (pull_request) Successful in 1m26s
CI / test (pull_request) Successful in 3m15s
CI / required (pull_request) Successful in 2s
CI / images (push) Canceled after 0s
CI / policy (push) Canceled after 19s
The merged condition in normalizeIfThenRule had no test: a reward
without a type, an unknown reward type, and an unknown type on a rule
that earns nothing each give exactly one earned-type reason.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3BMPwb4HePhnBX7BwU
2026-11-30 17:56:29 +01:00
nessarandClaude Fable 5.2 1b910bfd16 refactor(planning): split a placement-optimization round into its passes
optimizeRulePlacements ran the stage precomputation, the rule-specific
bundles, the generic date scan and the relocation chains in one body.
Each pass is now its own function over a search object, built once per
call, and a round object, built once per round; nothing new is allocated
per date. The steps and checks keep their order.

Timed against the previous commit, interleaved over 21 rounds on the
loaded year: best 2823 ms against 2830 ms.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3BMPwb4HePhnBX7BwU
2026-11-30 17:56:29 +01:00
nessarandClaude Fable 5.2 bc19d753b1 refactor(planning): name the two parts of the obligation search
satisfyObligations computed which later requirements may run first and
carried the date-choice recursion as an inner generator. They are now
extensionRequirementIndexes and chooseObligationDates. The steps and
checks keep their order; the benchmark ratios are unchanged (loaded year
0.74, default rules 0.89, against 0.77 and 0.91 before).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3BMPwb4HePhnBX7BwU
2026-11-30 17:56:29 +01:00
nessarandClaude Fable 5.2 79dba0259e refactor(planning): split the planning orchestrator into its stages
calculatePlanningSteps held the incumbent retention, the finishing of an
outcome, the obligation stage, the ranking of obligation solutions and
the interruption handling in one body of closures. Each is now a
module-level function over one PlanningWorkspace object, and the orchestrator
reads as the sequence of stages. Every yield, check and event keeps its
place and order.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3BMPwb4HePhnBX7BwU
2026-11-30 17:56:29 +01:00
nessarandClaude Fable 5.2 33f26248f8 refactor(planning): settle a planning run apart from its wiring
planInWorker mixed two things: the rules that resolve each of a run's
promises exactly once, and the wiring of the job, the liveness watchdog
and the message dispatch. createRunSettlement now owns the first and its
state; planInWorker keeps the second. The order of resolutions is
unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3BMPwb4HePhnBX7BwU
2026-11-30 17:56:29 +01:00
nessarandClaude Fable 5.2 2618e9ffc9 refactor(planning): move the job transport out of the planning service
The local worker, the remote socket with its fallback and the choice
between them move to leave-planner.jobs.ts, unchanged. The service keeps
the lifecycle and supersession and re-exports the job types, so no
importer changes. This clears the service's max-lines warning.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3BMPwb4HePhnBX7BwU
2026-11-30 17:17:19 +01:00
nessarandClaude Fable 5.2 b400d1d0b3 refactor(planning): evaluate a counterfactual date in its own function
analyzeCounterfactualInternal rebuilt the state, screened each date and
evaluated it in one body. stateFromPlan, counterfactualIneligibility and
evaluateCounterfactualDate now hold those parts, with the checks in the
same order.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3BMPwb4HePhnBX7BwU
2026-11-30 17:16:20 +01:00
nessarandClaude Fable 5.2 2188716df4 refactor(planning): validate an IF_THEN rule in its own function
normalizeRules validated three rule types inline. The IF_THEN part moves
to normalizeIfThenRule, and the two branches that pushed the same
earned-type reason become one condition. Reasons keep their order.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3BMPwb4HePhnBX7BwU
2026-11-30 17:16:20 +01:00
nessarandClaude Fable 5.2 3051390a90 refactor(benchmark): hold the scenarios in a module table
benchmarkScenarios was long only because it carried the scenario data.
The table is now a constant and the function only adds the presets, which
clears its max-lines-per-function warning. Requests are cloned before
use, so sharing the table between calls changes nothing.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3BMPwb4HePhnBX7BwU
2026-11-30 17:14:23 +01:00
nessarandClaude Fable 5.2 9eff2213ee chore(lint): warn on long files and long functions
CI / build (pull_request) Successful in 37s
CI / security (pull_request) Successful in 1m16s
CI / images (pull_request) Successful in 1m12s
CI / required (pull_request) Successful in 1s
CI / build (push) Successful in 35s
CI / validate (push) Successful in 38s
CI / benchmark (push) Successful in 49s
CI / security (push) Successful in 1m2s
CI / test (push) Successful in 3m11s
CI / required (push) Successful in 2s
CI / policy (pull_request) Successful in 11s
CI / validate (pull_request) Successful in 48s
CI / benchmark (pull_request) Successful in 1m35s
CI / test (pull_request) Successful in 3m37s
CI / policy (push) Successful in 16s
CI / images (push) Successful in 49s
max-lines (800) and max-lines-per-function (150) on non-spec source, at
warning level: the lint still passes, and the nine current warnings name
the planner core, the planning service and their longest functions.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 16:54:03 +01:00
nessarandClaude Fable 5.2 e461da8673 refactor(planning): report a calculation through one event stream
CI / build (pull_request) Successful in 21s
CI / security (pull_request) Successful in 59s
CI / images (pull_request) Successful in 50s
CI / validate (push) Successful in 28s
CI / build (push) Successful in 37s
CI / benchmark (push) Successful in 1m5s
CI / security (push) Successful in 58s
CI / test (push) Successful in 2m36s
CI / required (push) Successful in 1s
CI / policy (pull_request) Successful in 13s
CI / validate (pull_request) Successful in 29s
CI / benchmark (pull_request) Successful in 1m28s
CI / test (pull_request) Successful in 2m41s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 8s
CI / images (push) Successful in 53s
The engine took five positional callbacks and a sixth channel hidden in
the request (progress), and its only caller, the worker message handler,
turned them back into one message stream while tracking which had fired.
The entry points now take a single emit(event). PlanningEvent is defined
once and WorkerResponse reuses it, so the handler passes post straight
through; the engine itself holds the artifacts back to the end and
guarantees a result.

The frozen engines keep the callback signature. callback-signature.ts
gives the current engine that shape for the tools that drive both, and
is to be deleted once both frozen engines take emit (see the rebuild
notes). No change to the messages a job posts or to deadline accounting.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 16:49:02 +01:00
nessarandClaude Fable 5.2 a3d56ba06f fix(rules): keep calendar dates as planning dates from input to planner
CI / build (pull_request) Successful in 20s
CI / security (pull_request) Successful in 58s
CI / images (pull_request) Successful in 1m10s
CI / validate (push) Successful in 29s
CI / build (push) Successful in 25s
CI / benchmark (push) Successful in 1m9s
CI / security (push) Successful in 1m3s
CI / test (push) Successful in 2m53s
CI / required (push) Successful in 1s
CI / policy (pull_request) Successful in 13s
CI / validate (pull_request) Successful in 26s
CI / benchmark (pull_request) Successful in 1m27s
CI / test (pull_request) Successful in 2m45s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 18s
CI / images (push) Successful in 52s
A leave balance and a TIME_WINDOW rule held JavaScript Dates, so the
YYYY-MM-DD form the planner, the share link and the saved balances
already use was rebuilt in five places. A rule boundary was also saved
as a UTC instant and read back as one, which could move it by a day in
another time zone.

Both models now hold planning dates. A Date exists only at the date
pickers and where a date is shown. Saved rules move to format version 3:
older lists are read as before, each boundary taking the calendar date
it showed on the device, then rewritten once. The share link format and
the saved balances are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 13:37:56 +01:00
nessarandClaude Fable 5.2 ce6576635c refactor(planning): record a placement change where it is made
CI / build (pull_request) Successful in 22s
CI / security (pull_request) Successful in 59s
CI / images (pull_request) Successful in 56s
CI / build (push) Successful in 21s
CI / validate (push) Successful in 27s
CI / security (push) Successful in 47s
CI / benchmark (push) Successful in 1m3s
CI / test (push) Successful in 2m42s
CI / required (push) Successful in 1s
CI / policy (pull_request) Successful in 11s
CI / validate (pull_request) Successful in 27s
CI / benchmark (pull_request) Successful in 56s
CI / test (pull_request) Successful in 3m3s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 13s
CI / images (push) Successful in 53s
plan-observations caches by the identity of the placements Map and derives
a child's entry from its parent's. The caller had to call
notePlacementAdded or notePlacementRemoved before mutating a fresh copy,
and a forgotten call gave stale observations without an error.
addPlacement and removePlacement now record and mutate together, so the
ordering rule no longer lives in the engine. The three places that change
a Map without a derivation say why none is needed. No behaviour change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 13:30:19 +01:00
nessarandClaude Fable 5.2 6a1fb325fc refactor(planning): build the search context in one place
CI / build (pull_request) Successful in 27s
CI / security (pull_request) Successful in 1m6s
CI / images (pull_request) Successful in 54s
CI / required (pull_request) Successful in 2s
CI / validate (push) Successful in 29s
CI / build (push) Successful in 33s
CI / benchmark (push) Successful in 1m7s
CI / security (push) Successful in 1m4s
CI / test (push) Successful in 2m52s
CI / required (push) Successful in 1s
CI / policy (pull_request) Successful in 9s
CI / validate (pull_request) Successful in 32s
CI / benchmark (pull_request) Successful in 1m5s
CI / test (pull_request) Successful in 2m54s
CI / policy (push) Successful in 12s
CI / images (push) Successful in 56s
The engine's SearchContext was written out by hand in three places, each
cast with 'as SearchContext', and the calendar behind it was built two
ways. createSearchContext now lists the fields once with a checked return
type, and the checkpoint explanation and the date analysis take their
calendar from prepareCalendar like the calculation does. No behaviour
change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 12:43:57 +01:00
nessarandClaude Fable 5.2 690f0202ed feat(ui): declare a range of non-working days with a sideways finger drag (#373)
CI / build (pull_request) Successful in 27s
CI / security (pull_request) Successful in 59s
CI / images (pull_request) Successful in 1m14s
CI / required (pull_request) Successful in 1s
CI / validate (push) Successful in 29s
CI / build (push) Successful in 20s
CI / security (push) Successful in 56s
CI / benchmark (push) Successful in 1m32s
CI / test (push) Successful in 2m37s
CI / required (push) Successful in 1s
CI / policy (pull_request) Successful in 10s
CI / validate (pull_request) Successful in 33s
CI / benchmark (pull_request) Successful in 1m1s
CI / test (pull_request) Successful in 2m41s
CI / policy (push) Successful in 20s
CI / images (push) Successful in 51s
During declaration entry the calendar takes touch-action: pan-y, so a finger that starts up or down still scrolls and one that starts sideways follows the mouse range path. The help text is shortened and says how to start the gesture.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 12:06:20 +01:00
nessarandClaude Fable 5.2 55c0ef27b5 docs(context): define declaration entry (#373)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 11:49:24 +01:00
nessarandClaude Opus 5.5 b69437302d chore(deps): update bun to v1.4.5
CI / build (pull_request) Successful in 20s
CI / security (pull_request) Successful in 59s
CI / images (pull_request) Successful in 1m14s
CI / validate (push) Successful in 27s
CI / build (push) Successful in 37s
CI / benchmark (push) Successful in 1m7s
CI / security (push) Successful in 59s
CI / test (push) Successful in 2m40s
CI / required (push) Successful in 1s
CI / policy (pull_request) Successful in 9s
CI / validate (pull_request) Successful in 34s
CI / benchmark (pull_request) Successful in 1m29s
CI / test (pull_request) Successful in 2m43s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 11s
CI / images (push) Successful in 1m13s
Replaces Renovate PR #317, which bumped package.json alone and so failed
scripts/install-bun.sh. Move every pin together: packageManager, @types/bun,
the installer's version and four SHA-256 values (from the release's
SHASUMS256.txt), and both Docker stages to oven/bun:1.4.5-alpine, which also
ends the 1.4.4 drift the separate Docker update left in the Dockerfile.
Renovate now groups these packages in one PR without automerge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 11:13:56 +01:00
nessarandClaude Opus 5.5 203cf55661 chore(renovate): automerge by rebase, the merge method the repository allows
The repository allows only rebase and fast-forward merges, so Renovate's
merge-commit automerge failed ("Merging of PR failed" on the dashboard) and
left green minor updates such as #369 open. Document rebase as the merge method.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 11:13:38 +01:00
nessarandClaude Opus 5.5 9b43adbf7e chore(deps): update dependency jsdom to v31
CI / build (pull_request) Successful in 36s
CI / security (pull_request) Successful in 1m33s
CI / images (pull_request) Successful in 52s
CI / required (pull_request) Successful in 1s
CI / validate (push) Successful in 36s
CI / build (push) Successful in 28s
CI / benchmark (push) Successful in 1m11s
CI / security (push) Successful in 1m9s
CI / test (push) Failing after 3m5s
CI / required (push) Failing after 1s
CI / policy (pull_request) Successful in 8s
CI / validate (pull_request) Successful in 28s
CI / benchmark (pull_request) Successful in 1m0s
CI / test (pull_request) Successful in 2m35s
CI / policy (push) Successful in 10s
CI / images (push) Skipped
Replaces Renovate PR #370, whose lockfile conflicted with the Angular 22.3.0 update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 11:08:47 +01:00
renovate Bot 767738637d fix(deps): update angular monorepo to v22.3.0
CI / build (pull_request) Successful in 27s
CI / security (pull_request) Successful in 59s
CI / images (pull_request) Successful in 50s
CI / required (pull_request) Successful in 1s
CI / validate (push) Successful in 34s
CI / build (push) Successful in 22s
CI / benchmark (push) Successful in 1m38s
CI / security (push) Successful in 1m6s
CI / test (push) Failing after 3m11s
CI / required (push) Failing after 2s
CI / policy (pull_request) Successful in 10s
CI / validate (pull_request) Successful in 29s
CI / benchmark (pull_request) Successful in 1m11s
CI / test (pull_request) Successful in 2m51s
CI / policy (push) Successful in 17s
CI / images (push) Skipped
2026-11-30 10:56:07 +01:00
nessarandClaude Fable 5.2 3f83f486ba feat(ui): show declared day types as swatch chips that keep their label on one line
CI / build (pull_request) Successful in 22s
CI / security (pull_request) Successful in 55s
CI / images (pull_request) Successful in 51s
CI / required (pull_request) Successful in 1s
CI / validate (push) Successful in 30s
CI / build (push) Successful in 36s
CI / benchmark (push) Successful in 1m13s
CI / security (push) Successful in 1m1s
CI / test (push) Successful in 2m51s
CI / required (push) Successful in 1s
CI / policy (pull_request) Successful in 20s
CI / validate (pull_request) Successful in 35s
CI / benchmark (pull_request) Successful in 1m36s
CI / test (pull_request) Successful in 2m51s
CI / policy (push) Successful in 9s
CI / images (push) Successful in 49s
The chips that choose what a calendar tap declares wrapped their label
over two lines, hid a check that still took room, hatched the text of
the chosen one and left Erase alone on a third row.

Each chip now carries a swatch painted as the calendar paints a declared
day, with the check inside it when chosen. Dated CP chips take a row
each, RTT, Other and Erase share the last one, and four chips make two
rows of two. Reworks the chips added for #379.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 10:36:53 +01:00
nessarandClaude Fable 5.2 81482abfb1 docs(readme): say which date decides the earned day's expiry (#374)
CI / build (pull_request) Successful in 21s
CI / security (pull_request) Successful in 57s
CI / images (pull_request) Successful in 1m14s
CI / required (pull_request) Successful in 1s
CI / policy (pull_request) Successful in 19s
CI / validate (pull_request) Successful in 36s
CI / benchmark (pull_request) Successful in 1m38s
CI / test (pull_request) Successful in 2m52s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 03:53:33 +01:00
nessarandClaude Fable 5.2 9f5c163fac test(rules): restore the refusal of a reserve in a version-1 share link (#378)
The test was dropped by accident in d919fd9; without it nothing covered that refusal.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 03:53:33 +01:00
nessarandClaude Fable 5.2 0b387b884b fix(planning): keep a proven conflict at the deadline and check reserves without a snapshot (#376)
Two follow-ups to 9c06516 from its verification.

A deadline reached while searching which reserve to name turned a conflict the first search had already proved into an incomplete calculation. The attribution now gives up at the deadline and the conflict is reported with its generic reason; a cancellation still interrupts.

The alternative-date analysis relied on earned activations, which the path without a final-state snapshot does not have. It now compares the occurrences of reserve-carrying rules satisfied before and after the move, on both paths.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 03:53:33 +01:00
nessarandClaude Fable 5.2 6e24b46709 docs(readme): describe the IF_THEN reserve and the validity of the earned day (#374)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 03:29:56 +01:00
nessarandClaude Fable 5.2 5a82c0a0f8 fix(i18n): put the reserve quantities in the accusative in German (#377, #378)
The explanation line and the rule summary insert a phrase such as "5 Tage bezahlten Urlaub", which is accusative; the sentences around it now ask for that case.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 03:29:56 +01:00
nessarandClaude Fable 5.2 d919fd9b21 test(rules): refuse malformed share links in both envelope versions (#378)
The refusal table and the unknown-fields test had moved to version-2 envelopes only. They now run for version 1 and version 2, since every published envelope version must stay decodable and all or nothing (ADR 0014).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 03:29:56 +01:00
nessarandClaude Fable 5.2 9c06516090 fix(planning): name a reserve that fails jointly and refuse alternative dates that break one (#376)
Two findings of the independent verification.

An obligation whose reserve holds for each occurrence alone but not for all together ended in the generic joint-date conflict. When no single occurrence fails and an obligation IF_THEN rule carries a reserve, the conflict path now searches the obligations once more with the obligation reserves ignored, on its own context and stopping at the first solution. Placements are only added along the obligation search, so a solution found there breaks at least one reserve: the conflict names the first occurrence whose reserve does not hold in it. Without such a solution the conflict is reported as before, and requests without a reserve-carrying obligation take the same path with the same steps.

The alternative-date analysis accepted a move that left an earned day in place while its reserve no longer held. A date is now ineligible when an activation of a reserve-carrying rule is no longer satisfied.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 03:29:56 +01:00
nessarandClaude Fable 5.2 2fe9a02f72 docs(benchmark): record the protocol with the reserve and the version-2 saved rules (#378)
The default rules scenario now carries the reserve of five: 2.90 s, 0.85 of the calibration, against a multiplier of 1.25 that did not change. The saved-rules section describes the version-2 envelope and the single migration that gives the supplied Samedi Malin its reserve.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 02:50:25 +01:00
nessarandClaude Fable 5.2 44d7adcda4 feat(rules): give the supplied Samedi Malin a reserve of five CP days (#378)
This is the change that makes the reserve reach users: a plan no longer promises a Samedi Malin day when fewer than five CP days would remain on that Saturday (ADR 0015).

- The rule dialog offers the reserve on IF_THEN rules and the rule summary mentions it when it is above zero; a refused reserve has its own translated validation reason.
- A first visit gets the supplied Samedi Malin with a reserve of five. A saved version-1 envelope or legacy list gives five once to the rule with the supplied identity, edited, disabled or untouched, in the existing single write, and is saved as version 2; a version-2 envelope is never migrated again, so a later value, zero included, is kept.
- Share links are produced in a second envelope version carrying the reserve of every IF_THEN rule. A version-1 link still decodes, with five on the supplied Samedi Malin and zero on its other IF_THEN rules; a non-canonical or misplaced reserve refuses the whole import.
- The reserve reaches the planner in the browser and through server-side planning, with a test on each path, and the supplied rules are planned end to end for 9 and 4 CP days on a 2027 horizon.
- The default rules benchmark scenario carries the reserve; no multiplier changed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 02:50:18 +01:00
nessarandClaude Fable 5.2 762b4be926 feat(declarations): record the leave balance a declared CP day was booked from (#379)
A declared CP day may carry the expiry date of the leave balance it was booked from. The planner attributes the day to the balance it names when its date lies within that balance's dates, and otherwise, as for every day that names none, to the matching balance usable on its date that expires first; an IF_THEN reserve then adds back only the days booked from a balance it counts. The field is optional in storage and in planning requests, on every calculation path, and days saved before this change load unchanged.

In declaration entry the CP chip becomes one chip per CP balance expiry date from two balances on, labelled with that date. With zero or one CP balance the controls and the clear-on-same-type behaviour are unchanged and the single balance is recorded automatically; with several, a CP day is cleared only by the chip of its own balance and replaced by another, and the drag preview follows the same rule.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 02:18:59 +01:00
nessarandClaude Fable 5.2 13d63879a2 feat(planning): explain the occurrences an IF_THEN reserve prevented (#377)
The plan outcome reports each occurrence a reserve prevented, with its rule, date, remaining and required quantities: a pattern in place that earns nothing, or a pattern not placed because the reserve could not hold. In the second case the remaining quantity is the one the displayed plan would leave with the pattern that has the fewest days still to place, funded first by unplaced leave. The field is absent when there is nothing to report, so outcomes without a reserve are unchanged.

The applied rules of the plan explanation show one line per occurrence, also for the plan retained by an incomplete calculation, and the conflict of an obligation whose reserve cannot hold reads as a sentence naming the rule, the occurrence and the missing quantity, in the four interface languages.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 01:56:43 +01:00
nessarandClaude Fable 5.2 be2812e34c feat(planning): let an IF_THEN rule require a reserve (#376)
A planning request can give an IF_THEN rule reserveDays: a quantity of its requested leave type that must remain on the occurrence date (ADR 0015). An occurrence is satisfied only when its pattern is complete and its reserve holds; one predicate feeds earning, the preference count, obligation validity and the counterfactual analysis.

The measure counts the reported balances of the requested type usable on the occurrence date, deducts their placements dated on or before the last day of the time-off period holding the occurrence, and adds back the declared days dated after it and attributed to those balances (the balance of the day's type usable on its date that expires first).

As a preference, an occurrence whose reserve cannot hold places nothing; behind earlier objectives the IF_THEN stage moves at most the missing days, held only by optimization rules, to free dates after the period, and the leaf check judges the moves. As an obligation, it ends in a planning conflict with reason if-then-reserve carrying the occurrence, the remaining and the required quantities.

An absent or zero reserve runs no new code: the frozen-engine differential check passes without a rebuild.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 01:40:37 +01:00
nessarandClaude Fable 5.2 339497b740 docs(benchmark): record the earned-day validity, its search change and the frozen-engine rebuild (#375)
Adds the #375 record with the comparison before the rebuild (4,953 of 5,000 seeded requests identical, one worse on a real objective, explained), the seven multi-year requests and the benchmark protocol, lists the rebuild from 1e06fe2 in the frozen-engine table, and notes in ADR 0012 that the loss it accepted behind loss prevention is lifted in the rule's own stage.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 01:07:15 +01:00
nessarandClaude Fable 5.2 2ca59441b7 test(planning): rebuild the frozen engine from the earned-day validity and its search change (#375)
Built from 1e06fe2 with the command of docs/benchmark/README.md. It carries the two commits of #375: the validity of the earned day (56ba9a7) and the IF_THEN stage that earns its day behind loss prevention (1e06fe2). The differential check passes again: 47 tests, 5,000 seeded requests and the seven multi-year requests.

From here the history of this branch is append-only: 56ba9a7 and 1e06fe2 must keep their hashes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 01:03:21 +01:00
nessarandClaude Fable 5.2 1e06fe2634 fix(planning): let an IF_THEN preference earn its day behind loss prevention (#375)
Search change under ADR 0010. An earned day now expires inside its leave year, so it counts as at risk as soon as it is earned. Behind loss prevention, the IF_THEN stage rejected every candidate that earned a day, and loss prevention stopped putting leave on a pattern, so the supplied rule order earned nothing.

The IF_THEN stage now does two things in its own stage:
- when a finalized candidate is worse than the baseline on an earlier leave-balance objective, it places the leave this rule earned on its first valid date, and keeps the candidate only if the earlier objectives are then no worse than the baseline;
- when earlier objectives already placed all the requested leave, it moves one such placement onto a free pattern date, and the same check judges the move.

A candidate that was already acceptable takes the path it took before. This lifts the loss ADR 0012 accepted for a pattern behind loss prevention; its obligation search is unchanged.

The frozen-engine differential check fails until the frozen engine is rebuilt from this commit.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 01:01:43 +01:00
nessarandClaude Fable 5.2 56ba9a7f05 feat(planning): expire an earned leave entitlement with the leave balance in use (#375)
An earned leave entitlement still becomes available the day after its generating time-off period ends. It now expires on the expiry date of the earliest-expiring reported balance of the rule's requested type that is usable on that availability date, and one year later only when there is none. This applies to every IF_THEN rule that earns leave (ADR 0015).

Usable is date-only: a balance the plan fully consumes still defines the leave year. Earned balances never define another earned balance's expiry. The bounds cache key gains the rule, since two rules with different requested types can share a period.

The frozen-engine differential check fails from this commit until the frozen engine is rebuilt.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 00:43:34 +01:00
nessarandClaude Fable 5.2 d9333bc54c docs(adr): record the Samedi Malin reserve and the validity of the earned day
ADR 0015 for #374: why the reserve follows the stricter reading of the
staff-representative report of 13 October 2026, which readings were rejected,
and what changes for saved rules and share links.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 00:13:57 +01:00
nessarandClaude Fable 5.2 bfe950cf34 docs(context): define the IF_THEN reserve and the validity of earned leave
Samedi Malin gains a reserve of five CP days, taken from the works-council
report of 13 October 2026, and its earned day expires with the CP balance in
use when it is credited. A declared CP day names the balance it was booked from.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3CzBZP96zgTG9hCgLw
2026-11-30 00:10:42 +01:00
renovate Bot d152035f04 chore(deps): update angular-cli monorepo to v22.2.7
renovate/stability-days Updates have met minimum release age requirement
CI / build (pull_request) Successful in 37s
CI / security (pull_request) Successful in 1m0s
CI / images (pull_request) Successful in 55s
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 / required (push) Successful in 5s
CI / policy (pull_request) Successful in 22s
CI / validate (pull_request) Successful in 41s
CI / benchmark (pull_request) Successful in 1m6s
CI / test (pull_request) Successful in 2m52s
CI / required (pull_request) Successful in 2s
CI / policy (push) Successful in 13s
CI / images (push) Successful in 1m16s
2026-11-16 06:03:22 +00:00
nessarandClaude Opus 5.5 995866fe5e docs(adr): share rule sets through the URL fragment
CI / build (pull_request) Successful in 21s
CI / security (pull_request) Successful in 1m1s
CI / images (pull_request) Successful in 52s
CI / required (pull_request) Successful in 1s
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 / required (push) Successful in 1s
CI / policy (pull_request) Successful in 8s
CI / validate (pull_request) Successful in 30s
CI / benchmark (pull_request) Successful in 1m31s
CI / test (pull_request) Successful in 2m48s
CI / policy (push) Successful in 14s
CI / images (push) Successful in 1m17s
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 / build (pull_request) Successful in 24s
CI / security (pull_request) Successful in 1m4s
CI / images (pull_request) Successful in 1m18s
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 / required (push) Successful in 1s
CI / policy (pull_request) Successful in 22s
CI / validate (pull_request) Successful in 28s
CI / benchmark (pull_request) Successful in 1m33s
CI / test (pull_request) Successful in 2m42s
CI / required (pull_request) Successful in 2s
CI / policy (push) Successful in 18s
CI / images (push) Successful in 52s
- 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 / build (pull_request) Successful in 21s
CI / security (pull_request) Successful in 1m1s
CI / images (pull_request) Successful in 1m17s
CI / required (pull_request) Successful in 2s
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 / required (push) Successful in 2s
CI / policy (pull_request) Successful in 17s
CI / validate (pull_request) Successful in 34s
CI / benchmark (pull_request) Successful in 1m32s
CI / test (pull_request) Successful in 2m37s
CI / policy (push) Successful in 22s
CI / images (push) Successful in 1m17s
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 / build (pull_request) Successful in 25s
CI / security (pull_request) Successful in 1m5s
CI / images (pull_request) Successful in 55s
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 / required (push) Successful in 2s
CI / policy (pull_request) Successful in 14s
CI / validate (pull_request) Successful in 27s
CI / benchmark (pull_request) Successful in 1m8s
CI / test (pull_request) Successful in 3m47s
CI / required (pull_request) Successful in 4s
CI / policy (push) Successful in 11s
CI / images (push) Successful in 1m17s
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 / build (pull_request) Successful in 24s
CI / security (pull_request) Successful in 56s
CI / images (pull_request) Successful in 1m19s
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 / required (push) Successful in 2s
CI / policy (pull_request) Successful in 15s
CI / validate (pull_request) Successful in 34s
CI / benchmark (pull_request) Successful in 1m10s
CI / test (pull_request) Successful in 3m50s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 16s
CI / images (push) Successful in 1m21s
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 / build (pull_request) Successful in 23s
CI / security (pull_request) Successful in 1m0s
CI / images (pull_request) Successful in 1m14s
CI / required (pull_request) Successful in 1s
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 / required (push) Successful in 1s
CI / policy (pull_request) Successful in 20s
CI / validate (pull_request) Successful in 34s
CI / benchmark (pull_request) Successful in 1m30s
CI / test (pull_request) Successful in 2m53s
CI / policy (push) Successful in 8s
CI / images (push) Successful in 1m15s
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 / build (pull_request) Successful in 38s
CI / security (pull_request) Successful in 2m5s
CI / images (pull_request) Successful in 1m13s
CI / required (pull_request) Successful in 2s
CI / policy (pull_request) Successful in 8s
CI / validate (pull_request) Successful in 38s
CI / benchmark (pull_request) Successful in 1m31s
CI / test (pull_request) Successful in 4m26s
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 / 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 / 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 / required (push) Successful in 1s
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 / policy (push) Successful in 7s
CI / images (push) Successful in 1m13s
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
140 changed files with 18715 additions and 8744 deletions

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@ This is a single-context repo using root `CONTEXT.md` and `docs/adr/`. See `docs
- `develop` is the default integration branch; `main` contains releases. Start `feature/*` branches from the current `origin/develop` and target their PRs to `develop`.
- Rebase working branches onto the latest `origin/develop` before opening or merging a PR. If `develop` advances, rebase and rerun the PR checks before merging.
- Integrate through PRs with successful required checks and merges restricted to designated maintainers through Gitea's merge allowlist. The `develop` allowlist also admits the `renovate` bot, which automerges minor, patch, digest, and pin updates once `required` passes; major updates stay manual. Use merge commits (`--no-ff`) with squashing disabled. Direct and forced pushes to `main` and `develop` are forbidden.
- Integrate through PRs with successful required checks and merges restricted to designated maintainers through Gitea's merge allowlist. The `develop` allowlist also admits the `renovate` bot, which automerges minor, patch, digest, and pin updates once `required` passes; major updates and the grouped Bun updates (see [Gitea Actions](docs/gitea-actions.md#bun-toolchain-and-node)) stay manual. Merge with Gitea's rebase method so `develop` stays linear; merge commits and squashing are disabled in the repository. Direct and forced pushes to `main` and `develop` are forbidden.
- Use Conventional Commits for new commits and PR titles.
- Create `release/X.Y.Z` from `develop` and `hotfix/X.Y.Z` from `main`. Only `release/*` and `hotfix/*` PRs target `main`. Merge each release or hotfix into both `main` and `develop`, keeping its branch until both PRs are merged.
- Use merges and back-merges for releases and hotfixes. Never rebase `main`, `develop`, or a frozen release branch.
+15 -4
View File
@@ -39,7 +39,11 @@ _Avoid_: horizon end
A Monday-to-Friday calendar date that is not a French national public holiday. New leave placements are restricted to working days that have not been declared non-working.
**Declared non-working day**:
A working day on which the user declares they will not work, identified by a CP, RTT, or Other leave type. Its date and type are fixed during planning; it consumes no remaining leave balance and contributes to compatible planning rules.
A working day on which the user declares they will not work, identified by a CP, RTT, or Other leave type; a declared CP day also names, by its expiry date, the leave balance it was booked from. Its date and type are fixed during planning; it consumes no remaining leave balance and contributes to compatible planning rules.
**Declaration entry**:
The calendar mode in which the user adds, retypes, or removes declared non-working days. The calendar then shows the current planning inputs rather than a calculated plan.
_Avoid_: edit mode, booking mode
**Public holiday**:
A French calendar date that cannot receive a leave placement and contributes to a time-off period.
@@ -109,7 +113,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.
@@ -120,8 +124,11 @@ A planning rule evaluated independently for every French public holiday on its c
**IF_THEN placement mode**:
`before` and `after` fix every requested day on one side; `around` considers every split with at least one day on each side; `auto` considers every split, including the all-before and all-after extremes. Each side takes the Monday-to-Friday dates nearest the occurrence, skipping only weekends; a split whose side would reach a weekday public holiday is unavailable.
**IF_THEN reserve**:
The quantity of an IF_THEN rule's requested leave type that must remain on the occurrence date for the occurrence to be satisfied; zero asks for none, and a complete pattern whose reserve does not hold neither satisfies the rule nor earns leave. It is counted across the matching leave balances available and unexpired on that date, once every matching leave placement of the time-off period containing the occurrence is deducted and every declared day booked from those balances and dated after that period is added back.
**Samedi Malin**:
The default IF_THEN preference that earns one Other day for a public holiday falling on a Saturday when CP leave placements or declared CP days surround it with at least one working day on each side, or precede or follow it with at least two. RTT and Other days do not count, and a weekday public holiday interrupts a side: in 2027, Saturday 8 May cannot be preceded by two CP days because Thursday 6 May is Ascension.
The default IF_THEN preference that earns one Other day for a public holiday falling on a Saturday when CP leave placements or declared CP days surround it with at least one working day on each side, or precede or follow it with at least two. RTT and Other days do not count, and a weekday public holiday interrupts a side: in 2027, Saturday 8 May cannot be preceded by two CP days because Thursday 6 May is Ascension. Its IF_THEN reserve is five CP days, so earning both Saturdays of May 2027 with the smallest patterns needs nine.
**TIME_WINDOW rule**:
A planning rule counting compatible leave placements and declared non-working days in an inclusive date window. A preference requests up to its configured quantity; an obligation requires exactly that quantity.
@@ -129,6 +136,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.
@@ -179,7 +190,7 @@ The lexicographic quality order applied after joint obligation feasibility, with
The total quantity of earned leave entitlements generated by all applicable planning rules for a plan, counted before consumption and attributed to their generating rules. Only entitlements becoming available strictly after the calculation's Europe/Paris calendar date qualify, including those becoming available after the planning horizon.
**Earned leave entitlement**:
A leave entitlement earned for each completed occurrence of an applicable planning rule after its generating time-off period ends, whether that occurrence is fulfilled by leave placements, declared non-working days, or both. It becomes available the following day, expires one year later, and may fund later compatible placements; only entitlements becoming available after the calculation's Europe/Paris calendar date are added to the plan.
A leave entitlement earned for each satisfied occurrence of an applicable planning rule after its generating time-off period ends, whether that occurrence is fulfilled by leave placements, declared non-working days, or both. It becomes available the following day, expires with the earliest-expiring leave balance of the rule's requested type usable on that day (one year later when there is none), and may fund later compatible placements; only entitlements becoming available after the calculation's Europe/Paris calendar date are added to the plan.
_Avoid_: reward, bonus days
**Optimization result**:
+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.5-alpine@sha256:da816670775f4c2b4e990b6b1847cf5540dcdc721a42033dd331ce7a88ba6a3b 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.5-alpine@sha256:da816670775f4c2b4e990b6b1847cf5540dcdc721a42033dd331ce7a88ba6a3b AS production
WORKDIR /app
+14 -13
View File
@@ -85,7 +85,7 @@ Rules are either:
- **obligations**, which must all be feasible in the same plan; or
- **preferences**, optimized lexicographically in user order.
`TIME_WINDOW` places a quantity inside an inclusive date window. `IF_THEN` creates before, after, around, or automatic patterns for each matching French public holiday, from the nearest weekdays on each side; a weekday public holiday interrupts a side. A completed `IF_THEN` occurrence may earn a new dated leave entitlement after its final time-off period ends.
`TIME_WINDOW` places a quantity inside an inclusive date window. `IF_THEN` creates before, after, around, or automatic patterns for each matching French public holiday, from the nearest weekdays on each side; a weekday public holiday interrupts a side. An `IF_THEN` rule may require a reserve (`reserveDays`): a quantity of its requested leave type that must remain on the occurrence date. An occurrence whose pattern is complete and whose reserve holds may earn a new dated leave entitlement, available after its final time-off period ends and expiring with the earliest-expiring balance of the requested type usable on the day it becomes available, or one year after that day when there is none ([ADR 0015](docs/adr/0015-samedi-malin-reserve-and-earned-day-validity.md)).
The outcome is one of:
@@ -192,12 +192,13 @@ Saved balances, including an empty list, are restored before the initial calcula
```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
│ ├── leave-planner.worker.ts # Worker entry: server Bun Worker and browser fallback
│ ├── leave-planner.core.ts # Framework-free planning algorithm
│ ├── leave-planner.core.ts # Framework-free planning algorithm: entry point
│ ├── leave-planner-core/ # Its modules, imported only through the entry point
│ ├── calendar-service.ts # Calendar projection and UI integration
│ ├── calendar-settings-service.ts # Persisted horizon and week-number settings
│ ├── planning-duration.service.ts # Indicative wait and session-local refinement
@@ -213,10 +214,10 @@ CONTEXT.md # Canonical domain language and rules
## Local development
Prerequisite: [Bun](https://bun.sh/) 1.4.3, the exact version pinned by `packageManager` in `package.json` and used by CI and the Docker image. Node.js is not needed. Dependency versions are locked in `bun.lock`.
Prerequisite: [Bun](https://bun.sh/) 1.4.5, the exact version pinned by `packageManager` in `package.json` and used by CI and the Docker image. Node.js is not needed. Dependency versions are locked in `bun.lock`.
```bash
curl -fsSL https://bun.sh/install | bash -s "bun-v1.4.3"
curl -fsSL https://bun.sh/install | bash -s "bun-v1.4.5"
bun install --frozen-lockfile
bun start
```
@@ -249,7 +250,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
@@ -274,9 +275,9 @@ Behind a reverse proxy, forward WebSocket upgrades for `/api/planning`; on Nginx
The workflow runs on pushes to `develop` and `main`, `v*` tag pushes, PR opening/reopening/synchronization/edits, and manual dispatch. Other branches run CI only through their PR, so a branch without a PR gets no automatic CI or image. Manual runs validate without publishing images. Required jobs cover policy regression tests, GitFlow and Conventional Commits, ESLint, Prettier, `bun check` type checks, Bun coverage, the production build, Semgrep SAST, and Trivy dependency/secret scans. Coverage, build output, and SARIF reports are retained for seven days.
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).
Jobs that run project commands install Bun 1.4.5 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.
@@ -284,11 +285,11 @@ Both protected branches still require `gitlab-to-gitea/ci-conversion-required` u
### GitFlow and releases
`develop` is the default integration branch. Create `feature/*` branches from it, rebase them onto the current `origin/develop` before opening or merging their PR, and merge into `develop` with a merge commit (`--no-ff`). Existing working-branch names such as `feat/*` follow the same rules. Working branches cannot merge `develop` into themselves instead of rebasing.
`develop` is the default integration branch. Create `feature/*` branches from it, rebase them onto the current `origin/develop` before opening or merging their PR, and merge into `develop` with Gitea's rebase method, which keeps its history linear. Existing working-branch names such as `feat/*` follow the same rules. Working branches cannot merge `develop` into themselves instead of rebasing.
Create `release/X.Y.Z` from `develop` when the release scope is ready. Set `package.json` to `X.Y.Z` on this branch, stabilize it, then merge it into `main` and back into `develop`. Keep the release branch until both PRs have merged. A `hotfix/X.Y.Z` starts from `main`, changes the package version, and follows the same two-target merge process. Do not rebase `main`, `develop`, or a frozen release onto ongoing development.
Use Conventional Commits for new commits and PR titles, for example `feat(calendar): add planning periods`, `fix(planner): handle expired balances`, or `chore(release): prepare 1.6.0`. Scopes are optional; `!` marks a breaking change. The merge commit subject must preserve the validated PR title. Gitea supports a [Git-based merge-message template](https://docs.gitea.com/usage/issues-prs/merge-message-templates/) at `.gitea/default_merge_message/MERGE_TEMPLATE.md`, using `${PullRequestTitle}` and `${PullRequestReference}`. The committed template and a checked example expansion are documented in the [activation guide](docs/gitea-actions.md); legacy history is not rewritten.
Use Conventional Commits for new commits and PR titles, for example `feat(calendar): add planning periods`, `fix(planner): handle expired balances`, or `chore(release): prepare 1.6.0`. Scopes are optional; `!` marks a breaking change. A rebase merge keeps each commit's own subject, so every commit of a PR follows this convention; where a merge commit is made, its subject must preserve the validated PR title. Gitea supports a [Git-based merge-message template](https://docs.gitea.com/usage/issues-prs/merge-message-templates/) at `.gitea/default_merge_message/MERGE_TEMPLATE.md`, using `${PullRequestTitle}` and `${PullRequestReference}`. The committed template and a checked example expansion are documented in the [activation guide](docs/gitea-actions.md); legacy history is not rewritten.
The image publisher implements this tag contract in `gitea.nessar.fr/nessar/vac-optimizer`:
@@ -309,7 +310,7 @@ git push origin v1.6.0
The tag must match the tagged commit's `package.json` version, use stable `vMAJOR.MINOR.PATCH` syntax, and point to a commit reachable from `main`. Wait for the main checks and image publication before tagging: promotion requires its `sha-<commit>` image. Tags do not increment the version automatically.
The Gitea repository policy requires `develop` as the default branch and **Merge commit** as the merge method, with squash and rebase merge methods disabled. Configure [branch protection](https://docs.gitea.com/usage/access-control/protected-branches/) for `main` and `develop` to disable direct and forced pushes, restrict the merge allowlist to designated maintainers, require successful status checks, and block outdated PRs. Administrators must follow the protection rules. The `develop` allowlist also admits the `renovate` bot: [renovate.json](renovate.json) automerges minor, patch, digest, and pin updates three days after their release once the `required` check passes, and leaves major updates for manual review. After merge-message approval and a successful reviewed PR run, replace the migration gate with the reported pull-request context for the `required` job, as described in the activation guide. These are required settings; the migration does not establish that every setting has already been applied.
The Gitea repository policy requires `develop` as the default branch and **Rebase** as the merge method (fast-forward-only may stay enabled), with merge-commit and squash methods disabled. Configure [branch protection](https://docs.gitea.com/usage/access-control/protected-branches/) for `main` and `develop` to disable direct and forced pushes, restrict the merge allowlist to designated maintainers, require successful status checks, and block outdated PRs. Administrators must follow the protection rules. The `develop` allowlist also admits the `renovate` bot: [renovate.json](renovate.json) automerges minor, patch, digest, and pin updates by rebase three days after their release once the `required` check passes, and leaves major updates and the grouped Bun updates for manual review. After merge-message approval and a successful reviewed PR run, replace the migration gate with the reported pull-request context for the `required` job, as described in the activation guide. These are required settings; the migration does not establish that every setting has already been applied.
Only `release/*` and `hotfix/*` PRs may target `main`; working PRs target `develop`. CI validates these rules and checks working-branch rebases against the fetched integration head. If `develop` advances after validation, rebase and rerun the PR checks before merging.
@@ -322,7 +323,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; its random fallback is superseded by ADR 0012.
- [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 0012](docs/adr/0012-empty-leave-balances-on-first-visit.md) starts from an empty leave-balance list instead of random balances.
- [ADR 0013](docs/adr/0013-empty-leave-balances-on-first-visit.md) starts from an empty leave-balance list instead of random balances.
+156 -178
View File
@@ -6,14 +6,14 @@
"name": "vac-optimizer",
"dependencies": {
"@angular/cdk": "^22.0.0",
"@angular/common": "22.2.3",
"@angular/compiler": "22.2.3",
"@angular/core": "22.2.3",
"@angular/forms": "22.2.3",
"@angular/common": "22.3.0",
"@angular/compiler": "22.3.0",
"@angular/core": "22.3.0",
"@angular/forms": "22.3.0",
"@angular/material": "^22.0.0",
"@angular/platform-browser": "22.2.3",
"@angular/platform-browser-dynamic": "22.2.3",
"@angular/router": "22.2.3",
"@angular/platform-browser": "22.3.0",
"@angular/platform-browser-dynamic": "22.3.0",
"@angular/router": "22.3.0",
"date-holidays": "^3.30.2",
"dayjs": "^1.11.21",
"rxjs": "~7.8.2",
@@ -21,11 +21,11 @@
},
"devDependencies": {
"@analogjs/vite-plugin-angular": "^2.7.5",
"@angular/build": "22.2.3",
"@angular/cli": "22.2.3",
"@angular/compiler-cli": "22.2.3",
"@angular/build": "22.2.7",
"@angular/cli": "22.2.7",
"@angular/compiler-cli": "22.3.0",
"@eslint/js": "^10.0.1",
"@types/bun": "1.4.3",
"@types/bun": "1.4.5",
"@types/jsdom": "^30.0.0",
"@types/node": "^26.0.0",
"eslint": "^10.4.1",
@@ -35,7 +35,7 @@
"istanbul-lib-coverage": "^3.2.2",
"istanbul-lib-report": "^3.0.1",
"istanbul-reports": "^3.2.0",
"jsdom": "^30.0.0",
"jsdom": "^31.0.0",
"prettier": "^3.8.3",
"typescript": "~6.0.3",
"typescript-eslint": "^8.60.0",
@@ -47,39 +47,35 @@
"@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=="],
"@angular/common": ["@angular/common@22.3.0", "", { "dependencies": { "tslib": "^2.3.0" }, "peerDependencies": { "@angular/core": "22.3.0", "rxjs": "^6.5.3 || ^7.4.0" } }, "sha512-bM49PPn/W1GaW9dqqS3n+JfQ7q3Jz7/gBFQV3t6hY45dPYyTcWW0WupM4QLuPWMrcYVRCc2+VnZt7Wihuqx1xQ=="],
"@angular/compiler": ["@angular/compiler@22.2.3", "", { "dependencies": { "tslib": "^2.3.0" } }, "sha512-GjDkmOBqW+6RJTeW5mlLRivf6Zy7Ed0auVh+DYD67d4UF4Sk17F1vIt8puF4CQ2PIezlHh7oOnermCBNHAOGkQ=="],
"@angular/compiler": ["@angular/compiler@22.3.0", "", { "dependencies": { "tslib": "^2.3.0" } }, "sha512-a01VbJm4MANutGvsoBIlFl7oej5V67WEmGWhnd6eLZIAat5DyDLFuKD5++l+yHhZx1BaIvOCooyPgAbIEpb64g=="],
"@angular/compiler-cli": ["@angular/compiler-cli@22.2.3", "", { "dependencies": { "@babel/core": "8.0.1", "@jridgewell/sourcemap-codec": "^1.4.14", "chokidar": "^5.0.0", "convert-source-map": "^1.5.1", "reflect-metadata": "^0.2.0", "semver": "^7.0.0", "tslib": "^2.3.0", "yargs": "^18.0.0" }, "peerDependencies": { "@angular/compiler": "22.2.3", "typescript": ">=6.0 <6.1" }, "optionalPeers": ["typescript"], "bin": { "ngc": "bundles/src/bin/ngc.js", "ng-xi18n": "bundles/src/bin/ng_xi18n.js" } }, "sha512-em7Ht0Dv7cN7vZgvl2fl1yscAs+zUG2Vr2YKpVZ/rOWuTL2JZyT1qIfKhC4wQoo/3lN8fiUIwQMpflSGzIEPng=="],
"@angular/compiler-cli": ["@angular/compiler-cli@22.3.0", "", { "dependencies": { "@babel/core": "8.1.0", "@jridgewell/sourcemap-codec": "^1.6.0", "chokidar": "^6.0.0", "convert-source-map": "^1.5.1", "reflect-metadata": "^0.2.0", "semver": "^7.0.0", "tslib": "^2.3.0", "yargs": "^18.0.0" }, "peerDependencies": { "@angular/compiler": "22.3.0", "typescript": ">=6.0 <6.1" }, "optionalPeers": ["typescript"], "bin": { "ngc": "bundles/src/bin/ngc.js", "ng-xi18n": "bundles/src/bin/ng_xi18n.js" } }, "sha512-eSBIg9CdJL7CQhLbNFBKrZw2bFJx9USBi4b6aXaiiLb2/i17qXXuqXkX4pM61JSeAREDEM9tNWteDLLQQovAjg=="],
"@angular/core": ["@angular/core@22.2.3", "", { "dependencies": { "tslib": "^2.3.0" }, "peerDependencies": { "@angular/compiler": "22.2.3", "rxjs": "^6.5.3 || ^7.4.0", "zone.js": "~0.15.0 || ~0.16.0" }, "optionalPeers": ["@angular/compiler", "zone.js"] }, "sha512-ponarFrAZsPutT+htRt3PEmkt2/IB7DyrBy2f48sxsIx3ZA6xw09i2HOEBo+VBphlN6B/ynK9q+o04HPhdJ+dQ=="],
"@angular/core": ["@angular/core@22.3.0", "", { "dependencies": { "tslib": "^2.3.0" }, "peerDependencies": { "@angular/compiler": "22.3.0", "rxjs": "^6.5.3 || ^7.4.0", "zone.js": "~0.15.0 || ~0.16.0" }, "optionalPeers": ["@angular/compiler", "zone.js"] }, "sha512-wGXoO1eiBa5xPF7Y+Vm9eVj7W7x7drRv3StF2HubXX6l/osaIxeQc9ewaHaWl/teywr/LlGblu5ClKE65wF0Zw=="],
"@angular/forms": ["@angular/forms@22.2.3", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "tslib": "^2.3.0", "zod": "^4.0.10" }, "peerDependencies": { "@angular/common": "22.2.3", "@angular/core": "22.2.3", "@angular/platform-browser": "22.2.3", "rxjs": "^6.5.3 || ^7.4.0" } }, "sha512-TKP8FpeRCY/++vKWsY8GC1J2sNtEkdNNBPdgnMAMLTwheW5JzjwVatuQlbuZEx3WaAjbll1Ux3d+eHeqAVrtQg=="],
"@angular/forms": ["@angular/forms@22.3.0", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "tslib": "^2.3.0", "zod": "^4.0.10" }, "peerDependencies": { "@angular/common": "22.3.0", "@angular/core": "22.3.0", "@angular/platform-browser": "22.3.0", "rxjs": "^6.5.3 || ^7.4.0" } }, "sha512-FHl4I8sYf8ZilX5a5xuxy+fmwmlOlj8oMj5z3KxhgPIMODSrMSacfHVs3cwaxxRxnsUEKRxv6mZiWRgDg17kqA=="],
"@angular/material": ["@angular/material@22.2.1", "", { "dependencies": { "tslib": "^2.3.0" }, "peerDependencies": { "@angular/cdk": "22.2.1", "@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-qw+/aJBV4lqqoJgv1VBWbMBVnE7431SX0Mew1j7PO+s1UcTushbG7CIAEo1hwmRq3kyo4Qqch8+uzFq4R631HQ=="],
"@angular/platform-browser": ["@angular/platform-browser@22.2.3", "", { "dependencies": { "tslib": "^2.3.0" }, "peerDependencies": { "@angular/animations": "22.2.3", "@angular/common": "22.2.3", "@angular/core": "22.2.3" }, "optionalPeers": ["@angular/animations"] }, "sha512-eWZGsbG4bSrSg9UB/NE8wORGVrh1u+x6rirPGpMWqq/mTi6q+nS+pnPxAxmiEs8wmPH5nCz5b2pRKQeYUkhAGA=="],
"@angular/platform-browser": ["@angular/platform-browser@22.3.0", "", { "dependencies": { "tslib": "^2.3.0" }, "peerDependencies": { "@angular/animations": "22.3.0", "@angular/common": "22.3.0", "@angular/core": "22.3.0" }, "optionalPeers": ["@angular/animations"] }, "sha512-cbDtSz7gme4EmAnl+GcWLnAloPQRFHUTm/vUW9EDRR/ahO1xWY8Y4vtB9xtxppPIEcbsrAGQzyApXoKLr/cHDg=="],
"@angular/platform-browser-dynamic": ["@angular/platform-browser-dynamic@22.2.3", "", { "dependencies": { "tslib": "^2.3.0" }, "peerDependencies": { "@angular/common": "22.2.3", "@angular/compiler": "22.2.3", "@angular/core": "22.2.3", "@angular/platform-browser": "22.2.3" } }, "sha512-+WBe2JjaEeK0NpMlBzV7UBkO+ltUBYTDtMfGYkew2xHdIviITnzXX7yUXijB1Y6jxALgz3jEuJa9iLid8s11rg=="],
"@angular/platform-browser-dynamic": ["@angular/platform-browser-dynamic@22.3.0", "", { "dependencies": { "tslib": "^2.3.0" }, "peerDependencies": { "@angular/common": "22.3.0", "@angular/compiler": "22.3.0", "@angular/core": "22.3.0", "@angular/platform-browser": "22.3.0" } }, "sha512-Ri4LpCKmmZE+oIF02+69DoLHiiBmVajXjx/vnVpKEZTKzgovrf9yF4Iu8/HCcCe+kjlmAc6ldKeBihmDMoLBEg=="],
"@angular/router": ["@angular/router@22.2.3", "", { "dependencies": { "tslib": "^2.3.0" }, "peerDependencies": { "@angular/common": "22.2.3", "@angular/core": "22.2.3", "@angular/platform-browser": "22.2.3", "rxjs": "^6.5.3 || ^7.4.0" } }, "sha512-h4C3iJ3OXM9HItErmTo9fFrFRDj1DSqbvweHAWl8eYJvyuhDD80gBNgdpN8/5gpt9K1HV+PXk0YbyjyQ0zMfPA=="],
"@asamuzakjp/css-color": ["@asamuzakjp/css-color@7.1.3", "", { "dependencies": { "@csstools/css-calc": "^3.4.2", "@csstools/css-color-parser": "^4.2.5", "@csstools/css-parser-algorithms": "^4.0.2", "@csstools/css-tokenizer": "^4.0.2", "lru-cache": "^11.5.3" } }, "sha512-1t1U8Cm3RBl9vh3RAZhjkPaduzLSvQJRToRrxpGR/eDRW99mOREleuu+mWfiFa795bUzjwht7NgphCKTs2ianQ=="],
"@asamuzakjp/dom-selector": ["@asamuzakjp/dom-selector@9.2.4", "", { "dependencies": { "bidi-js": "^1.1.0", "css-tree": "^3.2.1", "is-potential-custom-element-name": "^1.0.1", "lru-cache": "^11.5.3" } }, "sha512-YnVzxDxLaqL0t7Q4wfcgHZjg55Wm6y5EaO7Bhu3q9J7wq/8iw3PhsnWiOQhYekx4VexnbkgWpTT6n+QIV7kczw=="],
"@angular/router": ["@angular/router@22.3.0", "", { "dependencies": { "tslib": "^2.3.0" }, "peerDependencies": { "@angular/common": "22.3.0", "@angular/core": "22.3.0", "@angular/platform-browser": "22.3.0", "rxjs": "^6.5.3 || ^7.4.0" } }, "sha512-YrU3YG615f7645Lqrpq6uvtrqIQpbEh9zrzdvMgB9I0oovZbeqE/mQAn+6zQR+yFJQRSbKQkk8UxcVZsVcWJyQ=="],
"@babel/code-frame": ["@babel/code-frame@8.0.6", "", { "dependencies": { "@babel/helper-validator-identifier": "^8.0.6", "js-tokens": "^10.0.0" } }, "sha512-uMHhvmDmwFiLuiozaoRYTZHqMFuu3fem/X9JY78lohAuLoh8LSGGC8JqUzo2cVuBsBxkjMZNk56CE7ock8Xxkw=="],
@@ -109,27 +105,13 @@
"@babel/types": ["@babel/types@8.0.6", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.6", "@babel/helper-validator-identifier": "^8.0.6" } }, "sha512-c+xgSWboV2pdwXP67BUWDVRHi2BO5Q3KwxyFVs7taVTY+fsK47/L51ZXQoV9rozHJDNHvJ4v4WEsI/IlxV2l2A=="],
"@bramus/specificity": ["@bramus/specificity@2.4.2", "", { "dependencies": { "css-tree": "^3.0.0" }, "bin": { "specificity": "bin/cli.js" } }, "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw=="],
"@bufbuild/protobuf": ["@bufbuild/protobuf@2.16.0", "", {}, "sha512-FWa0sPlqYGJgpTs6OxBRcL/AW4JT0OIO+W1ajerluoTVh8CV0B7XM1qsNCRgnkSCkRCgOICKHRQlY17jrsm0+Q=="],
"@csstools/color-helpers": ["@csstools/color-helpers@6.1.2", "", {}, "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow=="],
"@emnapi/core": ["@emnapi/core@2.0.0-alpha.6", "", { "dependencies": { "@emnapi/wasi-threads": "2.2.0", "tslib": "^2.4.0" } }, "sha512-MNVvMV7WtEJMgqaWJMvCyupK7Oi8sZctUIgPRZTsiS3cVvefk8DXPflOU3MSBddtj/rrYHygpYgpHDgwXnI3+w=="],
"@csstools/css-calc": ["@csstools/css-calc@3.4.3", "", { "peerDependencies": { "@csstools/css-parser-algorithms": "^4.0.2", "@csstools/css-tokenizer": "^4.0.2" } }, "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA=="],
"@emnapi/runtime": ["@emnapi/runtime@2.0.0-alpha.6", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-5ZR49ZsZ3cLvu5lkrVj6CMpHRgZjYz7XSlqK23GYYpyEqp749RVuIH0bEUKaGNghMh2pXRhIC3cnVrH28Y1j1Q=="],
"@csstools/css-color-parser": ["@csstools/css-color-parser@4.2.6", "", { "dependencies": { "@csstools/color-helpers": "^6.1.2", "@csstools/css-calc": "^3.4.3" }, "peerDependencies": { "@csstools/css-parser-algorithms": "^4.0.2", "@csstools/css-tokenizer": "^4.0.2" } }, "sha512-iiPQ3iRWwnJkeEn6RIu6SJPr7hYrLz6XZ9s/QZl+2/LI5KQVjpl2fdmDSZKuD4xP6GMmMPgHFFXg6k1Wkz0Trg=="],
"@csstools/css-parser-algorithms": ["@csstools/css-parser-algorithms@4.0.2", "", { "peerDependencies": { "@csstools/css-tokenizer": "^4.0.2" } }, "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA=="],
"@csstools/css-syntax-patches-for-csstree": ["@csstools/css-syntax-patches-for-csstree@1.1.15", "", { "peerDependencies": { "css-tree": "^3.2.1" }, "optionalPeers": ["css-tree"] }, "sha512-J0u7HkVl2nzSlhsiTOp4AmwcUQ3D+mGEEKfBy/7To5/y7F2OHwyLrXfrhR0SMgr4p5Lo+eaMVSeai24zUcBIxA=="],
"@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/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="],
"@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 +303,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 +337,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,45 +375,45 @@
"@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=="],
"@types/bun": ["@types/bun@1.4.5", "", { "dependencies": { "bun-types": "1.4.5" } }, "sha512-DpgwNI9z0L1S0gtb45QLCWgwCUcMLnsHYMJHQvpNj7erGiCGBvpggltAIeARrtobNMKMuy0UP7i56tKKgwFs/Q=="],
"@types/esrecurse": ["@types/esrecurse@4.3.1", "", {}, "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw=="],
@@ -495,9 +477,11 @@
"baseline-browser-mapping": ["baseline-browser-mapping@2.10.32", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-wbPvpyjJPC0zdfdKXxqEL3Ea+bOMD/87X4lftiJkkaBiuG6ALQy1SLmEd7BSmVCuwCQsBrCamgBoLyfFDD1EPg=="],
"beasties": ["beasties@0.5.4", "", { "dependencies": { "css-select": "^7.0.0", "css-what": "^8.0.0", "dom-serializer": "^3.0.0", "domhandler": "^6.0.0", "htmlparser2": "^12.0.0", "picocolors": "^1.1.1", "postcss": "^8.4.49", "postcss-media-query-parser": "^0.2.3", "postcss-safe-parser": "^7.0.1" } }, "sha512-8/lOOjT+PElYCnaUbmhgd3Uad5R1VTQ4Wg0k4rK8bX04m5WEqHNmnlLy3Q/lJ7dk25XA+72gayzc/skTfKKpcA=="],
"bcp-47": ["bcp-47@2.1.2", "", { "dependencies": { "is-alphabetical": "^2.0.0", "is-alphanumerical": "^2.0.0", "is-decimal": "^2.0.0" } }, "sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg=="],
"bidi-js": ["bidi-js@1.1.0", "", { "dependencies": { "require-from-string": "^2.0.2" } }, "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg=="],
"bcp-47-match": ["bcp-47-match@2.0.3", "", {}, "sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ=="],
"beasties": ["beasties@0.5.4", "", { "dependencies": { "css-select": "^7.0.0", "css-what": "^8.0.0", "dom-serializer": "^3.0.0", "domhandler": "^6.0.0", "htmlparser2": "^12.0.0", "picocolors": "^1.1.1", "postcss": "^8.4.49", "postcss-media-query-parser": "^0.2.3", "postcss-safe-parser": "^7.0.1" } }, "sha512-8/lOOjT+PElYCnaUbmhgd3Uad5R1VTQ4Wg0k4rK8bX04m5WEqHNmnlLy3Q/lJ7dk25XA+72gayzc/skTfKKpcA=="],
"boolbase": ["boolbase@2.0.0", "", {}, "sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA=="],
@@ -507,7 +491,7 @@
"buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="],
"bun-types": ["bun-types@1.4.3", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="],
"bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="],
"caldate": ["caldate@2.0.5", "", { "dependencies": { "moment-timezone": "^0.5.43" } }, "sha512-JndhrUuDuE975KUhFqJaVR1OQkCHZqpOrJur/CFXEIEhWhBMjxO85cRSK8q4FW+B+yyPq6GYua2u4KvNzTcq0w=="],
@@ -537,8 +521,6 @@
"css-select": ["css-select@7.0.0", "", { "dependencies": { "boolbase": "^2.0.0", "css-what": "^8.0.0", "domhandler": "^6.0.1", "domutils": "^4.0.2", "nth-check": "^3.0.1" } }, "sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g=="],
"css-tree": ["css-tree@3.2.1", "", { "dependencies": { "mdn-data": "2.27.1", "source-map-js": "^1.2.1" } }, "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA=="],
"css-what": ["css-what@8.0.0", "", {}, "sha512-DH0Bqq3DNp5tdOReuNyAA+Ev4Y2GS5FMbZpeTLP6C4CDi0h5nL0BmUPChXw3o/qbHLDWHl49sbNqQVY7bMSDdw=="],
"data-urls": ["data-urls@8.0.0", "", { "dependencies": { "whatwg-mimetype": "^5.0.0", "whatwg-url": "^17.1.2" } }, "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ=="],
@@ -671,6 +653,12 @@
"imurmurhash": ["imurmurhash@0.1.4", "", {}, "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA=="],
"is-alphabetical": ["is-alphabetical@2.0.1", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="],
"is-alphanumerical": ["is-alphanumerical@2.0.1", "", { "dependencies": { "is-alphabetical": "^2.0.0", "is-decimal": "^2.0.0" } }, "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw=="],
"is-decimal": ["is-decimal@2.0.1", "", {}, "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A=="],
"is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="],
"is-fullwidth-code-point": ["is-fullwidth-code-point@5.1.0", "", { "dependencies": { "get-east-asian-width": "^1.3.1" } }, "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ=="],
@@ -697,7 +685,7 @@
"js-yaml": ["js-yaml@4.1.1", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],
"jsdom": ["jsdom@30.1.2", "", { "dependencies": { "@asamuzakjp/css-color": "^7.1.3", "@asamuzakjp/dom-selector": "^9.2.4", "@bramus/specificity": "^2.4.2", "@csstools/css-syntax-patches-for-csstree": "^1.1.15", "@exodus/bytes": "^1.16.0", "css-tree": "^3.2.1", "data-urls": "^8.0.0", "decimal.js": "^10.6.0", "html-encoding-sniffer": "^7.0.0", "is-potential-custom-element-name": "^1.0.1", "lru-cache": "^11.5.3", "parse5": "^8.0.1", "saxes": "^6.0.0", "tough-cookie": "^6.0.2", "undici": "^8.11.2", "w3c-xmlserializer": "^6.0.0", "webidl-conversions": "^8.0.1", "whatwg-mimetype": "^5.0.0", "whatwg-url": "^17.2.0", "xml-name-validator": "^5.0.0" }, "peerDependencies": { "canvas": "^3.2.3" }, "optionalPeers": ["canvas"] }, "sha512-0FFE/jE1rppmVfUrJUgxqXjcwolZYIGtAgj1pTussMhNZxIxi7W/PvfWaMNroGi2B36X1IKHbexpZ9DhkoOPiQ=="],
"jsdom": ["jsdom@31.0.1", "", { "dependencies": { "@exodus/bytes": "^1.16.0", "bcp-47": "^2.1.2", "bcp-47-match": "^2.0.3", "data-urls": "^8.0.0", "decimal.js": "^10.6.0", "html-encoding-sniffer": "^7.0.0", "is-potential-custom-element-name": "^1.0.1", "lru-cache": "^11.5.3", "parse5": "^8.1.0", "parse5-parser-stream": "^8.1.0", "saxes": "^6.0.0", "tough-cookie": "^6.0.2", "undici": "^8.12.3", "w3c-xmlserializer": "^6.0.0", "webidl-conversions": "^8.0.1", "whatwg-mimetype": "^5.0.0", "whatwg-url": "^17.3.0", "xml-name-validator": "^5.0.0" }, "peerDependencies": { "@napi-rs/canvas": "^1.0.13" }, "optionalPeers": ["@napi-rs/canvas"] }, "sha512-CbhJL8ZQg3eKswxSZth4QO9tW0jPIhmR0vtSXQSbKSfWbwIT6hoRc17wdHIVTQ43KI0mdV5iTJr3281IDgVZ5g=="],
"jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
@@ -757,8 +745,6 @@
"make-dir": ["make-dir@4.0.0", "", { "dependencies": { "semver": "^7.5.3" } }, "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw=="],
"mdn-data": ["mdn-data@2.27.1", "", {}, "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ=="],
"mimic-function": ["mimic-function@5.0.1", "", {}, "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA=="],
"minimatch": ["minimatch@10.2.5", "", { "dependencies": { "brace-expansion": "^5.0.5" } }, "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg=="],
@@ -811,6 +797,8 @@
"parse5-html-rewriting-stream": ["parse5-html-rewriting-stream@8.0.1", "", { "dependencies": { "entities": "^8.0.0", "parse5": "^8.0.0", "parse5-sax-parser": "^8.0.0" } }, "sha512-NaRku2aMpUN1Sh1Gyk1KWUh2A7EJx2c6qYzvwsPtqhoHoaURshdrceYK3LunVCm3WHhm6FS7Vcczbvdh3/UIVw=="],
"parse5-parser-stream": ["parse5-parser-stream@8.1.1", "", { "dependencies": { "parse5": "^8.1.1" } }, "sha512-hMcVbbUJcQmP8rURWUdYrT1flRiBiBVjq/RYGguJpDUgIXSqdYKlE0CxthmdMWoSlBAuL5bUBa73g0pttSy7Hw=="],
"parse5-sax-parser": ["parse5-sax-parser@8.0.0", "", { "dependencies": { "parse5": "^8.0.0" } }, "sha512-/dQ8UzHZwnrzs3EvDj6IkKrD/jIZyTlB+8XrHJvcjNgRdmWruNdN9i9RK/JtxakmlUdPwKubKPTCqvbTgzGhrw=="],
"path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
@@ -853,7 +841,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=="],
@@ -951,7 +939,7 @@
"typescript-eslint": ["typescript-eslint@8.60.0", "", { "dependencies": { "@typescript-eslint/eslint-plugin": "8.60.0", "@typescript-eslint/parser": "8.60.0", "@typescript-eslint/typescript-estree": "8.60.0", "@typescript-eslint/utils": "8.60.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-9f65qWLZdAW9m1JaxBDUHcqRUfL8bkxxXL7XxEfI+F09q56PkBvIfCjLF3yInsDM/BBmwkqmCQdCZe/RYlIWEw=="],
"undici": ["undici@8.11.2", "", {}, "sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ=="],
"undici": ["undici@8.14.0", "", {}, "sha512-MqM6wqORYo0jb1WFUwFKZTFWFz6VeBMPj9op5Hq+RvlrQjISQCyLEfx5+/iqOLWC/LL1HliJ5t0NP1BgYpXeVQ=="],
"undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],
@@ -965,7 +953,7 @@
"verkit": ["verkit@0.3.2", "", {}, "sha512-zj/ob3UsvJGN0whEAKFp53REA5X66hvffVqoCtVQAakJKnKlH+/PcOfMoFwIG/o4rElqLv/ycAFlx8ZlXUorCg=="],
"vite": ["vite@8.3.2", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.28", "rolldown": "~1.2.11", "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-SQr1x6W5vVSbROg7vsyXIaxK9b0G7zsT68acdWWRmnBUsgDieLCRG+Rep9WdZgcposvv/GSnr4GUUBqB3vXq6w=="],
"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=="],
"w3c-xmlserializer": ["w3c-xmlserializer@6.0.0", "", { "dependencies": { "xml-name-validator": "^5.0.0" } }, "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q=="],
@@ -975,7 +963,7 @@
"whatwg-mimetype": ["whatwg-mimetype@5.0.0", "", {}, "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw=="],
"whatwg-url": ["whatwg-url@17.2.0", "", { "dependencies": { "@exodus/bytes": "^1.16.0", "tr46": "^7.0.0", "webidl-conversions": "^8.0.1" } }, "sha512-IhLIHNcBrzIixC5XXsbr4DxdjajyA5vQ5RwGZMtrUp+GbtE5Nrsge9QKau7jXrC0aTXLYGV0xiW7Tb4YS2aomw=="],
"whatwg-url": ["whatwg-url@17.3.0", "", { "dependencies": { "@exodus/bytes": "^1.16.0", "tr46": "^7.0.0", "webidl-conversions": "^8.0.1" } }, "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg=="],
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
@@ -1009,13 +997,11 @@
"@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/compiler-cli/@babel/core": ["@babel/core@8.1.0", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/generator": "^8.1.0", "@babel/helper-compilation-targets": "^8.0.7", "@babel/helpers": "^8.1.0", "@babel/parser": "^8.1.0", "@babel/template": "^8.0.0", "@babel/traverse": "^8.1.0", "@babel/types": "^8.1.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": "^3.0.0", "verkit": "^0.5.0" } }, "sha512-3jqm7xh3kJCmIeOK8sk6/EvOWdSzvOqvjt0tJEDOHHmzWjcQSvIh2/tq1I9RA741tl0QZdMzPJWCulWE+Dy5ww=="],
"@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=="],
"@angular/forms/zod": ["zod@4.6.5", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="],
"@angular/compiler-cli/chokidar": ["chokidar@6.0.0", "", { "dependencies": { "readdirp": "^5.1.1" } }, "sha512-Ec2Z7wpcKBiMpR7DxteoqS/sq5G5d2A4fpxzPv6+fD7xNNdrTghn7L11YwV5EN1B3i72Erc3XVT5FkWIDx90+A=="],
"@babel/core/convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],
@@ -1053,9 +1039,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=="],
@@ -1069,166 +1059,154 @@
"cliui/wrap-ansi": ["wrap-ansi@9.0.2", "", { "dependencies": { "ansi-styles": "^6.2.1", "string-width": "^7.0.0", "strip-ansi": "^7.1.0" } }, "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww=="],
"data-urls/whatwg-url": ["whatwg-url@17.2.0", "", { "dependencies": { "@exodus/bytes": "^1.16.0", "tr46": "^7.0.0", "webidl-conversions": "^8.0.1" } }, "sha512-IhLIHNcBrzIixC5XXsbr4DxdjajyA5vQ5RwGZMtrUp+GbtE5Nrsge9QKau7jXrC0aTXLYGV0xiW7Tb4YS2aomw=="],
"jsdom/parse5": ["parse5@8.1.1", "", { "dependencies": { "entities": "^9.0.0" } }, "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w=="],
"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=="],
"parse5-parser-stream/parse5": ["parse5@8.1.1", "", { "dependencies": { "entities": "^9.0.0" } }, "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w=="],
"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=="],
"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=="],
"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-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/compiler-cli/@babel/core/@babel/generator": ["@babel/generator@8.1.3", "", { "dependencies": { "@babel/parser": "^8.1.3", "@babel/types": "^8.1.3", "@jridgewell/gen-mapping": "0.4.0-beta.0", "@jridgewell/trace-mapping": "^0.3.31", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-lfUz17Qtr+EinAoqyK1+4J5F0GtgsZjXktM5o+QXWM8KRUOauR/WuwBHWGU/aaSp4FI99M7rj6kg851XYWDvmQ=="],
"@angular/compiler-cli/@babel/core/@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@8.0.7", "", { "dependencies": { "@babel/compat-data": "^8.0.5", "@babel/helper-validator-option": "^8.0.0", "browserslist": "^4.24.0", "flru": "1.0.2", "verkit": "^0.5.0" } }, "sha512-ilAZCdOOlOVA7dQbaFNw2f/59p6GW33NxTopc3DvEE3efp3ZXTrGX/yZScaKw8/vd9bq31Ag0EcXiLw32bAgJg=="],
"@angular/compiler-cli/@babel/core/@babel/helpers": ["@babel/helpers@8.1.3", "", { "dependencies": { "@babel/template": "^8.1.2", "@babel/types": "^8.1.3" } }, "sha512-s5s0hMqsgSVikMuK7XHFDlIJvZp5CdAFpJcgNF5b/6oRvVCS8n779zsJVQuwtUUu75/nCYceKvi+K2FDKcogXg=="],
"@angular/compiler-cli/@babel/core/@babel/parser": ["@babel/parser@8.1.3", "", { "dependencies": { "@babel/types": "^8.1.3" }, "bin": "./bin/babel-parser.js" }, "sha512-v3ck2WN7jn8gEJlEfIDEwTM8dCBjOac1CZjolvB6/r0O1ome6E7xS2cDQEOQqESRQZWWrLrhnjxD0qjmZ8QBgg=="],
"@angular/compiler-cli/@babel/core/@babel/traverse": ["@babel/traverse@8.1.3", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/generator": "^8.1.3", "@babel/helper-globals": "^8.0.6", "@babel/parser": "^8.1.3", "@babel/template": "^8.1.2", "@babel/types": "^8.1.3", "obug": "^3.0.0" } }, "sha512-Mil7E37zLel1sjGwcgAF0wn8tbTJp3LLVMb0fqgDxWJJm52NXBv3MJaqmNOp76qzInY/0uDH3rSZfl3BqCjHiw=="],
"@angular/compiler-cli/@babel/core/@babel/types": ["@babel/types@8.1.3", "", { "dependencies": { "@babel/helper-string-parser": "^8.1.3", "@babel/helper-validator-identifier": "^8.0.6" } }, "sha512-eBREGwDHRPHtdsg44t071GE2KRDEuJrf0J2uT5/qvJPB2+pfPZOKlx93dMZOFkE7QW5G0JWoczySD7a01Jf0iw=="],
"@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=="],
"@angular/compiler-cli/@babel/core/obug": ["obug@3.0.0", "", {}, "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw=="],
"@schematics/angular/oxc-parser/@oxc-parser/binding-android-arm64": ["@oxc-parser/binding-android-arm64@0.150.0", "", { "os": "android", "cpu": "arm64" }, "sha512-B6ofpoFiAUwIZ0MJ2IgHPvZK8FAtL4qzSZRwOkAKIfxEobE1mQC8nDdiFZj7pUaJiVUVCsfkMsBJKedzO8rZvA=="],
"@angular/compiler-cli/@babel/core/verkit": ["verkit@0.5.0", "", {}, "sha512-u4J1hr6Y+C/hit34GwL3eIcUf3wngT8TlYUjK7tk0jxydKLAq3sYvifjdTDA6U3KCKRcQCQDGf/srjxfZF3l7g=="],
"@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=="],
"@angular/compiler-cli/chokidar/readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="],
"@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=="],
"@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-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-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-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-android-arm64": ["@oxc-parser/binding-android-arm64@0.156.0", "", { "os": "android", "cpu": "arm64" }, "sha512-mwkWKhOBpmh8fWc3m4MiLsmEAtx0YuHmvyo9ff557cnb3QZ2kt2eauSz75wCGIpiZG3gUsJ4WwzEjm4R4/BHig=="],
"@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-darwin-arm64": ["@oxc-parser/binding-darwin-arm64@0.156.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-6pGR5fUszM9M4eBBapqpGjCRJolFwuCldx8bRQjqXyM09cQysBTWVF2Ttg4UNJVxYSaw5RRINbveCOOCrsuGvA=="],
"@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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-project/types": ["@oxc-project/types@0.150.0", "", {}, "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw=="],
"@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-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-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-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=="],
"vite/rolldown/@oxc-project/types": ["@oxc-project/types@0.152.0", "", {}, "sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw=="],
"jsdom/parse5/entities": ["entities@9.0.0", "", {}, "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg=="],
"vite/rolldown/@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.12", "", { "os": "android", "cpu": "arm" }, "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A=="],
"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/@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.12", "", { "os": "android", "cpu": "arm64" }, "sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg=="],
"parse5-parser-stream/parse5/entities": ["entities@9.0.0", "", {}, "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg=="],
"vite/rolldown/@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.12", "", { "os": "darwin", "cpu": "arm64" }, "sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w=="],
"vite/postcss/nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="],
"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=="],
"vite/postcss/source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="],
"vite/rolldown/@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.12", "", { "os": "freebsd", "cpu": "x64" }, "sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ=="],
"@angular/compiler-cli/@babel/core/@babel/generator/@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.4.0-beta.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0-beta.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-JdGNkbE4GlNPYQhM0L95fBQr7ctLZJ276QXQLTad4t1oSdnnCI3fDq9DW3BqYAWv8Wc3+HS+4Gsii1oPMCfz1w=="],
"vite/rolldown/@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.12", "", { "os": "linux", "cpu": "arm" }, "sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g=="],
"@angular/compiler-cli/@babel/core/@babel/helpers/@babel/template": ["@babel/template@8.1.2", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/parser": "^8.1.2", "@babel/types": "^8.1.2" } }, "sha512-9B3FA5HZWK7rTJ7nU2F03qAc/t80O/WB5YQ7NKYdvmMwpq7EUyN04APNQWpkqwSqWtOsuwR0jMSRYLFoAd1m9A=="],
"vite/rolldown/@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw=="],
"@angular/compiler-cli/@babel/core/@babel/traverse/@babel/template": ["@babel/template@8.1.2", "", { "dependencies": { "@babel/code-frame": "^8.0.6", "@babel/parser": "^8.1.2", "@babel/types": "^8.1.2" } }, "sha512-9B3FA5HZWK7rTJ7nU2F03qAc/t80O/WB5YQ7NKYdvmMwpq7EUyN04APNQWpkqwSqWtOsuwR0jMSRYLFoAd1m9A=="],
"vite/rolldown/@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw=="],
"@angular/compiler-cli/@babel/core/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@8.1.3", "", {}, "sha512-5HTuREtgj0xIc345zU4gtD2+3vIPkZpJw7wUYytt/mzBTQN2mWpGr1nxYiocYa2E8sWggRkrSg/k7BK51pAxIg=="],
"vite/rolldown/@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.12", "", { "os": "linux", "cpu": "ppc64" }, "sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ=="],
"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=="],
"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=="],
"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=="],
"vite/rolldown/@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.12", "", { "os": "linux", "cpu": "x64" }, "sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw=="],
"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=="],
"vite/rolldown/@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.12", "", { "os": "linux", "cpu": "x64" }, "sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g=="],
"vite/rolldown/@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.12", "", { "os": "none", "cpu": "arm64" }, "sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA=="],
"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=="],
"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/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/rolldown/@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.12", "", { "os": "android", "cpu": "arm64" }, "sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg=="],
"@angular/build/vite/rolldown/@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.12", "", { "os": "darwin", "cpu": "arm64" }, "sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w=="],
"@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=="],
"@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,5 +1,5 @@
# Restore Saved Planning Inputs Before Generating Random Defaults
[ADR 0012](0012-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.
[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. [Issue #375](https://gitea.nessar.fr/nessar/vac-optimizer/issues/375) later settled it in that stage: an IF_THEN preference now moves leave onto its pattern behind loss prevention, so the two-year request earns its day again ([record](../benchmark/issue-375.md)).
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,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.
@@ -0,0 +1,38 @@
---
status: accepted
---
# Samedi Malin Reserve and Validity of the Earned Day
Accepted on 2026-11-30 for [issue #374](https://gitea.nessar.fr/nessar/vac-optimizer/issues/374).
The report of the staff-representative meeting of 13 October 2026 is the only written source for Samedi Malin. Management's answer confirms the pattern already implemented, and adds that the day is credited after the leave around the Saturday, into the supplementary-leave counter "of the current year", with no carry-over. A union comment in the same report adds a condition management does not state: five CP days must be in the counter "during the period of the Saturday public holiday". VacOptimizer ignored that condition and gave the earned day a full year, so it could promise a day payroll refuses and plan it after it has lapsed.
IF_THEN rules gain a reserve: a quantity of the requested leave type that must remain on the occurrence date for the occurrence to be satisfied. The supplied Samedi Malin sets it to five CP days; every other rule defaults to zero. The earned day now expires with the earliest-expiring balance of the requested type usable on the day it is credited, and one year later only when there is none.
The report gives no formula, so each reading below is a choice, and wherever two were plausible the stricter one was taken: announcing a day that payroll then refuses costs the user a CP pattern placed for nothing, while missing a day payroll grants costs nothing.
- **Measured on the Saturday, with the whole leave deducted.** The reserve counts the balances available and unexpired on the Saturday, minus every placement of the time-off period containing it, including those after the Saturday. Earning both Saturdays of May 2027 with the smallest patterns needs nine CP days.
- **Booked leave elsewhere still counts.** Reported balances already exclude booked leave ([ADR 0007](0007-declared-days-and-reported-balances.md)), but on that Saturday payroll has not yet deducted leave booked for later. Declared days dated after the period are therefore added back when they were booked from a balance in the reserve. A declared CP day names that balance by its expiry date; one that names none is attributed to the usable balance that expires first.
- **The reserve is part of the rule, not only of the reward.** A complete pattern whose reserve does not hold neither satisfies the rule nor earns leave, so a preference places nothing for that occurrence and an obligation ends in a conflict.
- **Existing rules change without being asked.** The supplied Samedi Malin gets a reserve of five in every saved rule list and in share links already sent, even when its owner edited it: the field did not exist, so no choice is overwritten, and leaving it at zero would keep every current user on the over-promising rule.
## Considered Options
- **Counting only the CP days taken before the Saturday**: rejected. Seven days would then earn both May 2027 Saturdays through patterns placed after them, and the planner would always pick those patterns to sidestep the reserve.
- **Counting every booked CP day as deducted**: rejected. A balance expiring on 31 May must be fully booked by then, so earning the 8 May day would require losing five CP days.
- **A fixed behaviour attached to the supplied rule instead of a parameter**: rejected. It could not be switched off when the union's reading proves wrong or another employer differs, and a rule recreated by hand or received through a link would silently lack it.
- **Guessing the balance of a declared day from its date alone**: rejected. It is wrong whenever a carried-over balance overlaps the next one.
- **Expiring the earned day on 31 December, or on a date set in the rule**: rejected for now. The report's question opposed "before the end of May 2027" to a carry-over, and its answer excludes the carry-over; following the user's own CP expiry date needs no input and adapts to an employer whose leave year is the calendar year.
## Consequences
The rule format changes, so the share-link envelope of [ADR 0014](0014-rule-sets-shared-through-the-url-fragment.md) needs a new version that still decodes every link already sent.
Plans change on upgrade without any action: a Samedi Malin day may disappear and CP days may be held back to keep the reserve. The plan explanation therefore names every occurrence the reserve prevented, with the figures, whether its pattern is in place or was never placed.
A day earned on 8 May 2027 lasts three weeks, during which the reserved CP days expiring on 31 May must also be placed.
A balance that reaches zero must stay in the list while declared days booked from it are still ahead; once it is deleted those days fall back to automatic attribution.
If the employer's supplementary-leave counter follows the calendar year while CP runs from June to May, the earned day expires too early for May and too late for December. Only the employer can settle it; the validity then moves to the rule.
+89 -20
View File
@@ -48,16 +48,33 @@ 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.90 | 0.85 | 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
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
multipliers were 0.15, 0.1, 0.05, 0.05, 2.5, 0.5 and 1.5; before it, 0.25, 3,
0.05, 0.05, 25, 1 and 3.5. A failure lists, per
scenario, the measured mean, the budget, the multiplier and the calibration in
milliseconds.
Ratios come from the development machine's Bun protocol after #321 (calibration
3.44 s, [record](issue-321.md#benchmark-protocol)), and for `default rules`,
added by #348, from the development laptop once its Samedi Malin carries the
reserve of five CP days of
[#378](https://gitea.nessar.fr/nessar/vac-optimizer/issues/378) (calibration
3.39 s; before the reserve 2.81 s and 0.82,
[record](issue-375.md#benchmark-protocol); after #348 2.86 s and 0.81,
[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 multipliers were 0.15, 0.1, 0.05,
0.05, 2.5, 0.5 and 1.5; before it, 0.25, 3, 0.05, 0.05, 25, 1 and 3.5. A failure
lists, per scenario, the measured mean, the budget, the multiplier and the
calibration in milliseconds.
With the reserve, the eight scenarios of the protocol measured on the
development laptop on 2026-11-30 (calibration 3.39 s) are: representative year
0.15 s (0.05), typed obligations 0.05 s (0.02), chained earned entitlements
0.00 s (0.00), deliberate conflict 0.00 s (0.00), loaded year 2.54 s (0.75), two
years 0.51 s (0.15), three years 1.63 s (0.48) and default rules 2.90 s (0.85).
No multiplier changed. Only `default rules` uses the supplied rules; its plan
has 39 placements, against 40 without the reserve, because the Saturday 25
December 2027 is no longer earned: the CP balance expires on 31 December, so
five CP days kept for after that time-off period could not all be placed before
they expire.
The first CI runs of PR #287 (commit `63b50c4`) give consistent ratios on two
runners:
@@ -78,7 +95,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 +150,24 @@ 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 `1e06fe2`. Its rebuilds, latest first:
| Built from | For | The commit | Record |
| ---------- | ---- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| `1e06fe2` | #375 | earns an IF_THEN day behind loss prevention, on top of `56ba9a7`, which expires the earned day with the leave balance in use | [issue-375.md](issue-375.md) |
| `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 +181,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)
@@ -173,6 +233,14 @@ bun src/app/services/frozen-engine/compare-engines.ts small 280000 5000
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 frozen and calibration engines built before the engine took a single
`emit` take positional callbacks and read `request.progress`.
`frozen-engine/callback-signature.ts` gives the current engine that same shape,
so one function type covers both. A frozen engine rebuilt from a commit that
has `emit` takes `emit` itself, so its `.d.mts` and its callers must be updated
at that rebuild. Once both frozen engines take `emit`, delete
`callback-signature.ts`.
The comparison is deliberately not a CI check. The differential check already
fails on any unintended change; the comparison only describes an intended one,
and a fixed acceptance threshold would have to be renegotiated with every
@@ -186,7 +254,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 +263,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.
+193
View File
@@ -0,0 +1,193 @@
# Issue #375: expire the earned day with the leave balance in use, and earn it behind loss prevention
Record for [issue #375](https://gitea.nessar.fr/nessar/vac-optimizer/issues/375).
Two commits change the planner. `56ba9a7` expires an earned leave entitlement
with the leave balance in use ([ADR 0015](../adr/0015-samedi-malin-reserve-and-earned-day-validity.md)).
`1e06fe2` is a search change under
[ADR 0010](../adr/0010-rank-obligation-solutions-before-preferences.md) that
lets an IF_THEN preference earn its day behind loss prevention. The frozen
engine of the [differential check](README.md#frozen-engine-differential-check)
was rebuilt from `1e06fe2` in `2ca5944`, so it carries both commits. The times
were measured on the development laptop (AMD Ryzen 5 7640U, WSL2, Bun 1.4.3),
and every planning run of this record carried a `deadlineMs`. After the
rebuild, `bun test --isolate src/app/services/frozen-engine.spec.ts` passes 47
tests in 30.4 seconds.
## The validity change
An earned leave entitlement still becomes available the day after its
generating time-off period ends. It now expires on the expiry date of the
earliest-expiring reported balance of the rule's requested type that is usable
on that availability date; one year later only when there is none. A balance is
usable on a date when it is available on or before that date and not expired,
whatever its remaining quantity. Earned balances never define another earned
balance's expiry.
## The search change
With the validity change alone, an earned day expires inside the horizon, so
the planner counts it as at risk as soon as it is earned. In the supplied order,
loss prevention first and Samedi Malin second, two things then stopped Samedi
Malin:
- the IF_THEN stage rejected every candidate that earned a day, because
unplaced-at-risk rose from 0 to 1 before anything could place the day;
- before, the days were earned because loss prevention itself put CP on pattern
dates, so those placements were attributed to both loss prevention and Samedi
Malin. Completing a pattern now also earns an at-risk day, so that move no
longer lowers the unplaced count, and loss prevention stopped making it.
Measured at `56ba9a7` alone, the 2027 request of 25 CP and 12 RTT earned 0 days
instead of 3.
The IF_THEN stage now has two mechanisms:
- (a) when a finalized candidate is worse than the baseline on an earlier
leave-balance objective, it places the leave this rule earned on the rule's
first valid date after the availability date, and keeps the candidate only if
the earlier objectives are then no worse than the baseline
(`placeEarnedForEarlierObjective`);
- (b) when the earlier objectives already placed all the requested leave, it
moves one placement held only by optimization rules onto a free pattern date,
and the same leaf check judges the move (`movedOntoPattern`).
A candidate that was already acceptable takes the path it took before.
This lifts the loss that [ADR 0012](../adr/0012-obligation-solutions-hold-only-funding-preference-patterns.md)
accepted: "where loss prevention ranks first and spends the CP a Samedi Malin
pattern needs, the plan no longer earns that day". ADR 0012 said that question
"belongs to its own stage, not to the obligation search". The obligation search
of ADR 0012 is unchanged.
## Comparison before the rebuild
With the old frozen engine (`5aa3f39`) still in place, run through a temporary
copy of `compare-engines.ts` that adds `deadlineMs: 20000` to every request:
```sh
bun src/app/services/frozen-engine/compare-engines.ts small 280000 5000
```
| Result | Requests |
| ----------------------- | -------: |
| Identical | 4,953 |
| Same objective values | 33 |
| Better (tie-break only) | 13 |
| Worse | 1 |
The old frozen engine took 6.7 seconds over the 5,000 requests and the current
engine 6.8 seconds.
The 13 "better (tie-break only)" requests all differ on the `balance-expiry`
tie-break. The earned balance expires sooner, and the tie-break reads an earlier
expiry as better. This is the validity change showing in the tie-break key, not
a better plan. Seeds: 280278, 280503, 280686, 280784, 280802, 282263, 283090,
283639, 283647, 283893, 284059, 284123, 284313.
The 33 "same objective values" requests keep every objective value and differ
elsewhere in the outcome. They were not inspected one by one.
One request became worse on a real objective: seed 282081.
- Horizon 2026-12-14 to 2027-02-05, calculated on 2026-12-14.
- One Other balance `b0` of 2 days, expiring on 2026-12-29.
- An Other day declared on 2027-01-25.
- The rules: the holiday-week value, the longest work sequence, and an IF_THEN
obligation `it0` (Friday public holidays, 2 Other days, `auto`, earning 2
Other days).
- `optimization:default-longest-work-sequence` goes from 8 to 9.
- Old frozen engine: `b0` on 2026-12-23 and 2026-12-24 for the Friday 25
December. The earned days are available on 2026-12-28 and expire on
2027-12-28. They pay 2027-01-04 and 2027-01-05 for Friday 1 January, and a
day earned for 1 January is placed on 2027-01-12 (supporting).
- Current engine: `b0` on 2026-12-28 and 2026-12-29. The earned days are
available on 2026-12-30 and expire on 2027-12-30. They pay 2027-01-04 and
2027-01-05, and the supporting day is on 2027-01-11.
- Why: with the old pattern, the earned days would be available on 28 December,
when `b0` (expiring on 29 December) is still usable, so they would expire on
29 December and could not pay the January pattern the obligation needs. With
the pattern after the holiday, they are available on 30 December, `b0` has
expired, no balance of the requested type is usable, and the one-year fallback
applies. This is the validity rule applied as specified, not a search
regression.
## The multi-year requests
Single runs of the seven multi-year requests, `deadlineMs: 30000`. Unplaced at
risk is 0 in every plan, before and after.
| Request | Samedi Malin satisfied | Christmas satisfied | Placements | Non-working-day gain | Old (s) | Current (s) |
| ---------------------------------------------------------- | ---------------------: | ------------------: | ---------: | -------------------: | ------: | ----------: |
| three years of 5 CP | 2 → 4 | 5 → 5 | 17 → 19 | 27 → 33 | 0.89 | 0.97 |
| two years of 5 CP with a TIME_WINDOW obligation | 0 → 1 | 2 → 2 | 10 → 11 | 20 → 19 | 0.17 | 0.18 |
| two years of 5 CP with Samedi Malin before loss prevention | 2 → 2 | 5 → 5 | 12 → 12 | 21 → 21 | 0.22 | 0.11 |
| one year of 25 CP and 12 RTT | 0 → 1 | 5 → 5 | 37 → 38 | 42 → 48 | 1.10 | 0.44 |
| one year of 25 CP and 12 RTT from 2027 | 3 → 3 | 5 → 5 | 39 → 40 | 53 → 53 | 2.49 | 2.74 |
| three years of 5 CP from 2026 | 0 → 5 | 5 → 4 | 15 → 20 | 24 → 31 | 0.16 | 0.90 |
| one year from 1 September 2025 of 10 CP and 4 RTT | 1 → 2 | 5 → 5 | 29 → 30 | 43 → 43 | 0.26 | 0.38 |
Details:
- Three years of 5 CP: the earned days were for 2027-05-01 and 2027-05-08
before. They are now for 2025-11-01, 2026-08-15, 2027-05-01 and 2027-12-25.
8 May 2027 is no longer earned, and four Saturdays are instead of two.
- Three years of 5 CP from 2026: the Christmas preference goes from 5 to 4. It
ranks after Samedi Malin, which goes from 0 to 5, so the plan is better in
rule priority order.
- Two years with a TIME_WINDOW obligation: the non-working-day gain goes from 20
to 19. It ranks after Samedi Malin, which goes from 0 to 1.
- One year of 25 CP and 12 RTT from 2027: the same three Saturdays are earned.
The day earned for 2027-12-25 used to stay unplaced (deferred, it expired a
year later); it is now placed, hence 40 placements.
- All seven differ from the old frozen engine in the strict comparison. The
request with Samedi Malin before loss prevention differs only through the
expiry dates of its earned days.
- Lower objectives were not compared beyond the columns above.
- Effect of the search change alone (`56ba9a7` to `1e06fe2`): none of the 5,000
seeded requests changed; six of the seven multi-year requests changed, all
except "Samedi Malin before loss prevention".
## Benchmark protocol
Run at `1e06fe2` with `timeout 240s bun test src/app/benchmark --timeout=240000`.
The calibration took 3.42 seconds.
| Scenario | Mean planning (s) | Ratio to calibration | Multiplier |
| --------------------------- | ----------------: | -------------------: | ---------: |
| representative year | 0.17 | 0.05 | 0.1 |
| typed obligations | 0.04 | 0.01 | 0.1 |
| chained earned entitlements | 0.01 | 0.00 | 0.05 |
| deliberate conflict | 0.00 | 0.00 | 0.05 |
| loaded year | 2.64 | 0.77 | 1.25 |
| two years | 0.55 | 0.16 | 0.25 |
| three years | 1.68 | 0.49 | 0.75 |
| default rules | 2.81 | 0.82 | 1.25 |
All eight scenarios are within budget, and no multiplier changed. At `56ba9a7`
alone, `default rules` took 1.50 seconds (ratio 0.44), because it earned
nothing.
## Changed test expectations
- `56ba9a7`:
- the earned expiry dates in `leave-planner.service.spec.ts` (5 cases),
`leave-planner-explanation.spec.ts` (1 case) and
`optimization-integration.spec.ts` (2 cases);
- `optimization-rule.spec.ts`, "finishes behind Samedi Malin with its earned
leave entitlement left": the earned day is now placed by loss prevention
(`ruleIds: ['loss'], supporting: false`) instead of by the gain rule as a
supporting placement;
- the fixture of "compares a generating preference with an ordinary obligation
solution before spending higher-priority leave" gives its RTT balance an
earlier expiry, so the earned CP still expires before the CP balance.
- `1e06fe2`: in `leave-planner-obligation-solutions.spec.ts`, "leaves a pattern
that funds no obligation to its own stage" now gives 11 placements and Samedi
Malin satisfied 1, instead of 10 placements and satisfied 0 with reason
`higher-priority`. The February obligation keeps the same five days as without
Samedi Malin.
## Not measured
- The loaded-year-sized comparison sample (`loaded-year 302000 50`, about an
hour).
- The reference phone and the browser.
+9 -6
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. |
@@ -46,7 +46,7 @@ progress.
## Runners and permissions
Every job that runs project commands uses Bun 1.4.3 with the frozen lockfile (see [Bun toolchain and Node](#bun-toolchain-and-node)). Job containers stay on Node 24.22.0. The image
Every job that runs project commands uses Bun 1.4.5 with the frozen lockfile (see [Bun toolchain and Node](#bun-toolchain-and-node)). Job containers stay on Node 24.22.0. The image
job uses Docker 29.9.1 and its matching Docker-in-Docker service. Scanner
versions are Semgrep 1.180.0 and Trivy 0.75.0; Trivy downloads are checksum-checked.
Trivy downloads its vulnerability database from Aqua's public ECR mirror because
@@ -79,12 +79,14 @@ secret is required by this workflow.
## Bun toolchain and Node
Project commands run on Bun 1.4.3 only. `package.json` (`packageManager`),
Project commands run on Bun 1.4.5 only. `package.json` (`packageManager`),
`@types/bun`, both Docker stages and `scripts/install-bun.sh` carry the same
version. To upgrade, change all of them together and replace the installer's
four SHA-256 values with those of the new release's `SHASUMS256.txt`; the
installer refuses a `package.json` that names a different version, so a bump of
only one place fails CI instead of drifting.
only one place fails CI instead of drifting. Renovate groups `bun`, `@types/bun`
and the `oven/bun` image in one PR that it never automerges; finish that PR by
updating the installer's version and checksums.
- **Install.** `policy`, `validate`, `test`, `benchmark`, `build` and `images`
run `sh scripts/install-bun.sh`. It downloads the release zip for the
@@ -190,8 +192,9 @@ secrets. Complete the remaining activation checks in this order:
checks rather than a push run or a guessed context spelling. Fork PRs must
also be able to satisfy this check without base-repository push permissions.
Keep direct/force pushes disabled, merges restricted to maintainers, outdated
PRs blocked, and administrator protection bypass disabled. Select merge
commits and disable squash/rebase merge methods.
PRs blocked, and administrator protection bypass disabled. Select the rebase
merge method (fast-forward-only may stay enabled) and disable merge commits
and squash.
6. Merge the first PR using the approved message, then verify the resulting merge
commit. Subsequent merges read the committed template. No direct
integration-branch push is needed.
+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
+37 -4
View File
@@ -157,7 +157,7 @@ independently of mutable placement states.
## Saved rules and initialization
`vacationRules` uses one versioned envelope: `{ version: 1, rules: [...] }`.
`vacationRules` uses one versioned envelope: `{ version: 3, rules: [...] }`.
`RuleService` restores it synchronously before the first duration estimate or calculation.
A legacy array, including `[]`, receives loss prevention first, every original record in
its original relative order, then the other five presets. Each original raw record is
@@ -167,6 +167,20 @@ Preset IDs use collision-free suffixes when a personal rule already uses a propo
New users receive the six active presets around the existing Samedi Malin and Christmas
calendar defaults.
Version 2 ([ADR 0015](adr/0015-samedi-malin-reserve-and-earned-day-validity.md)) adds
`reserveDays` to IF_THEN rules. A version-1 envelope or a legacy array is migrated in
the same single write: the IF_THEN rule with the supplied Samedi Malin identity
(`default-samedi-malin`) receives a reserve of five, whether it was edited, disabled or
left untouched, and every other record stays as it is, a missing reserve reading as
zero. A version-2 or version-3 envelope is never given the reserve again, so a value the person sets
afterwards, zero included, is kept.
Version 3 saves every TIME_WINDOW boundary as a `YYYY-MM-DD` planning date. Versions 1 and 2
and the legacy array saved it as an instant (`JSON.stringify` of a `Date`); reading one of
those converts each boundary that is not already a planning date to the calendar date it shows
on the device, then rewrites the list as version 3 in the same single write. A boundary that
cannot be read as a date is left as saved, and the planner reports it as invalid input.
The migration and its version are written by one synchronous `setItem`; no separate
marker can succeed while the rules fail to save. A failed write leaves the original
key intact and permits a later complete save or a fresh reload to retry. Failed reads,
@@ -239,9 +253,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
+20 -1
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
+30
View File
@@ -29,6 +29,36 @@ export default [
'@typescript-eslint/no-deprecated': 'error',
},
},
{
// Length is a prompt to look at the design, never a limit: these stay warnings, which do not fail the lint.
files: ['src/**/*.ts'],
ignores: ['**/*.spec.ts', 'src/testing/**'],
rules: {
'max-lines': ['warn', { max: 800, skipBlankLines: true, skipComments: true }],
'max-lines-per-function': [
'warn',
{ max: 150, skipBlankLines: true, skipComments: true },
],
},
},
{
// The planner core's modules export their internals to each other only: everything else imports the entry point.
files: ['src/**/*.ts'],
ignores: ['src/app/services/leave-planner.core.ts', 'src/app/services/leave-planner-core/**'],
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['**/leave-planner-core/*'],
message: 'Import from leave-planner.core, the entry point.',
},
],
},
],
},
},
{
ignores: ['dist/**', 'node_modules/**', '.angular/**', 'coverage/**'],
},
+13 -13
View File
@@ -1,7 +1,7 @@
{
"name": "vac-optimizer",
"version": "1.5.0",
"packageManager": "bun@1.4.3",
"packageManager": "bun@1.4.5",
"scripts": {
"ng": "ng",
"start": "bun scripts/generate-langs.js && ng serve",
@@ -30,14 +30,14 @@
"private": true,
"dependencies": {
"@angular/cdk": "^22.0.0",
"@angular/common": "22.2.3",
"@angular/compiler": "22.2.3",
"@angular/core": "22.2.3",
"@angular/forms": "22.2.3",
"@angular/common": "22.3.0",
"@angular/compiler": "22.3.0",
"@angular/core": "22.3.0",
"@angular/forms": "22.3.0",
"@angular/material": "^22.0.0",
"@angular/platform-browser": "22.2.3",
"@angular/platform-browser-dynamic": "22.2.3",
"@angular/router": "22.2.3",
"@angular/platform-browser": "22.3.0",
"@angular/platform-browser-dynamic": "22.3.0",
"@angular/router": "22.3.0",
"date-holidays": "^3.30.2",
"dayjs": "^1.11.21",
"rxjs": "~7.8.2",
@@ -45,11 +45,11 @@
},
"devDependencies": {
"@analogjs/vite-plugin-angular": "^2.7.5",
"@angular/build": "22.2.3",
"@angular/cli": "22.2.3",
"@angular/compiler-cli": "22.2.3",
"@angular/build": "22.2.7",
"@angular/cli": "22.2.7",
"@angular/compiler-cli": "22.3.0",
"@eslint/js": "^10.0.1",
"@types/bun": "1.4.3",
"@types/bun": "1.4.5",
"@types/jsdom": "^30.0.0",
"@types/node": "^26.0.0",
"eslint": "^10.4.1",
@@ -59,7 +59,7 @@
"istanbul-lib-coverage": "^3.2.2",
"istanbul-lib-report": "^3.0.1",
"istanbul-reports": "^3.2.0",
"jsdom": "^30.0.0",
"jsdom": "^31.0.0",
"prettier": "^3.8.3",
"typescript": "~6.0.3",
"typescript-eslint": "^8.60.0"
+11 -1
View File
@@ -5,7 +5,7 @@
],
"prConcurrentLimit": 3,
"automerge": false,
"automergeStrategy": "merge-commit",
"automergeStrategy": "rebase",
"minimumReleaseAge": "3 days",
"packageRules": [
{
@@ -16,6 +16,16 @@
"pin"
],
"automerge": true
},
{
"description": "One Bun version everywhere: scripts/install-bun.sh needs the new release's checksums by hand.",
"matchPackageNames": [
"bun",
"@types/bun",
"oven/bun"
],
"groupName": "bun",
"automerge": false
}
]
}
+5 -5
View File
@@ -3,7 +3,7 @@
# Needs curl, unzip and sha256sum. Bun upgrades change the version, package.json and every checksum together.
set -eu
version=1.4.3
version=1.4.5
dest=${BUN_INSTALL_DIR:-/opt/bun}
grep -q "\"packageManager\": \"bun@${version}\"" package.json || {
@@ -23,10 +23,10 @@ libc=
if [ -e /etc/alpine-release ]; then libc=-musl; fi
asset="bun-linux-${arch}${libc}"
case "$asset" in
bun-linux-x64) sha256=3e730528d89775f03f87f05c06787c4df4099d0a37f3f252e7b829cb23816e18 ;;
bun-linux-x64-musl) sha256=6e9ea98554ea0d05efda5840ae292618aaa3adefd66b0853520c5c86a37eac9c ;;
bun-linux-aarch64) sha256=efa9813da5ed72423bf847f916e8d2c47c0d776add972354026a75e10da9aa21 ;;
bun-linux-aarch64-musl) sha256=8de8a0003cc2707bb555887e3d450e24e1edf3f605f491393e89ed61a8853420 ;;
bun-linux-x64) sha256=94559b3b528995a49452f9f2404cec74f2efd7d06e0a000a8cd214b02c3666eb ;;
bun-linux-x64-musl) sha256=9b6bdba1fa0914b6adfe48e4438212e2c106d9199b77ba642a9b8a3968a49a59 ;;
bun-linux-aarch64) sha256=18656a3bf0ea5641f5796ae4213b75255579a70a0fded2f337933785568cdf84 ;;
bun-linux-aarch64-musl) sha256=d655765d3a0c0fdf707e27c7aa1a4f2c84f1bbc1f759db7e6e3d3c5be414396c ;;
esac
work=$(mktemp -d)
+6 -6
View File
@@ -34,7 +34,7 @@ describe('Application Settings', () => {
localStorage.clear();
localStorage.setItem('app.language', JSON.stringify('en'));
localStorage.setItem('leaveBalances', savedBalances);
localStorage.setItem('vacationRules', '{"version":1,"rules":[]}');
localStorage.setItem('vacationRules', '{"version":3,"rules":[]}');
localStorage.setItem('unrelated.entry', 'keep this value');
mediaQuery = Object.assign(new EventTarget(), {
matches: true,
@@ -144,7 +144,7 @@ describe('Application Settings', () => {
expect(root.querySelectorAll('app-calendar-month')).toHaveLength(13);
expect(
root.querySelector('button[data-date="2026-11-11"]')?.getAttribute('aria-label'),
).toContain('Public Holiday');
).toContain('Public holiday');
expect(
root.querySelector('button[data-date="2026-10-10"]')?.getAttribute('aria-label'),
).toContain('Weekend');
@@ -257,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([
@@ -359,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"]')!;
@@ -472,7 +472,7 @@ describe('Application Settings', () => {
await (await dialog.getHarness(MatSlideToggleHarness)).check();
expect(localStorage.getItem('calendarSettings.showWeekNumbers')).toBe('true');
expect(localStorage.getItem('leaveBalances')).toBe(savedBalances);
expect(localStorage.getItem('vacationRules')).toBe('{"version":1,"rules":[]}');
expect(localStorage.getItem('vacationRules')).toBe('{"version":3,"rules":[]}');
expect(localStorage.getItem('unrelated.entry')).toBe('keep this value');
expect(fixture.nativeElement.querySelectorAll('.week-number').length).toBeGreaterThan(
0,
@@ -501,7 +501,7 @@ describe('Application Settings', () => {
TestBed.resetTestingModule();
await createApp();
expect(localStorage.getItem('leaveBalances')).toBe(savedBalances);
expect(localStorage.getItem('vacationRules')).toBe('{"version":1,"rules":[]}');
expect(localStorage.getItem('vacationRules')).toBe('{"version":3,"rules":[]}');
expect(localStorage.getItem('unrelated.entry')).toBe('keep this value');
expect(document.body.classList.contains('dark-mode')).toBe(true);
expect(
+31 -2
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,7 +23,7 @@
</button>
</header>
<main class="planner-layout">
<main class="planner-layout" [attr.data-view]="view()">
<section
class="configuration-panel"
cdkScrollable
@@ -32,7 +34,34 @@
<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>
+72
View File
@@ -103,11 +103,83 @@ 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 {
+213 -1
View File
@@ -1,8 +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 () => {
@@ -13,7 +20,8 @@ describe('App', () => {
});
afterEach(() => {
localStorage.removeItem('app.language');
vi.restoreAllMocks();
localStorage.clear();
document.documentElement.lang = 'en';
});
@@ -60,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);
});
});
});
+76
View File
@@ -1,10 +1,15 @@
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';
@@ -12,12 +17,19 @@ 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';
@@ -30,6 +42,9 @@ function isBenchmarkUrl(url: string): boolean {
MatDatepickerModule,
UserInput,
CalendarYear,
CalculateButton,
DeclarationControls,
RuleSetImport,
MatButton,
MatIcon,
RouterOutlet,
@@ -44,6 +59,18 @@ 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('VacOptimizer');
protected readonly showPlanner = signal(
@@ -57,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');
+164 -123
View File
@@ -40,132 +40,172 @@ const balance = (
expiryDate,
});
export function benchmarkScenarios(): BenchmarkScenario[] {
const horizon = { start: '2024-01-01', end: '2025-01-01' };
const presets = createOptimizationPresetRules();
const scenarios: BenchmarkScenario[] = [
{
name: 'representative year',
const HORIZON = { start: '2024-01-01', end: '2025-01-01' };
const SCENARIOS: BenchmarkScenario[] = [
{
name: 'representative year',
request: {
horizon: HORIZON,
balances: [balance('cp', 'cp', 20), balance('rtt', 'rtt', 10)],
rules: [],
},
},
{
name: 'typed obligations',
request: {
horizon: HORIZON,
balances: [balance('cp', 'cp', 5), balance('rtt', 'rtt', 5)],
rules: [
{
id: 'cp-window',
type: 'time_window',
force: 'obligation',
startDate: '2024-04-08',
endDate: '2024-04-12',
placeDays: 2,
placeType: 'cp',
},
{
id: 'rtt-window',
type: 'time_window',
force: 'obligation',
startDate: '2024-04-08',
endDate: '2024-04-12',
placeDays: 2,
placeType: 'rtt',
},
],
},
},
{
name: 'chained earned entitlements',
request: {
horizon: { start: '2024-04-25', end: '2024-05-15' },
balances: [balance('cp', 'cp', 2), balance('rtt', 'rtt', 0, '2026-01-01')],
rules: [
{
id: 'wednesday-holidays',
type: 'if_then',
force: 'obligation',
dayOfWeek: 3,
placeDays: 1,
placeType: 'cp',
placement: 'before',
rewardDays: 1,
rewardType: 'rtt',
},
{
id: 'thursday-consumer',
type: 'if_then',
force: 'obligation',
dayOfWeek: 4,
placeDays: 1,
placeType: 'rtt',
placement: 'after',
rewardDays: 0,
},
],
},
},
{
name: 'deliberate conflict',
request: {
horizon: HORIZON,
balances: [balance('cp', 'cp', 1)],
rules: [
{
id: 'rtt-required',
type: 'time_window',
force: 'obligation',
startDate: '2024-04-01',
endDate: '2024-04-05',
placeDays: 1,
placeType: 'rtt',
},
],
},
},
{
name: 'loaded year',
request: {
horizon: HORIZON,
balances: Array.from({ length: 6 }, (_, index) =>
balance(`cp-${index}`, index % 2 ? 'rtt' : 'cp', 12),
),
rules: Array.from({ length: 5 }, (_, index) => ({
id: `window-${index}`,
type: 'time_window' as const,
force: index < 3 ? ('obligation' as const) : ('preference' as const),
startDate: `2024-${String(index + 1).padStart(2, '0')}-01`,
endDate: `2024-${String(index + 1).padStart(2, '0')}-28`,
placeDays: 3,
placeType: index % 2 ? ('rtt' as const) : ('any' as const),
})),
},
},
...[2, 3].map(
(years): BenchmarkScenario => ({
name: years === 2 ? 'two years' : 'three years',
request: {
horizon,
balances: [balance('cp', 'cp', 20), balance('rtt', 'rtt', 10)],
horizon: { start: '2024-01-01', end: `${2024 + years}-01-01` },
balances: Array.from({ length: years }, (_, index) => 2024 + index).flatMap(
(year) =>
(['cp', 'rtt'] as const).map((type) => ({
id: `${type}-${year}`,
type,
quantity: type === 'cp' ? 20 : 10,
availableFrom: `${year}-01-01`,
expiryDate: `${year}-12-31`,
})),
),
rules: [],
},
},
{
name: 'typed obligations',
request: {
horizon,
balances: [balance('cp', 'cp', 5), balance('rtt', 'rtt', 5)],
rules: [
{
id: 'cp-window',
type: 'time_window',
force: 'obligation',
startDate: '2024-04-08',
endDate: '2024-04-12',
placeDays: 2,
placeType: 'cp',
},
{
id: 'rtt-window',
type: 'time_window',
force: 'obligation',
startDate: '2024-04-08',
endDate: '2024-04-12',
placeDays: 2,
placeType: 'rtt',
},
],
},
},
{
name: 'chained earned entitlements',
request: {
horizon: { start: '2024-04-25', end: '2024-05-15' },
balances: [balance('cp', 'cp', 2), balance('rtt', 'rtt', 0, '2026-01-01')],
rules: [
{
id: 'wednesday-holidays',
type: 'if_then',
force: 'obligation',
dayOfWeek: 3,
placeDays: 1,
placeType: 'cp',
placement: 'before',
rewardDays: 1,
rewardType: 'rtt',
},
{
id: 'thursday-consumer',
type: 'if_then',
force: 'obligation',
dayOfWeek: 4,
placeDays: 1,
placeType: 'rtt',
placement: 'after',
rewardDays: 0,
},
],
},
},
{
name: 'deliberate conflict',
request: {
horizon,
balances: [balance('cp', 'cp', 1)],
rules: [
{
id: 'rtt-required',
type: 'time_window',
force: 'obligation',
startDate: '2024-04-01',
endDate: '2024-04-05',
placeDays: 1,
placeType: 'rtt',
},
],
},
},
{
name: 'loaded year',
request: {
horizon,
balances: Array.from({ length: 6 }, (_, index) =>
balance(`cp-${index}`, index % 2 ? 'rtt' : 'cp', 12),
),
rules: Array.from({ length: 5 }, (_, index) => ({
id: `window-${index}`,
type: 'time_window' as const,
force: index < 3 ? ('obligation' as const) : ('preference' as const),
startDate: `2024-${String(index + 1).padStart(2, '0')}-01`,
endDate: `2024-${String(index + 1).padStart(2, '0')}-28`,
placeDays: 3,
placeType: index % 2 ? ('rtt' as const) : ('any' as const),
})),
},
},
...[2, 3].map(
(years): BenchmarkScenario => ({
name: years === 2 ? 'two years' : 'three years',
request: {
horizon: { start: '2024-01-01', end: `${2024 + years}-01-01` },
balances: Array.from({ length: years }, (_, index) => 2024 + index).flatMap(
(year) =>
(['cp', 'rtt'] as const).map((type) => ({
id: `${type}-${year}`,
type,
quantity: type === 'cp' ? 20 : 10,
availableFrom: `${year}-01-01`,
expiryDate: `${year}-12-31`,
})),
),
rules: [],
}),
),
{
// 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',
reserveDays: 5,
},
}),
),
];
return scenarios.map((scenario) => ({
{
id: 'christmas',
type: 'time_window',
force: 'preference',
startDate: '2027-12-20',
endDate: '2028-01-03',
placeDays: 5,
placeType: 'any',
},
],
},
},
];
export function benchmarkScenarios(): BenchmarkScenario[] {
const presets = createOptimizationPresetRules();
return SCENARIOS.map((scenario) => ({
...scenario,
request: {
...scenario.request,
@@ -307,7 +347,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 +356,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();
}
}
@@ -17,6 +17,8 @@ import type { LeaveType } from '../../services/leave-planner.service';
export interface DeclarationPreview {
dates: ReadonlySet<string>;
type: LeaveType | null;
/** The previewed dates the declaration would clear instead of set. */
cleared: ReadonlySet<string>;
}
@Component({
@@ -68,10 +70,10 @@ export class CalendarMonth implements OnInit {
declarationPreview: DeclarationPreview | null = null;
getDeclaredType(date: string): LeaveType | undefined {
const current = this.declaredDays[date];
if (!this.declarationPreview?.dates.has(date)) return current;
const selected = this.declarationPreview.type;
return current === selected ? undefined : (selected ?? undefined);
if (!this.declarationPreview?.dates.has(date)) return this.declaredDays[date];
return this.declarationPreview.cleared.has(date)
? undefined
: (this.declarationPreview.type ?? undefined);
}
getDayClasses(day: Date): string {
File diff suppressed because it is too large. Load diff
@@ -148,19 +148,38 @@
}
}
@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>
}
@@ -269,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">
@@ -361,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
@@ -382,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 }} ·
@@ -469,9 +506,21 @@
<h3>{{ contribution.label }}</h3>
<p>
{{ contribution.declaredDays.length }}
{{ tr().bookedDays.booked }} +
{{
counted(
tr().planning.explanation.bookedDays,
contribution.declaredDays.length
)
}}
+
{{ contribution.placementDates.length }}
{{ tr().planning.explanation.leaveDays }} =
{{
counted(
tr().planning.explanation.leaveDays,
contribution.placementDates.length
)
}}
=
<strong
>{{
contribution.declaredDays.length +
@@ -502,9 +551,21 @@
</h3>
<p>
{{ contribution.declaredDays.length }}
{{ tr().bookedDays.booked }} +
{{
counted(
tr().planning.explanation.bookedDays,
contribution.declaredDays.length
)
}}
+
{{ contribution.placementDates.length }}
{{ tr().planning.explanation.leaveDays }} =
{{
counted(
tr().planning.explanation.leaveDays,
contribution.placementDates.length
)
}}
=
<strong
>{{ contribution.requested }} /
{{ contribution.requested }}</strong
@@ -536,6 +597,15 @@
}
</section>
}
@for (
prevention of plan.ifThenReservePreventions ?? [];
track prevention.ruleId + prevention.occurrence
) {
<section class="outcome-explanation declared-rule">
<h3>{{ ruleLabel(prevention.ruleId) }}</h3>
<p>{{ reservePreventionLabel(prevention) }}</p>
</section>
}
@for (period of declaredPeriods(); track period.start) {
<section class="outcome-explanation declared-period">
<h3>
@@ -544,14 +614,37 @@
</h3>
<p>
{{ period.declaredDates!.length }}
{{ tr().bookedDays.booked }} +
{{
counted(
tr().planning.explanation.bookedDays,
period.declaredDates!.length
)
}}
+
{{ period.placementDates.length }}
{{ tr().planning.explanation.leaveDays }} +
{{
counted(
tr().planning.explanation.leaveDays,
period.placementDates.length
)
}}
+
{{ period.nonWorkingDates.length }}
{{ tr().planning.explanation.freeDays }} =
{{
counted(
tr().planning.explanation.freeDays,
period.nonWorkingDates.length
)
}}
=
<strong
>{{ period.duration }}
{{ tr().planning.explanation.daysOff }}</strong
{{
counted(
tr().planning.explanation.daysOff,
period.duration
)
}}</strong
>
</p>
<p>{{ tr().bookedDays.fixed }}</p>
@@ -560,6 +653,23 @@
</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>
@@ -645,89 +755,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>
}
}
@@ -79,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);
@@ -98,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;
}
}
@@ -110,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);
@@ -151,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 {
@@ -183,26 +219,6 @@ code {
font-size: 1.75rem;
}
}
.earned-leave-breakdown {
display: grid;
gap: 0.75rem;
margin: 0;
div {
display: flex;
justify-content: space-between;
gap: 1rem;
}
dt {
min-width: 0;
overflow-wrap: anywhere;
}
dd {
margin: 0;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
}
.placement-explanation,
.outcome-explanation {
display: grid;
@@ -298,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);
@@ -385,6 +402,8 @@ output {
gap: 1rem;
&.declaration-entry {
user-select: none;
// A finger that starts sideways draws a range; one that starts up or down still scrolls (#373).
touch-action: pan-y pinch-zoom;
}
}
.month-card {
@@ -447,6 +466,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';
@@ -41,6 +43,7 @@ import {
PlanExplanation,
PlanningObjective,
PlanningOutcome,
IfThenReservePrevention,
PlanningReason,
} from '../../services/leave-planner.service';
@@ -58,6 +61,7 @@ type PlacementExplanation = PlanExplanation['placements'][number];
CalendarMonth,
DateComparison,
PlanningCriteria,
TimeOffPeriods,
MatCardContent,
MatProgressSpinner,
MatIcon,
@@ -131,7 +135,16 @@ export class CalendarYear {
if (date >= horizon.start && date < horizon.end && isWorkingPlanningDate(date))
dates.add(date);
}
return { dates, type: this.userInput.declaredTypeSignal() };
const type = this.userInput.declaredTypeSignal();
const declared = new Map(this.userInput.declaredDaysSignal().map((day) => [day.date, day]));
const cleared = new Set(
type
? [...dates].filter((date) =>
this.userInput.clearsDeclaredDay(declared.get(date), type),
)
: [],
);
return { dates, type, cleared };
});
/** Without a calculation to display, the calendar shows the current inputs, as during declaration entry. */
private readonly showsInputs = computed(
@@ -169,41 +182,17 @@ export class CalendarYear {
return (
(plan?.timeWindowContributions?.length ?? 0) +
(plan?.ifThenContributions?.length ?? 0) +
(plan?.ifThenReservePreventions?.length ?? 0) +
this.declaredPeriods().length
);
});
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 timeOffPeriodCount = computed(() => {
const plan = this.displayedPlan();
return plan ? timeOffPeriodRows(plan).length : 0;
});
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 statistics = computed(() => {
const plan = this.displayedPlan();
return plan && planStatistics(plan);
});
protected readonly planExplanation = computed(() => {
@@ -351,6 +340,16 @@ export class CalendarYear {
: 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 {
if (!this.displayedPlan() || this.statisticsDialog) return;
const dialog = this.dialog.open(this.statisticsTemplate(), {
@@ -420,8 +419,6 @@ export class CalendarYear {
protected startDeclarationRange(event: PointerEvent): void {
if (!this.declarationEntry() || event.button !== 0 || !event.isPrimary) return;
this.suppressDeclarationClick = false;
// Keep native touch scrolling and single-day taps available on the calendar.
if (event.pointerType === 'touch') return;
const button = this.declarationButton(event.target);
const date = button?.dataset['date'];
if (!date || button?.disabled) return;
@@ -490,8 +487,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);
@@ -571,6 +571,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();
@@ -661,7 +672,11 @@ export class CalendarYear {
}
protected reasonLabel(reason: PlanningReason): string {
return labels.reasonLabel(this.tr(), reason);
return labels.reasonLabel(this.tr(), reason, this.calculations.snapshot());
}
protected reservePreventionLabel(prevention: IfThenReservePrevention): string {
return labels.reservePreventionLabel(this.tr(), prevention, this.calculations.snapshot());
}
protected validationReasonLabel(reason: PlanningReason): string {
@@ -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,46 @@
<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 (chip of chips(); track chip.type + chip.balance) {
<button
mat-stroked-button
type="button"
[attr.data-declared-type]="chip.type"
[attr.data-declared-balance]="chip.balance"
[attr.aria-pressed]="
declaredType() === chip.type &&
(chip.balance === null || chip.balance === declaredBalance())
"
(click)="choose(chip.type, chip.balance)"
>
<span matButtonIcon class="declaration-swatch" aria-hidden="true">
<mat-icon>check</mat-icon>
</span>
{{ chip.label }}
</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,114 @@
: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: flex;
flex-wrap: wrap;
gap: 0.5rem;
padding: 0.75rem;
// Sized by its label, so a long one takes a row instead of wrapping inside the chip.
button {
flex: 0 1 auto;
justify-content: flex-start;
min-height: 2.75rem;
height: auto;
padding: 0.375rem 0.875rem 0.375rem 0.625rem;
border-radius: calc(var(--ui-radius-sm) - 1px);
background-color: var(--ui-card-bg);
color: var(--number-color);
line-height: 1.5;
text-align: start;
&[aria-pressed='true'] {
border-color: var(--mat-sys-primary);
box-shadow: inset 0 0 0 1px var(--mat-sys-primary);
background-color: var(--mat-sys-primary-container);
}
&[aria-pressed='false'] .declaration-swatch mat-icon {
visibility: hidden;
}
}
}
// The declared day as the calendar paints it, so the chip shows what a tap will apply.
.declaration-swatch {
display: grid;
flex: none;
place-items: center;
width: 1.5rem;
height: 1.5rem;
margin-inline-end: 0.5rem;
border: 1px solid color-mix(in srgb, currentColor 30%, transparent);
border-radius: 0.25rem;
background-image: var(--declared-day-pattern);
[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);
}
mat-icon {
width: 1.125rem;
height: 1.125rem;
font-size: 1.125rem;
}
}
// The Erase icon fills the box a swatch takes, so the labels line up.
[data-declaration-erase] > mat-icon {
width: 1.5rem;
height: 1.5rem;
margin-inline: 0 0.5rem;
font-size: 1.5rem;
}
@container declaration-controls (width < 34rem) {
.declaration-types button {
flex: 1 1 30%;
// Dated CP chips stack, which keeps RTT, Other and Erase together on the last row.
&[data-declared-balance] {
flex-basis: 100%;
}
// Four chips make two rows of two rather than three and a lone Erase.
&:first-child:nth-last-child(4),
&:first-child:nth-last-child(4) ~ button {
flex-basis: 40%;
}
}
}
@@ -0,0 +1,103 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SelectableDayType } from '../../services/calendar-service';
import { LeaveBalance, UserInputService } from '../../services/user-input-service';
import { DeclarationControls } from './declaration-controls';
describe('DeclarationControls', () => {
let fixture: ComponentFixture<DeclarationControls>;
let userInput: UserInputService;
const cp = (id: string, expiryDate: string): LeaveBalance => ({
id,
type: SelectableDayType.CP,
numberOfDays: 3,
availableDate: '2026-01-01',
expiryDate: expiryDate,
});
async function create(language: string, ...expiryDates: string[]) {
localStorage.setItem('app.language', JSON.stringify(language));
await TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection()],
}).compileComponents();
userInput = TestBed.inject(UserInputService);
userInput.updateBalances(() => expiryDates.map((date, index) => cp(`cp${index}`, date)));
userInput.declarationEntrySignal.set(true);
fixture = TestBed.createComponent(DeclarationControls);
fixture.detectChanges();
}
const chips = () =>
[...fixture.nativeElement.querySelectorAll('[data-declared-type]')] as HTMLButtonElement[];
const erase = () =>
fixture.nativeElement.querySelector('[data-declaration-erase]') as HTMLButtonElement;
const pressed = () =>
[...chips(), erase()].filter((button) => button.getAttribute('aria-pressed') === 'true');
const text = (button: Element) => button.textContent?.replace(/\s+/g, ' ').trim();
beforeEach(() => localStorage.clear());
afterEach(() => localStorage.clear());
it.each([[[]], [['2027-05-31']]])(
'shows the single CP chip, RTT and Other with %j CP balances',
async (expiryDates) => {
await create('en', ...expiryDates);
expect(chips().map((chip) => chip.dataset['declaredType'])).toEqual([
'cp',
'rtt',
'other',
]);
expect(chips().map((chip) => chip.dataset['declaredBalance'])).toEqual([
undefined,
undefined,
undefined,
]);
expect(text(chips()[0])).toContain('CP');
expect(pressed().map((chip) => chip.dataset['declaredType'])).toEqual(['cp']);
},
);
it('shows one CP chip per balance, labelled with its expiry date in the interface language', async () => {
await create('fr', '2027-05-31', '2026-05-31', '2027-05-31');
expect(chips().map((chip) => chip.dataset['declaredType'])).toEqual([
'cp',
'cp',
'rtt',
'other',
]);
expect(chips().map((chip) => chip.dataset['declaredBalance'])).toEqual([
'2026-05-31',
'2027-05-31',
undefined,
undefined,
]);
expect(text(chips()[0])).toContain('31 mai 2026');
expect(text(chips()[1])).toContain('31 mai 2027');
expect(pressed()).toEqual([chips()[0]]);
});
it('selects the clicked balance, then another type, with exactly one chip pressed', async () => {
await create('en', '2026-05-31', '2027-05-31');
chips()[1].click();
fixture.detectChanges();
expect(userInput.declaredBalanceSignal()).toBe('2027-05-31');
expect(pressed()).toEqual([chips()[1]]);
chips()[2].click();
fixture.detectChanges();
expect(userInput.declaredTypeSignal()).toBe('rtt');
expect(pressed()).toEqual([chips()[2]]);
chips()[0].click();
fixture.detectChanges();
expect(userInput.declaredTypeSignal()).toBe('cp');
expect(pressed()).toEqual([chips()[0]]);
erase().click();
fixture.detectChanges();
expect(userInput.declaredTypeSignal()).toBeNull();
expect(pressed()).toEqual([erase()]);
chips()[3].click();
fixture.detectChanges();
expect(userInput.declaredTypeSignal()).toBe('other');
expect(pressed()).toEqual([chips()[3]]);
});
});
@@ -0,0 +1,58 @@
import { ChangeDetectionStrategy, Component, computed, 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';
interface Chip {
type: LeaveType;
balance: string | null;
label: string;
}
/** 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 declaredBalance = this.userInput.declaredBalanceChoice;
protected readonly translationService = inject(TranslationService);
protected readonly tr = this.translationService.tr;
/** One CP chip per expiry date from two balances on; otherwise the single CP chip. */
protected readonly chips = computed<readonly Chip[]>(() => {
const dates = this.userInput.cpBalanceExpiryDates();
const cp: Chip[] =
dates.length > 1
? dates.map((balance) => ({
type: 'cp',
balance,
label: this.tr().bookedDays.cpUntil.replace(
'{date}',
this.translationService.formatPlanningDate(balance),
),
}))
: [{ type: 'cp', balance: null, label: 'CP' }];
return [
...cp,
...(['rtt', 'other'] as const).map((type) => ({
type,
balance: null,
label: this.translationService.getDayTypeLabel(type),
})),
];
});
protected choose(type: LeaveType, balance: string | null): void {
this.declaredType.set(type);
if (balance) this.userInput.declaredBalanceSignal.set(balance);
}
}
@@ -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,274 @@
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,
reserveDays: 0,
},
{
id: 'christmas',
name: '<b>Noël</b> <img src="x" onerror="alert(1)">',
type: RuleType.TIME_WINDOW,
enabled: false,
force: 'preference',
startDate: '2026-12-20',
endDate: '2027-01-03',
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);
});
}
}
@@ -1,3 +1,4 @@
import { emitTo } from '../../../testing/planning-events';
import { provideZonelessChangeDetection } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
@@ -10,6 +11,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 +48,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 +67,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 +82,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();
}
@@ -115,11 +104,13 @@ describe('calendar rule editing and persistence', () => {
],
rules: service.rules,
},
undefined,
({ explanation }) => {
if (explanation?.kind === 'PlanExplanation')
objectiveValues = explanation.placements[0]?.objectiveVector.objectives ?? [];
},
emitTo({
artifacts: ({ artifacts: { explanation } }) => {
if (explanation?.kind === 'PlanExplanation')
objectiveValues =
explanation.placements[0]?.objectiveVector.objectives ?? [];
},
}),
);
if (plan.kind !== 'Plan')
throw new Error('Expected a plan from saved editor configuration');
@@ -154,8 +145,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 +192,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,230 @@
<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>
<div class="editor-row">
<mat-form-field class="wide-label">
<mat-label>{{ tr().rules.reserveDays }}</mat-label>
<input
matInput
type="number"
[(ngModel)]="$any(editBuffer).reserveDays"
min="0"
/>
</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]="pickerDate($any(editBuffer).startDate)"
(ngModelChange)="setBoundary('startDate', $event)"
/>
<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]="pickerDate($any(editBuffer).endDate)"
(ngModelChange)="setBoundary('endDate', $event)"
/>
<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,288 @@
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 fr from '../../../i18n/fr.json';
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',
reserveDays: 0,
id: expect.any(String),
enabled: true,
});
expect(document.activeElement).toBe(addButton(0));
});
it('offers the reserve on IF_THEN rules only', async () => {
const reserve = () => ruleDialog()!.querySelectorAll('mat-form-field mat-label');
const labels = () => Array.from(reserve(), (label) => label.textContent?.trim());
for (const [index, expected] of [
[0, true],
[1, false],
[2, false],
] as const) {
addButton(index).click();
await fixture.whenStable();
expect(labels().includes(fr.rules.reserveDays)).toBe(expected);
await clickDialogButton(fixture, 'Annuler');
await closed();
}
});
it('takes the reserve like the other quantities: a number field from zero, started at zero', async () => {
addButton(0).click();
await fixture.whenStable();
const input = (label: string, index = 0) =>
dialogField(label, index).querySelector<HTMLInputElement>('input')!;
const reserve = input(fr.rules.reserveDays);
const earned = input('Jours', 1);
expect(reserve.type).toBe(earned.type);
expect(reserve.min).toBe(earned.min);
expect(reserve.value).toBe('0');
await typeInDialog(fixture, fr.rules.reserveDays, '7');
await clickDialogButton(fixture, 'Ajouter');
await closed();
expect(component.rules.at(-1)).toMatchObject({ type: RuleType.IF_THEN, reserveDays: 7 });
});
it('prefills the saved reserve and saves the edited one', async () => {
editButton(1).click();
await fixture.whenStable();
expect(dialogField(fr.rules.reserveDays).querySelector('input')!.value).toBe('5');
await typeInDialog(fixture, fr.rules.reserveDays, '0');
await clickDialogButton(fixture, 'Enregistrer');
await closed();
expect(component.rules[1]).toMatchObject({ id: 'default-samedi-malin', reserveDays: 0 });
});
it('leaves the date being typed as typed', async () => {
addButton(1).click();
await fixture.whenStable();
await typeInDialog(fixture, 'Date de début', '20/12/2024');
await typeInDialog(fixture, 'Date de début', '2/12/2024');
expect(dialogField('Date de début').querySelector('input')!.value).toBe('2/12/2024');
});
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(rule).toMatchObject({ startDate: '2024-12-21', endDate: '2024-12-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,250 @@
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 {
addPlanningDays,
deviceMidnight,
planningDateInParis,
planningDateOnDevice,
} from '../../services/planning-date';
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,
reserveDays: 0,
} 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>;
}
const today = planningDateInParis(new Date());
return {
name: this.tr().rules.defaultNewPeriodName,
type: RuleType.TIME_WINDOW,
force: 'preference',
startDate: today,
endDate: addPlanningDays(today, 7),
placeDays: 5,
placeType: SelectableDayType.CP,
} as Partial<TimeWindowRule>;
}
/** One Date per planning date, so that the picker is not rewritten at every change detection. */
private readonly pickerDates = new Map<string, Date>();
protected pickerDate(key: string): Date {
let date = this.pickerDates.get(key);
if (!date) this.pickerDates.set(key, (date = deviceMidnight(key)));
return date;
}
protected setBoundary(boundary: 'startDate' | 'endDate', value: Date | null) {
if (!value || this.editBuffer.type !== RuleType.TIME_WINDOW) return;
const key = planningDateOnDevice(value);
this.editBuffer[boundary] = key;
// The picker keeps the Date it emitted, so what the person is typing is not rewritten.
this.pickerDates.set(key, value);
}
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,79 @@ 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>' +
fr.rules.ifThenReserve.other.replace('{reserve}', '5 jours de congés payés') +
'.',
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>, if <strong>5 days of paid leave</strong> remain.',
);
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' +
de.rules.ifThenReserve.other.replace('{reserve}', '5 Tage bezahlten Urlaub') +
'.',
);
});
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('mentions a reserve above zero at the end of the sentence and leaves a zero reserve out', () => {
const samediMalin = component.rules[1];
if (samediMalin.type !== RuleType.IF_THEN) throw new Error('Expected an IF_THEN rule');
expect(samediMalin.reserveDays).toBe(5);
const translations = TestBed.inject(TranslationService);
translations.setLanguage('en');
expect(component.getRuleSummary(samediMalin)).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>, if <strong>5 days of paid leave</strong> remain.',
);
expect(component.getRuleSummary({ ...samediMalin, reserveDays: 1, rewardDays: 0 })).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, if <strong>1 day of paid leave</strong> remains.',
);
const noReserve = component.getRuleSummary({ ...samediMalin, reserveDays: 0 });
expect(noReserve).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>.',
);
const { reserveDays: _, ...saved } = samediMalin;
expect(component.getRuleSummary(saved as VacationRule)).toBe(noReserve);
for (const language of translations.availableLanguages) {
translations.setLanguage(language);
const summary = component.getRuleSummary({ ...samediMalin, reserveDays: 12 });
expect(summary).toContain('12');
expect(summary).not.toMatch(/[{}]|\(s\)/);
}
});
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,
reserveDays: 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 +159,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 +181,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 +195,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 +206,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 +268,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: '2027-01-03',
endDate: '2026-12-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: '2027-01-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.',
});
});
});
});
+134 -247
View File
@@ -2,42 +2,25 @@ 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 { deviceMidnight } from '../../services/planning-date';
import { RuleDialog, type RuleDialogData } from './rule-dialog';
import { CdkDragDrop, CdkDropList, CdkDrag, CdkDragHandle } from '@angular/cdk/drag-drop';
@Component({
@@ -47,12 +30,6 @@ import { CdkDragDrop, CdkDropList, CdkDrag, CdkDragHandle } from '@angular/cdk/d
MatIconModule,
MatButtonModule,
MatSlideToggleModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
MatDatepickerModule,
FormsModule,
NgTemplateOutlet,
CdkDropList,
CdkDrag,
CdkDragHandle,
@@ -60,12 +37,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 +49,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 +169,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 +197,46 @@ 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),
)
: '') +
// Appended before the final stop; a saved rule without a reserve reads as zero.
(rule.reserveDays > 0
? labels
.plural(tr, tr.rules.ifThenReserve, rule.reserveDays)
.replace('{reserve}', days(rule.reserveDays, rule.placeType))
: ''),
);
}
return tr.rules.timeWindowTemplate
.replace('{placeDays}', days(rule.placeDays, rule.placeType))
.replace('{startDate}', deviceMidnight(rule.startDate).toLocaleDateString(locale))
.replace('{endDate}', deviceMidnight(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);
}
}
+2 -67
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">
@@ -81,50 +78,7 @@
<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>
@@ -133,26 +87,7 @@
@if (duration.estimate() && !nothingToPlan()) {
<p id="planning-duration-estimate" class="duration-estimate">{{ durationLabel() }}</p>
}
<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)="triggerComputation()"
>
<mat-icon aria-hidden="true">auto_awesome</mat-icon>
{{ tr().userInput.calculate }}
</button>
<app-calculate-button></app-calculate-button>
</div>
@if (hasRemainingDays()) {
+4 -110
View File
@@ -91,75 +91,6 @@
}
}
.declaration-controls {
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;
}
}
}
.day-input-wrapper {
animation: slide-fade-in 200ms ease-out;
@@ -197,19 +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: contents;
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;
@@ -223,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);
@@ -275,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));
@@ -306,7 +218,6 @@ form {
column-gap: 1.5rem;
}
.section-heading,
.calculate-button,
.warning-card {
grid-column: 1 / -1;
}
@@ -315,21 +226,7 @@ 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 {
@@ -348,7 +245,4 @@ form {
background: var(--ui-card-bg);
border-block-start: 1px solid var(--ui-border);
}
.duration-estimate {
margin: 0;
}
}
@@ -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';
@@ -68,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();
@@ -142,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');
@@ -198,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());
@@ -214,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();
});
@@ -225,13 +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.
expect(calculate.parentElement?.classList).toContain('calculate-bar');
expect(root.querySelector('#planning-duration-estimate')?.parentElement).toBe(
calculate.parentElement,
);
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();
@@ -280,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);
@@ -304,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',
@@ -322,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();
@@ -386,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',
@@ -419,7 +429,7 @@ describe('UserInput', () => {
expect(calculate.disabled).toBe(true);
expect(calculate.getAttribute('aria-describedby')).toBe('leave-balances-empty');
expect(root.querySelector('#planning-duration-estimate')).toBeNull();
component.triggerComputation();
calculateDirectly();
expect(createCalculation).not.toHaveBeenCalled();
expect(localStorage.getItem('leaveBalances')).toBeNull();
expect(localStorage.getItem('app.language')).toBe('"en"');
+4 -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,10 +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 nothingToPlan = this.userInputService.nothingToPlan;
protected readonly declaredTypes: readonly LeaveType[] = ['cp', 'rtt', 'other'];
protected readonly calendarSettings = inject(CalendarSettingsService);
protected readonly duration = inject(PlanningDurationService);
private readonly calculations = inject(PlanningCalculationService);
@@ -173,9 +173,4 @@ export class UserInput {
days.map((day, i) => (i === index ? updatedDay : day)),
);
}
public triggerComputation() {
if (this.calendarSettings.planningHorizonError() || this.nothingToPlan()) return;
this.calculations.start();
}
}
@@ -36,7 +36,7 @@
<mat-icon aria-hidden="true">date_range</mat-icon>
<span
>{{ tr().userInput.expires }}
{{ day().expiryDate.toLocaleDateString(translationService.locale()) }}</span
{{ expiryDate().toLocaleDateString(translationService.locale()) }}</span
>
<mat-icon class="dates-chevron" aria-hidden="true">expand_more</mat-icon>
</summary>
@@ -46,7 +46,7 @@
<input
matInput
[matDatepicker]="availablePicker"
[value]="day().availableDate"
[value]="availableDate()"
(dateChange)="addAvailabilityEvent($event)"
/>
<mat-datepicker-toggle
@@ -60,7 +60,7 @@
<input
matInput
[matDatepicker]="picker"
[value]="day().expiryDate"
[value]="expiryDate()"
(dateChange)="addEvent($event)"
/>
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
@@ -13,7 +13,7 @@ describe('DayInput', () => {
id: 'test-id',
type: SelectableDayType.CP,
numberOfDays: 5,
expiryDate: new Date('2025-12-31'),
expiryDate: '2025-12-31',
};
beforeEach(async () => {
@@ -43,11 +43,10 @@ describe('DayInput', () => {
it('emits an availability-date change without mutating the input value', () => {
const emitted: LeaveBalance[] = [];
component.dayChange.subscribe((value) => emitted.push(value));
const availableDate = new Date('2025-02-03T00:00:00');
component.addAvailabilityEvent({ value: availableDate } as never);
component.addAvailabilityEvent({ value: new Date(2025, 1, 3) } as never);
expect(emitted[0].availableDate).toBe(availableDate);
expect(emitted[0].availableDate).toBe('2025-02-03');
expect(mockLeaveBalance.availableDate).toBeUndefined();
});
});
@@ -1,6 +1,15 @@
import { Component, input, output, ChangeDetectionStrategy, inject, effect } from '@angular/core';
import {
Component,
computed,
input,
output,
ChangeDetectionStrategy,
inject,
effect,
} from '@angular/core';
import { SelectableDayType } from '../../../services/calendar-service';
import { LeaveBalance } from '../../../services/user-input-service';
import { deviceMidnight, planningDateOnDevice } from '../../../services/planning-date';
import { TranslationService } from '../../../services/translation-service';
import { MatCard } from '@angular/material/card';
import { MatOption, MatSelect } from '@angular/material/select';
@@ -41,6 +50,12 @@ export class DayInput {
public dayChange = output<LeaveBalance>();
public deleteEntry = output<void>();
protected readonly availableDate = computed(() => {
const date = this.day().availableDate;
return date ? deviceMidnight(date) : null;
});
protected readonly expiryDate = computed(() => deviceMidnight(this.day().expiryDate));
protected readonly translationService = inject(TranslationService);
private readonly dateAdapter = inject(DateAdapter);
@@ -68,11 +83,16 @@ export class DayInput {
}
addEvent(event: MatDatepickerInputEvent<Date>) {
if (event.value) this.dayChange.emit({ ...this.day(), expiryDate: event.value });
if (event.value)
this.dayChange.emit({
...this.day(),
expiryDate: planningDateOnDevice(event.value),
});
}
addAvailabilityEvent(event: MatDatepickerInputEvent<Date>) {
const value = event.value;
if (value) this.dayChange.emit({ ...this.day(), availableDate: value });
if (value)
this.dayChange.emit({ ...this.day(), availableDate: planningDateOnDevice(value) });
}
}
@@ -5,6 +5,8 @@ import type { LeaveType } from './leave-planner.core';
export interface DeclaredNonWorkingDay {
date: string;
type: LeaveType;
/** Expiry date of the leave balance a CP day was booked from; days saved without it stay valid. */
balanceExpiryDate?: string;
}
const holidaysByYear = new Map<number, Set<string>>();
@@ -37,14 +39,19 @@ export function parseDeclaredDays(value: unknown): DeclaredNonWorkingDay[] {
return value.map((item: unknown) => {
if (typeof item !== 'object' || item === null)
throw new Error('Each declared non-working day needs a date and leave type.');
const { date, type } = item as Record<string, unknown>;
const { date, type, balanceExpiryDate } = item as Record<string, unknown>;
if (!isWorkingPlanningDate(date) || dates.has(date))
throw new Error(
'Declared dates must be unique working days outside French public holidays.',
);
if (type !== 'cp' && type !== 'rtt' && type !== 'other')
throw new Error('Declared non-working days must have a CP, RTT, or Other type.');
if (
balanceExpiryDate !== undefined &&
(type !== 'cp' || !isPlanningDate(balanceExpiryDate))
)
throw new Error('A declared balance expiry date must be a date on a CP day.');
dates.add(date);
return { date, type };
return balanceExpiryDate === undefined ? { date, type } : { date, type, balanceExpiryDate };
});
}
+25 -3
View File
@@ -1,11 +1,10 @@
import { afterAll, describe, expect, it } from 'bun:test';
import { frenchPublicHolidaysForYear } from './declared-non-working-days';
import type { PlanningArtifacts, PlanningOutcome } from './leave-planner.core';
import {
calculatePlanningAsyncInternal,
calculatePlanningInternal,
type PlanningArtifacts,
type PlanningOutcome,
} from './leave-planner.core';
} from './frozen-engine/callback-signature';
import {
calculatePlanningAsyncInternal as frozenCalculateAsync,
calculatePlanningInternal as frozenCalculate,
@@ -18,6 +17,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 +91,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 +184,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);
@@ -0,0 +1,73 @@
// The current engine reports through one `emit`; the frozen engines still take callbacks and read
// `request.progress`. This gives the current engine their signature, so one function type covers both.
import {
calculatePlanningAsyncInternal as calculateAsync,
calculatePlanningInternal as calculate,
type PlanningArtifacts,
type PlanningEmit,
} from '../leave-planner.core';
import type {
InterruptionReason,
PlanOutcome,
PlanningExplanation,
PlanningOutcome,
PlanningStateSnapshot,
} from '../leave-planner.service';
export type PlanningCheckpoint = (plan: PlanOutcome, state?: PlanningStateSnapshot) => void;
export type PlanningArtifactsCallback = (artifacts: PlanningArtifacts) => void;
export type PlanningOutcomeCallback = (outcome: PlanningOutcome) => void;
export type PlanningExplanationCallback = (
explanation: PlanningExplanation | undefined,
explanationError: InterruptionReason | undefined,
finalState: PlanningStateSnapshot | undefined,
) => void;
function emitFromCallbacks(
request: unknown,
checkpoint?: PlanningCheckpoint,
artifacts?: PlanningArtifactsCallback,
outcome?: PlanningOutcomeCallback,
explanation?: PlanningExplanationCallback,
): PlanningEmit | undefined {
const given = (request as { progress?: unknown } | undefined)?.progress;
const progress = typeof given === 'function' ? given : undefined;
// With nobody listening the engine builds no checkpoint, as a frozen engine given no callback does.
if (!progress && !checkpoint && !artifacts && !outcome && !explanation) return undefined;
return (event) => {
if (event.type === 'progress') progress?.(event.stage);
else if (event.type === 'checkpoint') checkpoint?.(event.plan, event.state);
else if (event.type === 'result') outcome?.(event.outcome);
else if (event.type === 'explanation')
explanation?.(event.explanation, event.explanationError, event.finalState);
else artifacts?.(event.artifacts);
};
}
export function calculatePlanningInternal(
request: unknown,
checkpoint?: PlanningCheckpoint,
artifacts?: PlanningArtifactsCallback,
outcome?: PlanningOutcomeCallback,
explanation?: PlanningExplanationCallback,
): PlanningOutcome {
return calculate(
request,
emitFromCallbacks(request, checkpoint, artifacts, outcome, explanation),
);
}
export function calculatePlanningAsyncInternal(
request: unknown,
checkpoint?: PlanningCheckpoint,
artifacts?: PlanningArtifactsCallback,
outcome?: PlanningOutcomeCallback,
explanation?: PlanningExplanationCallback,
isCancelled?: () => boolean,
): Promise<PlanningOutcome> {
return calculateAsync(
request,
emitFromCallbacks(request, checkpoint, artifacts, outcome, explanation),
isCancelled,
);
}
@@ -9,7 +9,7 @@ import { compareObjectiveValues } from '../planning-objectives';
// The preset rules come from an Angular service file, which needs the JIT compiler outside tests.
await import('@angular/compiler');
const { generateLoadedYearRequest, generateRequest } = await import('./random-planning-requests');
const current = await import('../leave-planner.core');
const current = await import('./callback-signature');
const baselines = {
frozen: await import('./leave-planner.core.frozen.mjs'),
calibration: await import('./leave-planner.core.calibration.mjs'),
@@ -1,10 +1,10 @@
import type { PlanningOutcome } from '../leave-planner.core';
import type {
PlanningArtifactsCallback,
PlanningCheckpoint,
PlanningExplanationCallback,
PlanningOutcome,
PlanningOutcomeCallback,
} from '../leave-planner.core';
} from './callback-signature';
export function calculatePlanningInternal(
request: unknown,
@@ -1,10 +1,10 @@
import type { PlanningOutcome } from '../leave-planner.core';
import type {
PlanningArtifactsCallback,
PlanningCheckpoint,
PlanningExplanationCallback,
PlanningOutcome,
PlanningOutcomeCallback,
} from '../leave-planner.core';
} from './callback-signature';
export function calculatePlanningInternal(
request: unknown,
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('./callback-signature'),
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'));
@@ -1,3 +1,4 @@
import { emitTo } from '../../testing/planning-events';
import { describe, expect, it } from 'bun:test';
import {
analyzeCounterfactualInternal,
@@ -48,8 +49,7 @@ function calculate(request: PlanningRequest, calculationDate = '2024-04-01') {
let artifacts: PlanningArtifacts = {};
const plan = calculatePlanningInternal(
{ ...request, calculationDate },
undefined,
(value) => (artifacts = value),
emitTo({ artifacts: (event) => (artifacts = event.artifacts) }),
);
if (plan.kind !== 'Plan') throw new Error(`Expected a plan, received ${plan.kind}`);
return { plan, artifacts };
@@ -1,6 +1,7 @@
import { createOptimizationPresetRules } from './rule-service';
import { vi } from '../../testing/vitest-compat';
import { createInProcessCalculation, scriptedJobs } from '../../testing/planning-jobs';
import { emitTo } from '../../testing/planning-events';
import { createPlanningCalculation, type PlanningIncompleteOutcome } from './leave-planner.service';
const request = {
@@ -35,16 +36,13 @@ describe('user cancellation', () => {
let interrupted = false;
let artifacts: import('./leave-planner.core').PlanningArtifacts = {};
const outcome = await core.calculatePlanningAsyncInternal(
{
...submitted,
progress: (stage: string) => {
submitted,
emitTo({
progress: ({ stage }) => {
if (stage === 'optimization:default-non-working-day-gain') interrupted = true;
},
},
undefined,
(value) => (artifacts = value),
undefined,
undefined,
artifacts: (event) => (artifacts = event.artifacts),
}),
() => interrupted,
);
const completed = core.calculatePlanningInternal(submitted);
@@ -107,16 +105,13 @@ describe('user cancellation', () => {
let interrupted = false;
let artifacts: import('./leave-planner.core').PlanningArtifacts = {};
const outcome = await core.calculatePlanningAsyncInternal(
{
...submitted,
progress: (stage: string) => {
submitted,
emitTo({
progress: ({ stage }) => {
if (stage === 'optimization:default-holiday-week-value') interrupted = true;
},
},
undefined,
(value) => (artifacts = value),
undefined,
undefined,
artifacts: (event) => (artifacts = event.artifacts),
}),
() => interrupted,
);
const completed = core.calculatePlanningInternal(submitted);
@@ -190,24 +185,24 @@ describe('user cancellation', () => {
],
...presets.slice(1),
],
progress: (stage: string) => {
if (stage === 'optimization:default-longest-work-sequence') cancelled = true;
},
};
const outcome = await core.calculatePlanningAsyncInternal(
submitted,
(plan, state) => {
if (!state) return;
const explained = core.explainIncompleteCheckpoint(submitted, plan, state, {
code: 'user-cancelled',
message: 'Cancelled',
}).explanation;
if (explained?.kind === 'PlanExplanation' && explained.placements.length)
checkpoints.push(explained.placements[0].objectiveVector.objectives);
},
(value) => (artifacts = value),
undefined,
undefined,
emitTo({
progress: ({ stage }) => {
if (stage === 'optimization:default-longest-work-sequence') cancelled = true;
},
checkpoint: ({ plan, state }) => {
if (!state) return;
const explained = core.explainIncompleteCheckpoint(submitted, plan, state, {
code: 'user-cancelled',
message: 'Cancelled',
}).explanation;
if (explained?.kind === 'PlanExplanation' && explained.placements.length)
checkpoints.push(explained.placements[0].objectiveVector.objectives);
},
artifacts: (event) => (artifacts = event.artifacts),
}),
() => cancelled,
);
expect(outcome).toMatchObject({
@@ -267,16 +262,13 @@ describe('user cancellation', () => {
rules: presets,
};
const cancelled = await core.calculatePlanningAsyncInternal(
{
...submitted,
progress: (stage: string) => {
submitted,
emitTo({
progress: ({ stage }) => {
if (stage === 'optimization:default-non-working-day-gain') interrupted = true;
},
},
undefined,
(value) => (artifacts = value),
undefined,
undefined,
artifacts: (event) => (artifacts = event.artifacts),
}),
() => interrupted,
);
if (cancelled.kind !== 'PlanningIncomplete' || !cancelled.incumbent)
@@ -348,8 +340,7 @@ describe('user cancellation', () => {
let artifacts: import('./leave-planner.core').PlanningArtifacts = {};
const plan = core.calculatePlanningInternal(
request,
undefined,
(value) => (artifacts = value),
emitTo({ artifacts: (event) => (artifacts = event.artifacts) }),
);
expect(plan.kind).toBe('Plan');
const { jobs, start } = scriptedJobs();
@@ -0,0 +1,486 @@
import { declaredWindowDays, occurrences, patternDateSatisfied, patternsFor } from './patterns';
import {
earnedPeriodBounds,
finalizeEarnedState,
occurrenceSatisfied,
selectedOccurrencePattern,
} from './placement';
import { selectorMatches } from './search-context';
import { cloneState, releasePlacement } from './state';
import {
activeObjectives,
activeObjectiveVector,
objectiveVector,
tieBreakObjectives,
unsatisfiedObligationCount,
} from './state-objectives';
import type {
LeaveType,
NormalizedCalendarRule,
NormalizedOptimizationRule,
NormalizedRule,
PlanningObjective,
PlanningObjectiveVector,
SearchContext,
State,
} from './types';
import { compareDate, isAtRisk, optimizationObservations } from '../plan-observations';
import {
compareObjectiveLists,
compareObjectiveValues,
evaluateValidatedOptimization,
OPTIMIZATION_PRESETS,
type OptimizationObservations,
} from '../planning-objectives';
export function reconcileOptimizationProvenance(
state: State,
context: SearchContext,
before: State,
objectives: readonly PlanningObjective[] = activeObjectiveVector(state, context),
): State {
const optimizations = objectives.filter(({ id }) => id.startsWith('optimization:'));
if (!optimizations.length) return state;
let result = state;
let observations: OptimizationObservations | undefined;
for (const placement of state.placements.values()) {
const previous = before.placements.get(placement.date);
const creditedIds = new Set([...placement.ruleIds, ...(previous?.ruleIds ?? [])]);
const credits = optimizations.filter(({ id }) =>
creditedIds.has(id.slice('optimization:'.length)),
);
if (!credits.length) continue;
const withoutState = releasePlacement(state, placement.date);
// Only credited objectives are compared, so skip observing the others.
const withoutPlacement = [
...activeObjectives(
withoutState,
context,
Number.POSITIVE_INFINITY,
new Set(credits.map(({ id }) => id)),
),
];
const ruleIds = new Set(
[...placement.ruleIds].filter(
(id) => !credits.some((objective) => objective.id === `optimization:${id}`),
),
);
for (const objective of credits) {
const without = withoutPlacement.find(({ id }) => id === objective.id)!;
const id = objective.id.slice('optimization:'.length);
const rule = context.rules.find(
(rule): rule is NormalizedOptimizationRule =>
rule.id === id && rule.type === 'optimization',
)!;
const compared = compareObjectiveValues(
objective.direction,
objective.value,
without.value,
);
let contributes = compared < 0;
if (compared === 0 && rule.configuration.aggregation === 'maximum') {
// Another tied maximum can mask a placement's improvement to its own element.
observations ??= optimizationObservations(state, context);
const withoutObservations = optimizationObservations(withoutState, context);
// Every catalog row accepts the sum, so this stays a valid configuration.
const summed = { ...rule.configuration, aggregation: 'sum' as const };
const summedComparison = compareObjectiveValues(
objective.direction,
evaluateValidatedOptimization(summed, observations),
evaluateValidatedOptimization(summed, withoutObservations),
);
contributes =
summedComparison < 0 ||
(summedComparison === 0 &&
rule.configuration.elements === 'time-off-periods' &&
objective.direction === 'maximize' &&
observations.timeOffPeriods.length <
withoutObservations.timeOffPeriods.length);
}
if (contributes) ruleIds.add(id);
}
if (
ruleIds.size === placement.ruleIds.size &&
[...ruleIds].every((id) => placement.ruleIds.has(id))
)
continue;
if (result === state) result = cloneState(state);
result.placements.get(placement.date)!.ruleIds = ruleIds;
}
return result;
}
export function supportingCalendarBenefit(
before: OptimizationObservations,
after: State,
context: SearchContext,
): boolean {
const observations = optimizationObservations(after, context);
return (
evaluateValidatedOptimization(OPTIMIZATION_PRESETS.holidayWeekValue, observations) >
evaluateValidatedOptimization(OPTIMIZATION_PRESETS.holidayWeekValue, before) ||
evaluateValidatedOptimization(OPTIMIZATION_PRESETS.nonWorkingDayGain, observations) >
evaluateValidatedOptimization(OPTIMIZATION_PRESETS.nonWorkingDayGain, before) ||
evaluateValidatedOptimization(OPTIMIZATION_PRESETS.longestWorkSequence, observations) <
evaluateValidatedOptimization(OPTIMIZATION_PRESETS.longestWorkSequence, before) ||
evaluateValidatedOptimization(OPTIMIZATION_PRESETS.shortSequenceDeficit, observations) <
evaluateValidatedOptimization(OPTIMIZATION_PRESETS.shortSequenceDeficit, before)
);
}
const rulesByIdCache = new WeakMap<SearchContext, Map<string, NormalizedRule>>();
export function finalizeRuleCandidate(
state: State,
context: SearchContext,
before: State,
): State | null {
let result = state;
const windowCredits = new Map<string, number>();
const patternCredits = new Map<string, Set<string>>();
let rulesById = rulesByIdCache.get(context);
if (!rulesById) {
// The first rule wins, as with find: ids are unique once a request is validated.
rulesById = new Map([...context.rules].reverse().map((rule) => [rule.id, rule]));
rulesByIdCache.set(context, rulesById);
}
for (const placement of state.placements.values()) {
let lostCalendarRequest = false;
let hasCalendarRequest = false;
for (const id of placement.ruleIds) {
const rule = rulesById.get(id);
if (rule?.type === 'optimization') continue;
const valid = counterfactualRuleValid(
placement.date,
placement.type,
[id],
context,
state,
);
const credited = windowCredits.get(id) ?? 0;
let withinRequest = true;
if (rule?.type === 'time_window')
withinRequest =
credited <
Math.max(0, rule.placeDays - declaredWindowDays(rule, context).length);
else if (rule?.type === 'if_then') {
if (!patternCredits.has(id))
patternCredits.set(
id,
new Set(
occurrences(rule, context).flatMap(
(occurrence) =>
selectedOccurrencePattern(rule, occurrence, state, context) ??
[],
),
),
);
withinRequest = patternCredits.get(id)!.has(placement.date);
}
if (valid && withinRequest) {
hasCalendarRequest = true;
if (rule?.type === 'time_window') windowCredits.set(id, credited + 1);
continue;
}
if (!valid && rule?.force === 'obligation') return null;
if (result === state) result = cloneState(state);
result.placements.get(placement.date)!.ruleIds.delete(id);
lostCalendarRequest = true;
}
const current = result.placements.get(placement.date)!;
const previous = before.placements.get(placement.date);
let supporting = current.supporting;
if (hasCalendarRequest) supporting = false;
else if (
lostCalendarRequest ||
(previous &&
(previous.balanceId !== placement.balanceId ||
previous.supporting !== current.supporting))
) {
const balance = result.balances.find((item) => item.id === placement.balanceId)!;
supporting =
!isAtRisk(balance, context) &&
(current.supporting ||
(previous?.balanceId === placement.balanceId && previous.supporting) ||
supportingCalendarBenefit(
optimizationObservations(releasePlacement(result, placement.date), context),
result,
context,
));
}
if (supporting !== current.supporting) {
if (result === state) result = cloneState(state);
result.placements.get(placement.date)!.supporting = supporting;
}
}
for (const activation of state.earnedActivations) {
const rule = context.rules.find(
(item): item is NormalizedCalendarRule =>
item.type === 'if_then' && item.id === activation.ruleId,
)!;
if (occurrenceSatisfied(rule, activation.occurrence, [activation.dates], state, context))
continue;
if (
[...state.placements.values()].some(
(placement) => placement.balanceId === activation.id,
)
)
return null;
result = cloneState(result);
result.earnedActivations = result.earnedActivations.filter(
(item) => item.id !== activation.id,
);
result.balances = result.balances.filter((balance) => balance.id !== activation.id);
}
const finalized = finalizeEarnedState(result, context);
return finalized && !unsatisfiedObligationCount(finalized, context) ? finalized : null;
}
type FinalizeInvariance = 'exact' | 'settled-earning' | 'unknown';
const finalizeInvarianceCache = new WeakMap<SearchContext, FinalizeInvariance[]>();
/**
* Finalizing never moves or retypes placements; it only edits ruleIds, supporting, and earned
* activations/balances. Preference results and the calendar optimizations (public-holiday-weeks,
* time-off-periods, work-sequences) read only placement dates and types, so the pre-finalize
* value is already the final one. leave-balances is exact only when finalizing leaves the earned
* balances as they are ({@link earningSettled}). leave-placements reads `supporting`, which
* finalizing rewrites. Entries follow activeObjectives order.
*/
function finalizeInvariance(context: SearchContext): FinalizeInvariance[] {
let entries = finalizeInvarianceCache.get(context);
if (!entries) {
entries = context.rules
.filter((rule) => rule.enabled && rule.force === 'preference')
.map((rule) => {
if (rule.type !== 'optimization') return 'exact';
switch (rule.configuration.elements) {
case 'public-holiday-weeks':
case 'time-off-periods':
case 'work-sequences':
return 'exact';
case 'leave-balances':
return 'settled-earning';
default:
// New element kinds stay unpruned until their bound is argued.
return 'unknown';
}
});
finalizeInvarianceCache.set(context, entries);
}
return entries;
}
/**
* True when a successful finalization would leave every balance's remaining quantity and expiry
* untouched. It mirrors finalizeEarnedState: no new pattern earns, every activation keeps its
* pattern, and its balance already carries the period bounds. A candidate that fails to finalize
* is rejected whatever its objectives, so its value needs no bound.
*/
function earningSettled(candidate: State, context: SearchContext): boolean {
for (const rule of context.rules) {
if (rule.type !== 'if_then' || !rule.rewardDays) continue;
for (const occurrence of occurrences(rule, context)) {
if (
!candidate.earnedActivations.some(
(activation) =>
activation.ruleId === rule.id && activation.occurrence === occurrence,
) &&
selectedOccurrencePattern(rule, occurrence, candidate, context)
)
return false;
}
}
for (const activation of candidate.earnedActivations) {
const rule = context.rules.find(
(item): item is NormalizedCalendarRule =>
item.type === 'if_then' && item.id === activation.ruleId,
);
const balance = candidate.balances.find((item) => item.id === activation.id);
if (
!rule ||
!balance ||
!occurrenceSatisfied(
rule,
activation.occurrence,
[activation.dates],
candidate,
context,
)
)
return false;
const bounds = earnedPeriodBounds(candidate, activation, context);
if (
bounds.availableFrom <= context.request.calculationDate ||
balance.availableFrom !== bounds.availableFrom ||
balance.expiryDate !== bounds.expiryDate
)
return false;
}
return true;
}
/** True when the first differing finalize-invariant protected objective is already worse than the baseline. */
function provablyWorseThanProtectedPrefix(
candidate: State,
context: SearchContext,
throughIndex: number,
baseline: readonly PlanningObjective[],
): boolean {
const invariance = finalizeInvariance(context);
let index = 0;
let settled: boolean | undefined;
for (const objective of activeObjectives(candidate, context, throughIndex)) {
const kind = invariance[index];
if (
kind === 'unknown' ||
(kind === 'settled-earning' && !(settled ??= earningSettled(candidate, context)))
)
return false;
const comparison = compareObjectiveValues(
objective.direction,
objective.value,
baseline[index].value,
);
if (comparison !== 0) return comparison > 0;
index++;
}
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.
*/
export function evaluateRuleCandidate(
before: State,
candidate: State | null,
context: SearchContext,
throughIndex: number,
addition = false,
baseline = activeObjectiveVector(before, context, throughIndex),
incumbentVector = objectiveVector(before, context),
onlyIfBetter = false,
): { state: State; vector?: PlanningObjectiveVector } | undefined {
if (!candidate) return undefined;
if (
onlyIfBetter
? provablyNotBetterThanIncumbent(candidate, context, incumbentVector.objectives)
: provablyWorseThanProtectedPrefix(candidate, context, throughIndex, baseline)
)
return undefined;
const state = finalizeRuleCandidate(candidate, context, before);
if (!state) return undefined;
const active: PlanningObjective[] = [];
let comparison = 0;
let incumbentComparison = 0;
for (const objective of activeObjectives(state, context)) {
const index = active.length;
active.push(objective);
if (index <= throughIndex && comparison === 0) {
comparison = compareObjectiveValues(
objective.direction,
objective.value,
baseline[index].value,
);
// A worse protected prefix cannot improve the jointly valid incumbent.
if (comparison > 0) return undefined;
}
if (incumbentComparison === 0)
incumbentComparison = compareObjectiveValues(
objective.direction,
objective.value,
incumbentVector.objectives[index + 1].value,
);
if (incumbentComparison > 0 && (comparison < 0 || index >= throughIndex))
return addition && comparison === 0 ? undefined : { state };
}
// finalizeRuleCandidate only returns states without unsatisfied obligations.
const vector = objectiveVector(state, context, active, 0);
// Preserve the best valid candidate even if the active prefix rejects it.
if (compareObjectiveLists(vector.objectives, incumbentVector.objectives) < 0)
context.retain?.(state, vector);
// shortcut: single additions cannot cross equal-value plateaus; add coordinated balance bundles when a measured configuration needs them.
if (addition && comparison === 0) return undefined;
return { state, vector };
}
export function counterfactualRuleValid(
date: string,
type: LeaveType,
ruleIds: readonly string[],
context: SearchContext,
baseline: State,
): boolean {
for (const ruleId of ruleIds) {
const rule = context.rules.find((candidate) => candidate.id === ruleId);
if (!rule) return false;
if (rule.type === 'optimization') continue;
if (rule.type === 'time_window') {
if (
!selectorMatches(rule.placeType, type) ||
compareDate(date, rule.startDate!) < 0 ||
compareDate(date, rule.endDate!) > 0
)
return false;
continue;
}
const matchesPattern = occurrences(rule, context).some((occurrence) =>
patternsFor(rule, occurrence, context).some(
(pattern) =>
pattern.includes(date) &&
pattern.every(
(candidateDate) =>
candidateDate === date ||
patternDateSatisfied(candidateDate, rule, baseline, context),
),
),
);
if (!matchesPattern || !selectorMatches(rule.placeType, type)) return false;
}
return true;
}
@@ -0,0 +1,614 @@
import { supportingCalendarBenefit } from './candidate-evaluation';
import { declaredWindowDays, occurrences, patternDateSatisfied, patternsFor } from './patterns';
import { assignDateToBalance, assignDateVariants, mandatoryRelocationDate } from './placement';
import { selectorMatches } from './search-context';
import { releasePlacement } from './state';
import {
activeObjectives,
activeObjectiveVector,
isHolidayWeekValueMaximum,
isUnplacedQuantitySum,
occupancyOnlyObjective,
} from './state-objectives';
import type {
NormalizedOptimizationRule,
NormalizedRule,
PlanningObjective,
PlanningObjectiveId,
PlanningSteps,
SearchContext,
State,
} from './types';
import {
addPlacement,
compareDate,
isAtRisk,
optimizationBalanceObservations,
optimizationObservations,
periodData,
workSequenceDates,
} from '../plan-observations';
import {
compareObjectiveLists,
compareObjectiveValues,
evaluateValidatedOptimization,
} from '../planning-objectives';
/** Optimistic reachability ignores preference values and complete-pattern validity. */
function relocationCanReachFree(
state: State,
context: SearchContext,
balanceId: string,
ruleIds: ReadonlySet<string>,
visited: ReadonlySet<string>,
failed: Set<string>,
): boolean {
const key = JSON.stringify([balanceId, [...ruleIds].sort(), [...visited].sort()]);
if (failed.has(key)) return false;
const queue = [{ balanceId, ruleIds }];
const seen = new Set<string>();
for (let index = 0; index < queue.length; index++) {
const entry = queue[index];
const identity = JSON.stringify([entry.balanceId, [...entry.ruleIds].sort()]);
if (seen.has(identity)) continue;
seen.add(identity);
const balance = state.balances.find((item) => item.id === entry.balanceId)!;
for (const date of context.workingDays) {
context.check();
if (
visited.has(date) ||
context.declaredDates.has(date) ||
date < balance.availableFrom ||
date > balance.expiryDate ||
!mandatoryRelocationDate(date, balance, entry.ruleIds, context)
)
continue;
const placement = state.placements.get(date);
if (!placement) return true;
queue.push({ balanceId: placement.balanceId, ruleIds: placement.ruleIds });
}
}
failed.add(key);
return false;
}
/** Relocate occupied dates along an augmenting path and validate only the complete addition. */
export function* relocateForAddition(
state: State,
context: SearchContext,
date: string,
balanceId: string,
ruleIds: Set<string>,
supporting: boolean,
accept: (candidate: State) => boolean,
visited = new Set<string>(),
failedReachability = new Set<string>(),
failedSearches = new Set<string>(),
): PlanningSteps<boolean> {
yield;
context.check();
if (visited.has(date) || context.declaredDates.has(date)) return false;
const existing = state.placements.get(date);
if (
existing?.balanceId === balanceId &&
existing.supporting === supporting &&
existing.ruleIds.size === ruleIds.size &&
[...existing.ruleIds].every((id) => ruleIds.has(id))
)
return false;
const key = JSON.stringify([
date,
balanceId,
[...ruleIds].sort(),
supporting,
[...visited].sort(),
state.balances.map((balance) => [balance.id, balance.remaining]),
[...state.placements.values()]
.sort((a, b) => compareDate(a.date, b.date))
.map((placement) => [
placement.date,
placement.balanceId,
[...placement.ruleIds].sort(),
placement.supporting,
]),
]);
if (failedSearches.has(key)) {
return false;
}
const assigned = assignDateToBalance(
existing ? releasePlacement(state, date) : state,
date,
balanceId,
context,
ruleIds,
);
if (!assigned) return false;
assigned.placements.get(date)!.supporting = supporting;
if (!existing) {
const accepted = accept(assigned);
if (!accepted) failedSearches.add(key);
return accepted;
}
const displaced = assigned.balances.find((balance) => balance.id === existing.balanceId)!;
const nextVisited = new Set([...visited, date]);
if (
!relocationCanReachFree(
assigned,
context,
existing.balanceId,
existing.ruleIds,
nextVisited,
failedReachability,
)
)
return false;
for (const destination of context.workingDays) {
yield;
if (destination < displaced.availableFrom || destination > displaced.expiryDate) continue;
if (!mandatoryRelocationDate(destination, displaced, existing.ruleIds, context)) continue;
if (
yield* relocateForAddition(
assigned,
context,
destination,
existing.balanceId,
existing.ruleIds,
existing.supporting,
accept,
nextVisited,
failedReachability,
failedSearches,
)
)
return true;
}
failedSearches.add(key);
return false;
}
function typedCalendarDates(context: SearchContext): Set<string> {
const typedDates = new Set<string>();
for (const rule of context.rules) {
if (rule.type === 'optimization' || rule.placeType === 'any') continue;
const dates =
rule.type === 'time_window'
? context.workingDays.filter(
(date) => rule.startDate! <= date && date <= rule.endDate!,
)
: occurrences(rule, context).flatMap((occurrence) =>
patternsFor(rule, occurrence, context).flat(),
);
for (const date of dates) typedDates.add(date);
}
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.
*/
export 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[],
ruleId: string,
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),
);
if (!missing.length) return false;
const before = optimizationObservations(state, context);
const typedDates = typedCalendarDates(context);
const failed = new Set<string>();
const rankedDonors: { date: string; objectives: PlanningObjective[] }[] = [];
for (const placement of state.placements.values()) {
yield;
context.check();
if (targetDates.includes(placement.date)) continue;
let objectives = donorObjectives.get(placement.date);
if (!objectives) {
objectives = activeObjectiveVector(releasePlacement(state, placement.date), context);
donorObjectives.set(placement.date, objectives);
}
rankedDonors.push({ date: placement.date, objectives });
}
// shortcut: recursion retains the original donor ranking; rerank when a measured bundle misses a better allocation.
rankedDonors.sort(
(a, b) => compareObjectiveLists(a.objectives, b.objectives) || compareDate(b.date, a.date),
);
const fill = function* (
index: number,
current: State,
additions: string[] = [],
): PlanningSteps<boolean> {
yield;
context.check();
const key = JSON.stringify([
index,
current.balances.map((balance) => [balance.id, balance.remaining]),
[...current.placements.values()]
.sort((a, b) => compareDate(a.date, b.date))
.map((placement) => [
placement.date,
targetDates.includes(placement.date)
? typedDates.has(placement.date)
? placement.type
: null
: placement.type,
targetDates.includes(placement.date) &&
!current.balances.find((balance) => balance.id === placement.balanceId)!.earned
? null
: placement.balanceId,
[...placement.ruleIds].sort(),
placement.supporting,
additions.includes(placement.date),
]),
]);
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) {
// No derivation: only the placement object is replaced, the key set is unchanged.
const placement = { ...current.placements.get(date)! };
current.placements.set(date, placement);
const balance = current.balances.find((item) => item.id === placement.balanceId)!;
placement.supporting = benefit && !isAtRisk(balance, context);
}
const accepted = accept(current, additions.length > 0);
if (!accepted) failed.add(key);
return accepted;
}
const date = missing[index];
for (const balance of current.balances) {
if (balance.remaining <= 0 || date < balance.availableFrom || date > balance.expiryDate)
continue;
const assigned = assignDateToBalance(
current,
date,
balance.id,
context,
new Set([ruleId]),
);
if (!assigned) continue;
if (yield* fill(index + 1, assigned, [...additions, date])) return true;
}
const donors = new Set<string>();
for (const donor of rankedDonors) {
yield;
const source = current.placements.get(donor.date);
if (!source) continue;
const balance = current.balances.find((item) => item.id === source.balanceId)!;
if (
date < balance.availableFrom ||
date > balance.expiryDate ||
!mandatoryRelocationDate(date, balance, source.ruleIds, context)
)
continue;
const without = releasePlacement(current, source.date);
const identity = JSON.stringify([
source.balanceId,
[...source.ruleIds].sort(),
source.supporting,
activeObjectiveVector(without, context),
]);
// shortcut: equivalent donor tokens share one deterministic source; expand coordinated donor choices if a measured plan needs them.
if (donors.has(identity)) continue;
donors.add(identity);
const assigned = assignDateToBalance(
without,
date,
source.balanceId,
context,
source.ruleIds,
);
if (!assigned) continue;
assigned.placements.get(date)!.supporting = source.supporting;
if (yield* fill(index + 1, assigned, additions)) return true;
}
failed.add(key);
return false;
};
return yield* fill(0, state);
}
export function* holidayWeekPlacementCandidates(
state: State,
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[]>();
for (const week of context.holidayWeeks)
yield* calendarPlacementCandidates(
state,
week.dates,
ruleId,
context,
accept,
donorObjectives,
cannotBeAccepted,
);
}
export function* timeOffPeriodPlacementCandidates(
state: State,
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++) {
const dates = context.workingDays.filter(
(date) => date > periods[index - 1].end && date < periods[index].start,
);
if (dates.length > 1)
yield* calendarPlacementCandidates(
state,
dates,
ruleId,
context,
accept,
undefined,
cannotBeAccepted,
);
}
}
/** Only the complete sequence change is compared; a partial gap fill can worsen the deficit. */
export function* workSequencePlacementCandidates(
state: State,
rule: NormalizedOptimizationRule,
context: SearchContext,
consider: (candidate: State) => boolean,
): PlanningSteps<void> {
const configuration = rule.configuration;
if (configuration.direction !== 'minimize') return;
const sequences = workSequenceDates(state, context).filter(
({ dates, internal }) =>
dates.length > 0 && (!configuration.conditions.includes('internal') || internal),
);
const bundles: string[][][] = [];
if (configuration.aggregation === 'count')
bundles.push(...sequences.map(({ dates }) => dates.map((date) => [date])));
else if (configuration.measure === 'work-sequence-deficit') {
const short = sequences.filter(({ dates }) => dates.length < configuration.thresholdDays);
if (configuration.aggregation === 'maximum') {
const shortest = Math.min(...short.map(({ dates }) => dates.length));
bundles.push(
short
.filter(({ dates }) => dates.length === shortest)
.flatMap(({ dates }) => dates.map((date) => [date])),
);
} else bundles.push(...short.map(({ dates }) => dates.map((date) => [date])));
} else if (
configuration.measure === 'work-sequence-length' &&
configuration.aggregation === 'maximum'
) {
const maximum = Math.max(0, ...sequences.map(({ dates }) => dates.length));
const tied = sequences.filter(({ dates }) => dates.length === maximum);
if (tied.length > 1) {
for (const offset of [0, 1]) {
const bundle: string[][] = [];
for (const { dates } of tied) {
const middle = Math.floor((dates.length - 1 + offset) / 2);
const centered = dates
.map((date, index) => ({ date, index }))
.sort(
(a, b) =>
Math.abs(a.index - middle) - Math.abs(b.index - middle) ||
compareDate(a.date, b.date),
);
const eligible = [
...new Set(
state.balances
.filter((balance) => balance.remaining > 0)
.map(
(balance) =>
centered.find(
({ date }) =>
balance.availableFrom <= date &&
date <= balance.expiryDate,
)?.date,
)
.filter((date): date is string => date !== undefined),
),
];
if (!eligible.length) break;
bundle.push(
eligible.sort(
(a, b) =>
centered.findIndex(({ date }) => date === a) -
centered.findIndex(({ date }) => date === b),
),
);
}
if (bundle.length === tied.length) bundles.push(bundle);
}
}
}
const before = optimizationObservations(state, context);
const available = state.balances.reduce((total, balance) => total + balance.remaining, 0);
const typedDates = typedCalendarDates(context);
const failedAssignments = new Set<string>();
function* assignBundle(
candidate: State,
slots: string[][],
dates: string[] = [],
): PlanningSteps<boolean> {
yield;
context.check();
// Equivalent rejected allocations differ only in non-earned balance provenance.
const key = JSON.stringify([
slots,
dates,
candidate.balances.map(({ id, remaining }) => [id, remaining]),
dates.map((date) => {
const placement = candidate.placements.get(date)!;
const balance = candidate.balances.find((item) => item.id === placement.balanceId)!;
return [
typedDates.has(date) ? placement.type : undefined,
balance.earned ? balance.id : undefined,
];
}),
]);
if (failedAssignments.has(key)) return false;
if (dates.length === slots.length) {
const supporting = supportingCalendarBenefit(before, candidate, context);
for (const date of dates) {
const placement = candidate.placements.get(date)!;
const balance = candidate.balances.find((item) => item.id === placement.balanceId)!;
placement.supporting = supporting && !isAtRisk(balance, context);
}
const accepted = consider(candidate);
if (!accepted) failedAssignments.add(key);
return accepted;
}
for (const date of slots[dates.length]) {
for (const next of assignDateVariants(candidate, date, 'any', rule.id, context))
if (yield* assignBundle(next, slots, [...dates, date])) return true;
}
failedAssignments.add(key);
return false;
}
// shortcut: bundles keep the first accepted allocation and nearest center per balance; extend when a measured case needs another coordinated allocation.
const examined = new Set<string>();
for (const slots of bundles) {
yield;
const key = JSON.stringify(slots);
if (slots.length <= 1 || slots.length > available || examined.has(key)) continue;
examined.add(key);
yield* assignBundle(state, slots);
}
}
/**
* 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.
*/
export 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);
addPlacement(state.placements, placements, 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;
}
@@ -0,0 +1,324 @@
import { counterfactualRuleValid } from './candidate-evaluation';
import { normalizeRequest } from './normalize';
import { declaredWindowDays, occurrences, patternsFor } from './patterns';
import {
assignDateToBalance,
finalizeEarnedState,
occurrenceSatisfied,
selectedOccurrencePattern,
} from './placement';
import { finishedPlanContext, isWorking } from './search-context';
import { cloneState, stateFromPlanningSnapshot } from './state';
import { objectiveComparison, objectiveVector } from './state-objectives';
import type {
CounterfactualAnalysis,
CounterfactualDateResult,
CounterfactualReasonCode,
InternalBalance,
LeavePlacement,
NormalizedBalance,
NormalizedCalendarRule,
PlanningObjectiveVector,
PlanningReason,
PlanningStateSnapshot,
PlanOutcome,
SearchContext,
State,
} from './types';
import { compareDate, dateRange, removePlacement } from '../plan-observations';
function counterfactualReason(
code: CounterfactualReasonCode,
message: string,
): PlanningReason & { code: CounterfactualReasonCode } {
return { code, message };
}
function counterfactualObligationsValid(
state: State,
context: SearchContext,
previous: State,
): boolean {
return context.rules
.filter(
(rule): rule is NormalizedCalendarRule => rule.enabled && rule.force === 'obligation',
)
.every((rule) => {
if (rule.type === 'time_window') {
const count = (candidate: State) =>
[...candidate.placements.values()].filter((placement) =>
placement.ruleIds.has(rule.id),
).length;
const requiredPlacements =
rule.placeDays - declaredWindowDays(rule, context).length;
return (
count(previous) !== requiredPlacements || count(state) === requiredPlacements
);
}
return occurrences(rule, context).every((occurrence) => {
const patterns = patternsFor(rule, occurrence, context);
const complete = (candidate: State) =>
occurrenceSatisfied(rule, occurrence, patterns, candidate, context);
return !complete(previous) || complete(state);
});
});
}
function stateFromPlan(
plan: PlanOutcome,
normalizedBalances: NormalizedBalance[],
horizon: { start: string; end: string },
): State {
const balances = normalizedBalances.map((balance) => ({
...balance,
remaining: balance.quantity,
}));
for (const placement of plan.placements) {
let balance = balances.find((candidate) => candidate.id === placement.balanceId);
if (!balance) {
const remaining = plan.remainingBalances.find(
(candidate) => candidate.id === placement.balanceId,
);
balance = {
id: placement.balanceId,
type: placement.type,
quantity: 0,
remaining: 0,
availableFrom: remaining?.availableFrom ?? horizon.start,
expiryDate: remaining?.expiryDate ?? horizon.end,
earned: remaining?.earned ?? true,
sourceRuleId: remaining?.sourceRuleId,
};
balances.push(balance);
}
balance.remaining = Math.max(0, balance.remaining - 1);
}
return {
balances,
placements: new Map(
plan.placements.map((placement) => [
placement.date,
{ ...placement, ruleIds: new Set(placement.ruleIds) },
]),
),
earnedActivations: [],
};
}
function counterfactualIneligibility(
date: string,
selected: LeavePlacement,
released: InternalBalance | undefined,
baseline: State,
context: SearchContext,
): ReturnType<typeof counterfactualReason> | undefined {
if (!isWorking(date, context.holidays))
return counterfactualReason('non-working', 'The date is a weekend or public holiday.');
if (context.declaredDates.has(date))
return counterfactualReason(
'declared-day',
'The date is a declared non-working day fixed by the user.',
);
if (baseline.placements.has(date))
return counterfactualReason('occupied', 'Another final placement already uses this date.');
if (!released)
return counterfactualReason(
'unavailable',
'The selected leave entitlement is unavailable.',
);
if (compareDate(released.availableFrom, date) > 0)
return counterfactualReason(
'unavailable',
'The selected entitlement is not available yet.',
);
if (compareDate(date, released.expiryDate) > 0)
return counterfactualReason(
'expired',
'The selected entitlement has expired by this date.',
);
if (released.type !== selected.type)
return counterfactualReason('type-incompatible', 'The date cannot host this leave type.');
if (!counterfactualRuleValid(date, selected.type, selected.ruleIds, context, baseline))
return counterfactualReason(
'rule-invalid',
'The date does not preserve the placement rules.',
);
return undefined;
}
interface CounterfactualScope {
selected: LeavePlacement;
context: SearchContext;
baseline: State;
comparisonState: State;
before: PlanningObjectiveVector;
removeDate: string | undefined;
reserveRules: NormalizedCalendarRule[];
reserveOccurrences: {
rule: NormalizedCalendarRule;
occurrence: string;
patterns: string[][];
}[];
}
function evaluateCounterfactualDate(
date: string,
scope: CounterfactualScope,
): CounterfactualDateResult {
const {
selected,
context,
baseline,
comparisonState,
before,
removeDate,
reserveRules,
reserveOccurrences,
} = scope;
const candidate = assignDateToBalance(
baseline,
date,
selected.balanceId,
context,
new Set(selected.ruleIds),
);
if (!candidate) {
return {
date,
status: 'ineligible',
reason: counterfactualReason(
'unavailable',
'The selected entitlement cannot be placed on this date.',
),
};
}
candidate.placements.get(date)!.supporting = selected.supporting;
// The candidate shares its activations with the baseline, so replace them rather than edit them.
if (removeDate && removeDate !== date)
candidate.earnedActivations = candidate.earnedActivations.map((activation) =>
selected.ruleIds.includes(activation.ruleId)
? {
...activation,
dates: activation.dates.map((activationDate) =>
activationDate === removeDate ? date : activationDate,
),
}
: activation,
);
const finalized = finalizeEarnedState(candidate, context);
if (!finalized) {
return {
date,
status: 'ineligible',
reason: counterfactualReason(
'unavailable',
'This date would make generated leave unavailable until its producing period ends.',
),
};
}
// The checks above cannot see a reserve, which depends on the date's whole plan: no satisfied
// occurrence may be lost, and a moved reserve-rule placement must still serve an occurrence.
const reserveBroken =
reserveOccurrences.some(
({ rule, occurrence, patterns }) =>
!occurrenceSatisfied(rule, occurrence, patterns, finalized, context),
) ||
reserveRules.some(
(rule) =>
selected.ruleIds.includes(rule.id) &&
!occurrences(rule, context).some((occurrence) =>
selectedOccurrencePattern(rule, occurrence, finalized, context)?.includes(date),
),
);
if (reserveBroken) {
return {
date,
status: 'ineligible',
reason: counterfactualReason(
'rule-invalid',
'The date does not preserve the placement rules.',
),
};
}
if (!counterfactualObligationsValid(finalized, context, comparisonState)) {
return {
date,
status: 'ineligible',
reason: counterfactualReason(
'rule-invalid',
'The date would leave an obligation unsatisfied.',
),
};
}
const after = objectiveVector(finalized, context);
const comparison = objectiveComparison(before, after);
return { date, status: 'eligible', comparison };
}
/** Analyze only the selected placement against the final-plan baseline. */
export function analyzeCounterfactualInternal(
request: unknown,
plan: PlanOutcome,
selected: LeavePlacement,
finalStateSnapshot?: PlanningStateSnapshot,
): CounterfactualAnalysis {
const normalized = normalizeRequest(
request,
plan.calculationDate ?? finalStateSnapshot?.calculationDate,
);
const horizon = normalized.horizon ?? plan.horizon;
const context = finishedPlanContext(normalized, horizon);
const reserveRules = context.rules.filter(
(rule): rule is NormalizedCalendarRule => rule.type === 'if_then' && !!rule.reserveDays,
);
const finalState: State = finalStateSnapshot
? stateFromPlanningSnapshot(finalStateSnapshot)
: stateFromPlan(plan, normalized.balances, horizon);
const comparisonState = cloneState(finalState);
// Occurrences of reserve rules the plan satisfies; a snapshot-less plan carries no activations.
const reserveOccurrences = reserveRules.flatMap((rule) =>
occurrences(rule, context).flatMap((occurrence) => {
const patterns = patternsFor(rule, occurrence, context);
return occurrenceSatisfied(rule, occurrence, patterns, comparisonState, context)
? [{ rule, occurrence, patterns }]
: [];
}),
);
const baseline = cloneState(finalState);
const removeDate = selected.date;
const removed = removeDate ? baseline.placements.get(removeDate) : undefined;
if (removeDate) {
removePlacement(finalState.placements, baseline.placements, removeDate);
}
const released = baseline.balances.find((balance) => balance.id === selected.balanceId);
if (released && removed?.balanceId === selected.balanceId) released.remaining++;
const beforeState = baseline;
const before = objectiveVector(beforeState, context);
const scope: CounterfactualScope = {
selected,
context,
baseline,
comparisonState,
before,
removeDate,
reserveRules,
reserveOccurrences,
};
const results: CounterfactualDateResult[] = [];
for (const date of dateRange(horizon.start, horizon.end)) {
const ineligible = counterfactualIneligibility(date, selected, released, baseline, context);
results.push(
ineligible
? { date, status: 'ineligible', reason: ineligible }
: evaluateCounterfactualDate(date, scope),
);
}
return {
kind: 'Counterfactual',
calculationId: '',
placement: { ...selected, ruleIds: [...selected.ruleIds] },
hypothetical: true,
baseline: before,
results,
};
}
@@ -0,0 +1,619 @@
import { normalizeRequest } from './normalize';
import {
declaredPatternDay,
declaredWindowDays,
occurrences,
patternDateSatisfied,
patternsFor,
} from './patterns';
import {
earnedPeriodBounds,
occurrenceSatisfied,
reserveRemaining,
reserveScope,
selectedOccurrencePattern,
} from './placement';
import { compareText, finishedPlanContext, reason } from './search-context';
import { cloneState, planningStateSnapshot, stateFromPlanningSnapshot } from './state';
import { objectiveComparison, objectiveVector } from './state-objectives';
import type {
ConflictExplanation,
IfThenContribution,
IfThenReservePrevention,
InternalPlacement,
InterruptionReason,
LeaveBalanceInput,
LeavePlacement,
NormalizedBalance,
NormalizedCalendarRule,
NormalizedRule,
PlacementContribution,
PlanExplanation,
PlanningArtifacts,
PlanningConflictOutcome,
PlanningMetrics,
PlanningReason,
PlanningStateSnapshot,
PlanOutcome,
PreferenceResult,
RemainingBalance,
RemainingClassification,
SearchContext,
State,
TimeOffPeriod,
TimeWindowContribution,
} from './types';
import {
compareDate,
evaluateStateOptimization,
optimizationObservations,
periodData,
removePlacement,
} from '../plan-observations';
import { OPTIMIZATION_PRESETS } from '../planning-objectives';
function qualityMetrics(
state: State,
context: SearchContext,
preferences: readonly PreferenceResult[],
): PlanningMetrics {
const periods = periodData(state, context);
const observations = optimizationObservations(state, context, periods);
const nonEmptySequences = observations.workSequences.filter((sequence) => sequence.length > 0);
return {
unplacedAtRisk: evaluateStateOptimization(
OPTIMIZATION_PRESETS.unplacedAtRisk,
state,
context,
observations,
),
holidayWeekValue: evaluateStateOptimization(
OPTIMIZATION_PRESETS.holidayWeekValue,
state,
context,
observations,
),
nonWorkingDayGain: evaluateStateOptimization(
OPTIMIZATION_PRESETS.nonWorkingDayGain,
state,
context,
observations,
),
longestWorkSequence: evaluateStateOptimization(
OPTIMIZATION_PRESETS.longestWorkSequence,
state,
context,
observations,
),
averageWorkSequence: nonEmptySequences.length
? nonEmptySequences.reduce((sum, sequence) => sum + sequence.length, 0) /
nonEmptySequences.length
: null,
averageTimeOffPeriod: periods.length
? periods.reduce((sum, period) => sum + period.duration, 0) / periods.length
: null,
longestTimeOffPeriod: periods.length
? Math.max(...periods.map((period) => period.duration))
: null,
shortSequenceDeficit: evaluateStateOptimization(
OPTIMIZATION_PRESETS.shortSequenceDeficit,
state,
context,
observations,
),
supportingPlacements: evaluateStateOptimization(
OPTIMIZATION_PRESETS.supportingPlacements,
state,
context,
observations,
),
preferenceSatisfaction: preferences.map((preference) => preference.satisfied),
};
}
function nonPlacementReason(
balance: NormalizedBalance,
state: State,
context: SearchContext,
completed: boolean,
): PlanningReason {
if (balance.expiryDate < context.horizon.start)
return reason('unavoidable-expiry', 'This balance expired before the planning horizon.');
if (balance.availableFrom >= context.horizon.end)
return reason(
'available-after-horizon',
'This balance becomes available after the last planning date.',
);
const dates = context.workingDays.filter(
(date) => date >= balance.availableFrom && date <= balance.expiryDate,
);
if (!dates.length)
return reason(
'no-working-date',
'There is no working date within both the horizon and this balance’s validity period.',
);
if (dates.every((date) => context.declaredDates.has(date) || state.placements.has(date)))
return reason(
'all-dates-occupied',
'Every working date within this balance’s validity period is already occupied in the displayed plan.',
);
if (!completed)
return reason(
'calculation-incomplete',
'The calculation stopped before completing its planning priorities.',
);
if (balance.expiryDate > context.horizon.end)
return reason(
'preserved',
'This balance expires after the horizon; the planner retained no additional placement under its planning priorities.',
);
return reason(
'active-priorities',
'The calculation retained no additional placement under the active planning rules.',
);
}
function remainingBalances(
state: State,
context: SearchContext,
completed: boolean,
): RemainingBalance[] {
return state.balances
.filter((balance) => balance.remaining > 0)
.map((balance) => {
const classification: RemainingClassification =
compareDate(balance.expiryDate, context.horizon.start) < 0
? 'unavoidable-expiry'
: compareDate(balance.expiryDate, context.horizon.end) <= 0
? 'at-risk'
: 'deferred';
return {
id: balance.id,
type: balance.type,
quantity: balance.remaining,
availableFrom: balance.availableFrom,
expiryDate: balance.expiryDate,
classification,
reason: nonPlacementReason(balance, state, context, completed),
earned: balance.earned,
sourceRuleId: balance.sourceRuleId,
};
});
}
function displayLabel(value: unknown, fallback: string): string {
return typeof value === 'string' && value.trim() ? value : fallback;
}
function timeWindowContributions(state: State, context: SearchContext): TimeWindowContribution[] {
if (!context.declaredDays.length) return [];
const { labels, identities } = context.request;
return context.rules
.filter(
(rule): rule is NormalizedCalendarRule => rule.enabled && rule.type === 'time_window',
)
.flatMap((rule) => {
const declaredDays = declaredWindowDays(rule, context);
return declaredDays.length
? [
{
ruleId: rule.id,
label: displayLabel(
labels?.[rule.id] ?? identities?.[rule.id] ?? rule.name,
rule.id,
),
requested: rule.placeDays,
declaredDays,
placementDates: [...state.placements.values()]
.filter((placement) => placement.ruleIds.has(rule.id))
.map(({ date }) => date)
.sort(compareDate),
},
]
: [];
});
}
function ifThenContributions(state: State, context: SearchContext): IfThenContribution[] {
const { labels, identities } = context.request;
return context.rules
.filter((rule): rule is NormalizedCalendarRule => rule.enabled && rule.type === 'if_then')
.flatMap((rule) =>
occurrences(rule, context).flatMap((occurrence) => {
const id = `earned:${rule.id}:${occurrence}`;
const activation = state.earnedActivations.find((item) => item.id === id);
const pattern = selectedOccurrencePattern(rule, occurrence, state, context);
if (!pattern) return [];
const declaredDays = pattern.flatMap((date) => {
const day = declaredPatternDay(date, rule.placeType, context);
return day ? [day] : [];
});
if (!declaredDays.length && !activation) return [];
const bounds = activation
? earnedPeriodBounds(state, activation, context)
: undefined;
return [
{
ruleId: rule.id,
label: displayLabel(
labels?.[rule.id] ?? identities?.[rule.id] ?? rule.name,
rule.id,
),
occurrence,
requested: rule.placeDays,
declaredDays,
placementDates: pattern.filter((date) => !context.declaredDates.has(date)),
...(activation && bounds
? {
earnedEntitlement: {
id,
type: rule.rewardType!,
quantity: rule.rewardDays!,
...bounds,
added:
bounds.availableFrom > context.request.calculationDate,
},
}
: {}),
},
];
}),
);
}
function ifThenReservePreventions(state: State, context: SearchContext): IfThenReservePrevention[] {
return context.rules
.filter(
(rule): rule is NormalizedCalendarRule =>
rule.enabled && rule.type === 'if_then' && !!rule.reserveDays,
)
.flatMap((rule) =>
occurrences(rule, context).flatMap((occurrence) => {
const patterns = patternsFor(rule, occurrence, context);
const missing = (pattern: readonly string[]) =>
pattern.filter((date) => !patternDateSatisfied(date, rule, state, context));
const entry = (remaining: number, patternInPlace: boolean) => [
{
ruleId: rule.id,
occurrence,
remaining,
required: rule.reserveDays!,
patternInPlace,
},
];
if (
!patterns.length ||
occurrenceSatisfied(rule, occurrence, patterns, state, context)
)
return [];
if (patterns.some((pattern) => !missing(pattern).length))
return entry(reserveRemaining(rule, occurrence, state, context), true);
// The pattern with the fewest days to place, among those whose dates can all take leave.
let pattern: readonly string[] | undefined;
for (const candidate of patterns)
if (
missing(candidate).every(
(date) =>
!context.declaredDates.has(date) && !state.placements.has(date),
) &&
(!pattern || missing(candidate).length < missing(pattern).length)
)
pattern = candidate;
if (!pattern) return [];
const { balanceIds } = reserveScope(rule, occurrence, context);
const funded = [...state.placements.values()].filter(
(placement) =>
balanceIds.has(placement.balanceId) && !pattern.includes(placement.date),
);
const byDate = (a: InternalPlacement, b: InternalPlacement) =>
compareDate(a.date, b.date);
// Unplaced leave first, so the figure is what the plan leaves with the pattern added; only
// then leave moved from before the pattern (the measure is unchanged), then later leave.
const sources = [
...state.balances
.filter(({ id }) => balanceIds.has(id))
.flatMap((balance) =>
Array.from({ length: Math.max(balance.remaining, 0) }, () => balance),
),
...funded.filter(({ date }) => date < pattern[0]).sort(byDate),
...funded
.filter(({ date }) => date > pattern[0])
.sort(byDate)
.reverse(),
];
const toPlace = missing(pattern);
if (sources.length < toPlace.length) return [];
// No derivation: this fresh Map is only read after the loop below finishes, so it was never observed.
const placements = new Map(state.placements);
toPlace.forEach((date, index) => {
const source = sources[index];
const moved = 'ruleIds' in source;
if (moved) placements.delete(source.date);
placements.set(date, {
date,
balanceId: moved ? source.balanceId : source.id,
type: source.type,
ruleIds: new Set(),
supporting: false,
});
});
const remaining = reserveRemaining(
rule,
occurrence,
{ ...state, placements },
context,
);
return remaining < rule.reserveDays! ? entry(remaining, false) : [];
}),
);
}
export function planExplanation(
state: State,
context: SearchContext,
placements: readonly LeavePlacement[],
periods: readonly TimeOffPeriod[],
preferences: readonly PreferenceResult[],
remaining: readonly RemainingBalance[],
metrics: PlanningMetrics,
): PlanExplanation {
const { balances, labels, identities } = context.request;
const vector = objectiveVector(state, context);
const windowContributions = timeWindowContributions(state, context);
const patternContributions = ifThenContributions(state, context);
return {
kind: 'PlanExplanation',
calculationDate: context.request.calculationDate,
...(context.declaredDays.length ? { declaredDays: context.declaredDays } : {}),
timeOffPeriods: periods,
...(windowContributions.length ? { timeWindowContributions: windowContributions } : {}),
...(patternContributions.length ? { ifThenContributions: patternContributions } : {}),
placements: placements.map((placement) => {
const balance = balances.find((candidate) => candidate.id === placement.balanceId);
const normalizedBalance = state.balances.find(
(candidate) => candidate.id === placement.balanceId,
);
const period = periods.find((candidate) =>
candidate.placementDates.includes(placement.date),
);
const sourceRules = placement.ruleIds.map((id) => {
const rule = context.rules.find((candidate) => candidate.id === id);
const label = displayLabel(labels?.[id] ?? identities?.[id] ?? rule?.name, id);
return { id, label };
});
const atRisk = normalizedBalance
? compareDate(normalizedBalance.expiryDate, context.horizon.start) >= 0 &&
compareDate(normalizedBalance.expiryDate, context.horizon.end) <= 0
: false;
const withoutPlacement = cloneState(state);
removePlacement(state.placements, withoutPlacement.placements, placement.date);
const released = withoutPlacement.balances.find(
(candidate) => candidate.id === placement.balanceId,
);
if (released) released.remaining++;
const comparison = objectiveComparison(
objectiveVector(withoutPlacement, context),
vector,
);
const contributions: PlacementContribution[] = [
{
kind: 'entitlement',
code: 'balance',
label: displayLabel(
labels?.[placement.balanceId] ??
identities?.[placement.balanceId] ??
balance?.label ??
balance?.name ??
balance?.id,
placement.balanceId,
),
},
...sourceRules.map((rule) => ({
kind: 'rule' as const,
code: 'rule',
label: rule.label,
ruleId: rule.id,
})),
];
if (atRisk)
contributions.push({
kind: 'at-risk',
code: 'at-risk',
label: 'Protects leave at risk of expiry.',
});
if (placement.supporting)
contributions.push({
kind: 'supporting',
code: 'supporting',
label: 'Supports the surrounding time-off plan.',
});
if (period)
contributions.push({
kind: 'time-off-period',
code: 'time-off-period',
label: `Contributes to the time-off period ${period.start}–${period.end}.`,
dates: period.nonWorkingDates,
});
for (const delta of comparison.delta) {
if (typeof delta.value !== 'number' || delta.value === 0) continue;
const objective = vector.objectives.find((candidate) => candidate.id === delta.id)!;
contributions.push({
kind: 'metric',
code: objective.id,
label: objective.label ?? objective.id,
value: delta.value,
});
}
const balanceSnapshot: Readonly<LeaveBalanceInput> | undefined = balance
? {
id: balance.id,
type: balance.type,
quantity: balance.quantity,
name: balance.name,
label: balance.label,
availableFrom: balance.availableFrom ?? normalizedBalance?.availableFrom,
expiryDate: balance.expiryDate,
}
: normalizedBalance
? {
id: normalizedBalance.id,
type: normalizedBalance.type,
quantity: normalizedBalance.quantity,
name: normalizedBalance.sourceRuleId
? `Earned from ${displayLabel(
labels?.[normalizedBalance.sourceRuleId],
normalizedBalance.sourceRuleId,
)}`
: undefined,
availableFrom: normalizedBalance.availableFrom,
expiryDate: normalizedBalance.expiryDate,
}
: undefined;
return {
placement: { ...placement, ruleIds: [...placement.ruleIds] },
balance: balanceSnapshot,
ruleIds: [...placement.ruleIds],
supporting: placement.supporting,
timeOffPeriod: period,
remainingBalance: remaining.find(
(candidate) => candidate.id === placement.balanceId,
),
remainingQuantity: normalizedBalance?.remaining ?? 0,
contributions,
finalMetrics: metrics,
objectiveVector: vector,
comparison,
firstDecisiveObjective: comparison.firstDecisiveObjective,
};
}),
};
}
export function makePlan(
state: State,
context: SearchContext,
preferences: PreferenceResult[],
stages: string[],
): PlanOutcome {
const periods = periodData(state, context);
const metrics = qualityMetrics(state, context, preferences);
const placements = [...state.placements.values()]
.sort((a, b) => compareDate(a.date, b.date) || compareText(a.balanceId, b.balanceId))
.map((placement) => ({
date: placement.date,
balanceId: placement.balanceId,
type: placement.type,
ruleIds: [...placement.ruleIds].sort(),
supporting: placement.supporting,
}));
const remaining = remainingBalances(state, context, stages.includes('dates'));
const windowContributions = timeWindowContributions(state, context);
const patternContributions = ifThenContributions(state, context);
const reservePreventions = ifThenReservePreventions(state, context);
const plan: PlanOutcome = {
kind: 'Plan',
calculationDate: context.request.calculationDate,
...(context.declaredDays.length ? { declaredDays: context.declaredDays } : {}),
...(windowContributions.length ? { timeWindowContributions: windowContributions } : {}),
...(patternContributions.length ? { ifThenContributions: patternContributions } : {}),
...(reservePreventions.length ? { ifThenReservePreventions: reservePreventions } : {}),
horizon: context.horizon,
placements,
timeOffPeriods: periods,
preferences,
remainingBalances: remaining,
metrics,
completedStages: [...stages],
lastCompletedStage: stages[stages.length - 1] ?? 'validation',
};
context.retain?.(state);
return plan;
}
export function ruleStage(rule: NormalizedRule): string {
return `${rule.type === 'optimization' ? 'optimization' : 'preference'}:${rule.id}`;
}
export function planningStages(context: SearchContext): string[] {
return [
'validation',
'obligations',
...context.rules
.filter((rule) => rule.enabled && rule.force === 'preference')
.map(ruleStage),
'expiry',
'dates',
];
}
export function conflictExplanation(
outcome: PlanningConflictOutcome,
context: SearchContext,
): ConflictExplanation {
const { labels } = context.request;
return {
kind: 'ConflictExplanation',
conflictingRules: outcome.conflictingRuleIds.map((id) => ({
id,
label: displayLabel(
labels?.[id] ?? context.rules.find((rule) => rule.id === id)?.name,
id,
),
})),
bottleneck: outcome.reasons[0],
};
}
/** Materialize an incumbent explanation from a delivered checkpoint without rerunning planning. */
export function explainIncompleteCheckpoint(
request: unknown,
incumbent: PlanOutcome,
checkpoint: PlanningStateSnapshot,
interruption: InterruptionReason,
): PlanningArtifacts {
try {
const normalized = normalizeRequest(
request,
incumbent.calculationDate ?? checkpoint.calculationDate,
);
if (normalized.reasons.length || !normalized.horizon)
throw new Error('The checkpoint explanation request is invalid.');
const horizon = normalized.horizon;
const context = finishedPlanContext(normalized, horizon);
const state = stateFromPlanningSnapshot(checkpoint);
const explanation = planExplanation(
state,
context,
incumbent.placements,
incumbent.timeOffPeriods,
incumbent.preferences,
incumbent.remainingBalances,
incumbent.metrics,
);
const uncompletedStages = planningStages(context).filter(
(stage) => !incumbent.completedStages.includes(stage),
);
return {
explanation:
uncompletedStages.length === 0
? explanation
: {
...explanation,
incomplete: {
kind: 'IncompleteExplanation',
reason: interruption,
completedStages: [...incumbent.completedStages],
uncompletedStages,
},
},
finalState: planningStateSnapshot(state, context),
};
} catch (error) {
return {
explanationError: reason(
'explanation-error',
error instanceof Error ? error.message : String(error),
),
};
}
}
@@ -0,0 +1,421 @@
import { reason } from './search-context';
import type {
LeaveBalanceInput,
LeaveSelector,
LeaveType,
NormalizedBalance,
NormalizedCalendarRule,
NormalizedRule,
PlacementMode,
PlanningReason,
RuleForce,
ValidatedRequest,
} from './types';
import { type DeclaredNonWorkingDay, parseDeclaredDays } from '../declared-non-working-days';
import { compareDate } from '../plan-observations';
import { addPlanningYears, isPlanningDate, planningDateInParis } from '../planning-date';
import { validateOptimizationConfiguration } from '../planning-objectives';
const VALID_TYPES = new Set<LeaveType>(['cp', 'rtt', 'other']);
const VALID_SELECTORS = new Set<LeaveSelector>(['cp', 'rtt', 'other', 'any']);
const VALID_MODES = new Set<PlacementMode>(['before', 'after', 'around', 'auto']);
function dateKey(value: unknown): string | null {
if (typeof value === 'string') {
// date-holidays returns date-only strings with a time suffix. Treat the
// leading calendar date as data, rather than letting the host timezone
// shift it across a midnight boundary.
const dateOnly = value.match(/^(\d{4}-\d{2}-\d{2})(?:$|\s|T)/)?.[1];
if (dateOnly) return isPlanningDate(dateOnly) ? dateOnly : null;
const parsed = new Date(value);
return Number.isNaN(parsed.getTime()) ? null : planningDateInParis(parsed);
}
return null;
}
function recordValue(value: unknown): Record<string, unknown> | undefined {
return typeof value === 'object' && value !== null
? (value as Record<string, unknown>)
: undefined;
}
// A present value that is not text still hides the fallbacks of a label, as a blank one does.
function textRecord(value: unknown): Readonly<Record<string, string>> | undefined {
const record = recordValue(value);
if (!record) return undefined;
return Object.fromEntries(
Object.entries(record).flatMap(([key, item]) =>
item === undefined || item === null
? []
: [[key, typeof item === 'string' ? item : '']],
),
);
}
function defaultHorizon(start: string): { start: string; end: string } {
return { start, end: addPlanningYears(start, 1) };
}
function normalizeType(value: unknown): LeaveType | null {
const normalized = String(value ?? '').toLowerCase();
return VALID_TYPES.has(normalized as LeaveType) ? (normalized as LeaveType) : null;
}
function normalizeSelector(value: unknown): LeaveSelector | null {
const normalized = String(value ?? '').toLowerCase();
return VALID_SELECTORS.has(normalized as LeaveSelector) ? (normalized as LeaveSelector) : null;
}
function normalizeForce(value: unknown): RuleForce | null {
if (value === undefined || value === '') return 'preference';
const normalized = String(value).toLowerCase();
if (normalized === 'obligation' || normalized === 'preference') return normalized;
return null;
}
function normalizeRuleType(value: unknown): NormalizedRule['type'] | null {
const normalized = String(value ?? '').toLowerCase();
return normalized === 'time_window' || normalized === 'if_then' || normalized === 'optimization'
? normalized
: null;
}
function normalizeMode(value: unknown): PlacementMode | null {
const normalized = String(value ?? '').toLowerCase();
return VALID_MODES.has(normalized as PlacementMode) ? (normalized as PlacementMode) : null;
}
function asInteger(value: unknown): number | null {
return typeof value === 'number' && Number.isInteger(value) ? value : null;
}
function normalizeBalances(
rawInput: unknown,
horizon: { start: string; end: string },
): {
balances: NormalizedBalance[];
submitted: LeaveBalanceInput[];
reasons: PlanningReason[];
} {
const reasons: PlanningReason[] = [];
if (!Array.isArray(rawInput)) {
return {
balances: [],
submitted: [],
reasons: [reason('balances', 'Leave balances must be an array.')],
};
}
const raw: unknown[] = rawInput;
const ids = new Set<string>();
const balances: NormalizedBalance[] = [];
const submitted: LeaveBalanceInput[] = [];
for (const input of raw) {
const value = recordValue(input);
const id = typeof value?.['id'] === 'string' ? value['id'] : '';
const rawType = value?.['type'];
const type = normalizeType(rawType);
const quantity = asInteger(value?.['quantity']);
const rawAvailableFrom = value?.['availableFrom'];
const availableFrom = dateKey(rawAvailableFrom) ?? horizon.start;
const rawExpiryDate = value?.['expiryDate'];
const expiryDate = dateKey(rawExpiryDate);
if (!id) reasons.push(reason('balance-id', 'Each leave balance needs a stable identity.'));
else if (ids.has(id))
reasons.push(reason('duplicate-balance-id', `Leave balance id "${id}" is duplicated.`));
else ids.add(id);
if (!type)
reasons.push(
reason('balance-type', `Leave balance "${id}" has an invalid leave type.`),
);
if (quantity === null || quantity < 0) {
reasons.push(
reason(
'balance-quantity',
`Leave balance "${id}" needs a non-negative integer quantity.`,
),
);
}
if (!expiryDate)
reasons.push(
reason('balance-expiry', `Leave balance "${id}" needs a valid expiry date.`),
);
if (rawAvailableFrom !== undefined && !dateKey(rawAvailableFrom))
reasons.push(
reason(
'balance-availability',
`Leave balance "${id}" needs a valid availability date.`,
),
);
// A legacy balance without availability is anchored at the horizon start.
// If it already expired before that horizon, keep it reportable as
// unavoidable expiry instead of turning migration into invalid input.
if (
expiryDate &&
compareDate(availableFrom, expiryDate) > 0 &&
rawAvailableFrom !== undefined
) {
reasons.push(
reason(
'balance-dates',
`Leave balance "${id}" must be available on or before expiry.`,
),
);
}
if (type && quantity !== null && quantity >= 0 && expiryDate) {
balances.push({
id,
type,
quantity,
availableFrom,
expiryDate,
earned: false,
});
const name = value?.['name'];
const label = value?.['label'];
// The submitted balance as an explanation repeats it; a field that is not text is left out.
submitted.push({
id,
type: typeof rawType === 'string' ? rawType : type,
quantity,
availableFrom: typeof rawAvailableFrom === 'string' ? rawAvailableFrom : undefined,
expiryDate: typeof rawExpiryDate === 'string' ? rawExpiryDate : expiryDate,
name: typeof name === 'string' ? name : undefined,
label: typeof label === 'string' ? label : undefined,
});
}
}
return { balances, submitted, reasons };
}
function normalizeIfThenRule(
value: Record<string, unknown> | undefined,
id: string,
base: Omit<NormalizedCalendarRule, 'type'>,
placeType: LeaveSelector | null,
reasons: PlanningReason[],
): NormalizedCalendarRule | undefined {
const dayOfWeek = asInteger(value?.['dayOfWeek']);
const mode = normalizeMode(value?.['placement']);
const rewardDays = asInteger(value?.['rewardDays']);
const rawRewardType = value?.['rewardType'];
const rewardType = normalizeType(rawRewardType);
const reserveDays = value?.['reserveDays'] === undefined ? 0 : asInteger(value['reserveDays']);
if (reserveDays === null || reserveDays < 0)
reasons.push(
reason(
'rule-reserve',
`IF_THEN rule "${id}" needs a non-negative whole number of reserved days.`,
),
);
if (dayOfWeek === null || dayOfWeek < 0 || dayOfWeek > 6) {
reasons.push(reason('rule-weekday', `IF_THEN rule "${id}" needs a weekday from 0 to 6.`));
}
if (!mode)
reasons.push(
reason('rule-mode', `IF_THEN rule "${id}" has an unsupported placement mode.`),
);
if (rewardDays === null || rewardDays < 0) {
reasons.push(
reason('earned-quantity', `IF_THEN rule "${id}" needs a non-negative earned quantity.`),
);
}
if (!rewardType && ((rewardDays ?? 0) > 0 || rawRewardType !== undefined)) {
reasons.push(
reason(
'earned-type',
`IF_THEN rule "${id}" needs CP, RTT, or Other as its earned type.`,
),
);
}
if (
placeType &&
mode &&
dayOfWeek !== null &&
rewardDays !== null &&
(rewardDays === 0 ? rawRewardType === undefined || rewardType : rewardType)
) {
return {
...base,
type: 'if_then',
dayOfWeek,
placement: mode,
rewardDays,
rewardType: rewardType ?? undefined,
reserveDays: reserveDays ?? 0,
};
}
return undefined;
}
export function normalizeRules(rawInput: unknown): {
rules: NormalizedRule[];
reasons: PlanningReason[];
} {
const reasons: PlanningReason[] = [];
if (!Array.isArray(rawInput)) {
return { rules: [], reasons: [reason('rules', 'Planning rules must be an array.')] };
}
const raw: unknown[] = rawInput;
const ids = new Set<string>();
const rules: NormalizedRule[] = [];
for (const input of raw) {
const value = recordValue(input);
if (value?.['enabled'] === false) continue;
const id = typeof value?.['id'] === 'string' ? value['id'] : '';
const type = normalizeRuleType(value?.['type']);
const forceValue = normalizeForce(value?.['force']);
const force = forceValue ?? 'preference';
if (!id) reasons.push(reason('rule-id', 'Each planning rule needs a stable identity.'));
else if (ids.has(id))
reasons.push(reason('duplicate-rule-id', `Planning rule id "${id}" is duplicated.`));
else ids.add(id);
if (!forceValue)
reasons.push(reason('rule-force', `Planning rule "${id}" has an invalid force.`));
if (!type) {
reasons.push(reason('rule-type', `Planning rule "${id}" has an unsupported type.`));
continue;
}
if (type === 'optimization') {
const validated = validateOptimizationConfiguration(value?.['configuration']);
if (forceValue !== 'preference')
reasons.push(
reason('rule-force', 'Optimization rules support preference mode only.', [id]),
);
if (!validated.valid) {
reasons.push(reason(validated.code, validated.message, [id]));
continue;
}
rules.push({
id,
name: typeof value?.['name'] === 'string' ? value['name'] : id,
type,
enabled: true,
force: 'preference',
configuration: structuredClone(validated.configuration),
});
continue;
}
const placeDays = asInteger(value?.['placeDays']);
const placeType = normalizeSelector(value?.['placeType']);
if (placeDays === null || placeDays < 0) {
reasons.push(
reason(
'rule-quantity',
`Planning rule "${id}" needs a non-negative integer quantity.`,
),
);
continue;
}
if (!placeType)
reasons.push(
reason('rule-selector', `Planning rule "${id}" has an invalid leave selector.`),
);
const base = {
id,
name: typeof value?.['name'] === 'string' ? value['name'] : id,
type,
enabled: value?.['enabled'] !== false,
force,
placeDays,
placeType: placeType ?? 'any',
};
if (type === 'time_window') {
const startDate = dateKey(value?.['startDate']);
const endDate = dateKey(value?.['endDate']);
if (!startDate || !endDate || compareDate(startDate, endDate) > 0) {
reasons.push(
reason(
'rule-window',
`TIME_WINDOW rule "${id}" needs an inclusive, ordered date window.`,
),
);
continue;
}
rules.push({ ...base, startDate, endDate, type: 'time_window' });
continue;
}
const rule = normalizeIfThenRule(value, id, base, placeType, reasons);
if (rule) rules.push(rule);
}
return { rules, reasons };
}
/** Validates an unverified request once, at an entry point; the planner reads only what this returns. */
export function normalizeRequest(
value: unknown,
calculationDate?: string,
): {
request: ValidatedRequest;
declaredDays: DeclaredNonWorkingDay[];
horizon?: { start: string; end: string };
balances: NormalizedBalance[];
rules: NormalizedRule[];
reasons: PlanningReason[];
} {
const source = recordValue(value) ?? {};
const today = planningDateInParis(new Date());
const submittedDate = source['calculationDate'];
const date = calculationDate ?? (isPlanningDate(submittedDate) ? submittedDate : today);
const rawHorizon = recordValue(source['horizon']);
// A calculation date given by an entry point is not checked; the horizon falls back to today.
const fallbackHorizon = defaultHorizon(isPlanningDate(date) ? date : today);
const start = dateKey(rawHorizon?.['start']) ?? fallbackHorizon.start;
const end = dateKey(rawHorizon?.['end']) ?? fallbackHorizon.end;
const reasons: PlanningReason[] = [];
if (!rawHorizon) {
reasons.push(reason('horizon', 'The planning horizon is required.'));
} else if (!dateKey(rawHorizon['start'])) {
reasons.push(
reason('horizon-start', 'The planning horizon start must be a valid calendar date.'),
);
}
if (rawHorizon && !dateKey(rawHorizon['end'])) {
reasons.push(
reason('horizon-end', 'The planning horizon end must be a valid calendar date.'),
);
}
if (rawHorizon && compareDate(start, end) >= 0) {
reasons.push(reason('horizon-order', 'The planning horizon must have start before end.'));
}
const configuredDeadline = source['deadlineMs'];
if (
configuredDeadline !== undefined &&
(typeof configuredDeadline !== 'number' ||
!Number.isFinite(configuredDeadline) ||
configuredDeadline < 0)
) {
reasons.push(
reason('deadline', 'The planning deadline must be a finite non-negative number.'),
);
}
let declaredDays: DeclaredNonWorkingDay[] = [];
const rawDeclaredDays = source['declaredDays'];
try {
declaredDays = parseDeclaredDays(rawDeclaredDays === undefined ? [] : rawDeclaredDays);
} catch (error) {
reasons.push(
reason('declared-days', error instanceof Error ? error.message : String(error)),
);
}
const balanceResult = normalizeBalances(source['balances'], { start, end });
const ruleResult = normalizeRules(source['rules']);
reasons.push(...balanceResult.reasons, ...ruleResult.reasons);
return {
request: {
calculationDate: date,
balances: balanceResult.submitted,
identities: textRecord(source['identities']),
labels: textRecord(source['labels']),
deadlineMs: typeof configuredDeadline === 'number' ? configuredDeadline : undefined,
},
horizon: reasons.some((item) => item.code === 'horizon' || item.code.startsWith('horizon-'))
? undefined
: { start, end },
balances: balanceResult.balances,
declaredDays,
rules: ruleResult.rules,
reasons,
};
}
@@ -0,0 +1,430 @@
import { finalizeRuleCandidate } from './candidate-evaluation';
import { declaredPatternDay, occurrences } from './patterns';
import {
addEarnedBalance,
assignDatesVariants,
assignDateVariants,
earnedPeriodBounds,
finalizeEarnedState,
reserveHolds,
reserveRemaining,
} from './placement';
import { DeadlineReached, OBLIGATION_SOLUTION_LIMIT, reason } from './search-context';
import type {
NormalizedCalendarRule,
NormalizedRule,
PlanningConflictOutcome,
PlanningSteps,
Requirement,
SearchContext,
State,
} from './types';
interface ObligationDateChoice {
requirements: Requirement[];
index: number;
solutions: State[] | undefined;
solutionLimit: number;
context: SearchContext;
requirement: Requirement;
candidates: string[];
needed: number;
}
function extensionRequirementIndexes(
requirements: Requirement[],
index: number,
state: State,
context: SearchContext,
chooseOrder: boolean,
): number[] {
// Extending a reported generator requires filling its first working gap.
// Only move requirements that can fill that gap ahead of a funded consumer.
const extensionDates =
chooseOrder && context.horizon.end > context.request.calculationDate
? state.earnedActivations.map(
(activation) =>
state.balances.find((balance) => balance.id === activation.id)
?.availableFrom ??
earnedPeriodBounds(state, activation, context).availableFrom,
)
: [];
return extensionDates.length
? requirements
.slice(index + 1)
.flatMap((candidate, offset) =>
(
candidate.patterns
? candidate.patterns.some((pattern) =>
pattern.some((date) => extensionDates.includes(date)),
)
: candidate.requiredPlacements > 0 &&
candidate.candidates?.some((date) => extensionDates.includes(date))
)
? [index + offset + 1]
: [],
)
: [];
}
function* chooseObligationDates(
fixed: ObligationDateChoice,
position: number,
picked: string[],
current: State,
): PlanningSteps<State | null> {
const {
requirements,
index,
solutions,
solutionLimit,
context,
requirement,
candidates,
needed,
} = fixed;
yield;
context.check();
if (picked.length === needed) {
const finalized = finalizeEarnedState(current, context);
if (!finalized) return null;
const complete = yield* satisfyObligations(
requirements,
finalized,
context,
index + 1,
solutions,
solutionLimit,
);
if (complete && !solutions) return complete;
return null;
}
if (candidates.length - position < needed - picked.length) {
return null;
}
for (let i = position; i < candidates.length; i++) {
yield;
for (const next of assignDateVariants(
current,
candidates[i],
requirement.rule.placeType,
requirement.rule.id,
context,
)) {
yield;
const complete = yield* chooseObligationDates(
fixed,
i + 1,
[...picked, candidates[i]],
next,
);
if (complete && !solutions) return complete;
if (solutions && solutionLimit > 0 && solutions.length >= solutionLimit) {
return null;
}
}
}
return null;
}
export function* satisfyObligations(
requirements: Requirement[],
state: State,
context: SearchContext,
index = 0,
solutions?: State[],
solutionLimit = OBLIGATION_SOLUTION_LIMIT,
chooseOrder = true,
): PlanningSteps<State | null> {
yield;
context.check();
if (index >= requirements.length) {
const finalized = finalizeRuleCandidate(state, context, state);
if (!finalized) return null;
if (solutions) solutions.push(finalized);
context.retain?.(finalized);
return solutions ? null : finalized;
}
const requirement = requirements[index];
const extensions = extensionRequirementIndexes(
requirements,
index,
state,
context,
chooseOrder,
);
if (extensions.length) {
for (const next of [index, ...extensions]) {
yield;
const ordered =
next === index
? requirements
: [
...requirements.slice(0, index),
requirements[next],
...requirements.slice(index, next),
...requirements.slice(next + 1),
];
const complete = yield* satisfyObligations(
ordered,
state,
context,
index,
solutions,
solutionLimit,
false,
);
if (complete && !solutions) return complete;
if (solutions && solutionLimit > 0 && solutions.length >= solutionLimit) break;
}
return null;
}
if (requirement.optional) {
const complete = yield* satisfyObligations(
requirements,
state,
context,
index + 1,
solutions,
solutionLimit,
);
if (complete && !solutions) return complete;
}
if (requirement.patterns) {
for (const pattern of requirement.patterns) {
yield;
for (const assigned of yield* assignDatesVariants(
state,
pattern,
requirement.rule,
context,
)) {
yield;
// Obligations only add placements, and each one can only lower the remaining reserve.
if (!reserveHolds(requirement.rule, requirement.occurrenceDate!, assigned, context))
continue;
const candidate = finalizeEarnedState(
addEarnedBalance(
assigned,
requirement.rule,
requirement.occurrenceDate!,
pattern,
context,
),
context,
);
if (!candidate) continue;
const complete = yield* satisfyObligations(
requirements,
candidate,
context,
index + 1,
solutions,
solutionLimit,
);
if (complete && !solutions) return complete;
if (solutions && solutionLimit > 0 && solutions.length >= solutionLimit) {
return null;
}
}
}
return null;
}
const candidates = requirement.candidates ?? [];
const needed = requirement.requiredPlacements;
return yield* chooseObligationDates(
{ requirements, index, solutions, solutionLimit, context, requirement, candidates, needed },
0,
[],
state,
);
}
export function* obligationConflict(
requirements: readonly Requirement[],
context: SearchContext,
jointReserve?: PlanningSteps<PlanningConflictOutcome | undefined>,
): PlanningSteps<PlanningConflictOutcome> {
const ruleIds = [...new Set(requirements.map((requirement) => requirement.rule.id))];
const generatedTypes = new Set(
context.rules
.filter(
(rule): rule is NormalizedCalendarRule =>
rule.enabled &&
rule.type === 'if_then' &&
(rule.rewardDays ?? 0) > 0 &&
!!rule.rewardType,
)
.map((rule) => rule.rewardType!),
);
let generatedCapacityBottleneck = false;
for (const requirement of requirements) {
if (requirement.rule.placeType === 'any') continue;
const required = requirement.requiredPlacements;
const capacity = context.initialBalances
.filter((balance) => balance.type === requirement.rule.placeType)
.reduce((sum, balance) => sum + balance.quantity, 0);
if (capacity < required) {
if (!generatedTypes.has(requirement.rule.placeType))
return {
kind: 'PlanningConflict',
conflictingRuleIds: ruleIds,
reasons: [
reason(
'typed-capacity',
`The obligations require more ${requirement.rule.placeType.toUpperCase()} leave than is available.`,
ruleIds,
),
],
};
generatedCapacityBottleneck = true;
}
}
if (
requirements.some(
(requirement) =>
(requirement.patterns !== undefined && requirement.patterns.length === 0) ||
(requirement.candidates !== undefined &&
requirement.requiredPlacements > 0 &&
requirement.candidates.length === 0),
)
)
return {
kind: 'PlanningConflict',
conflictingRuleIds: ruleIds,
reasons: [
reason(
'horizon-bottleneck',
'The planning horizon contains no eligible dates for at least one obligation.',
ruleIds,
),
],
};
let reserveConflict = obligationReserveConflict(requirements, context);
if (!reserveConflict && jointReserve)
try {
reserveConflict = yield* jointReserve;
} catch (error) {
// The conflict is already proven: out of time to name a reserve, report it as before.
if (!(error instanceof DeadlineReached)) throw error;
}
if (reserveConflict) return reserveConflict;
if (generatedCapacityBottleneck)
return {
kind: 'PlanningConflict',
conflictingRuleIds: ruleIds,
reasons: [
reason(
'earned-entitlement-bottleneck',
'An earned leave entitlement is not available early enough to satisfy every obligation.',
ruleIds,
),
],
};
return {
kind: 'PlanningConflict',
conflictingRuleIds: ruleIds,
reasons: [
reason(
'joint-date-conflict',
'The obligation date patterns cannot be satisfied together.',
ruleIds,
),
],
};
}
/**
* The first obligation occurrence whose reserve fails with any one of its patterns placed alone on
* top of the declared days; placements only lower the reserve, so no plan can satisfy it.
*/
function obligationReserveConflict(
requirements: readonly Requirement[],
context: SearchContext,
): PlanningConflictOutcome | undefined {
const empty: State = {
balances: context.initialBalances.map((balance) => ({
...balance,
remaining: balance.quantity,
})),
placements: new Map(),
earnedActivations: [],
};
for (const { rule, occurrenceDate: occurrence, patterns, requiredPlacements } of requirements) {
if (!rule.reserveDays || !occurrence || !patterns?.length) continue;
const open = (pattern: string[]) =>
pattern.filter((date) => !declaredPatternDay(date, rule.placeType, context));
const remainingWith = (pattern: string[]) => {
let state = empty;
for (const date of open(pattern))
state =
assignDateVariants(state, date, rule.placeType, rule.id, context)[0] ?? state;
return reserveRemaining(rule, occurrence, state, context);
};
if (patterns.some((pattern) => remainingWith(pattern) >= rule.reserveDays!)) continue;
return reserveConflictOutcome(
rule,
occurrence,
remainingWith(patterns.find((pattern) => open(pattern).length === requiredPlacements)!),
);
}
return undefined;
}
/**
* Obligations that fail only together because of their reserves: search them once more with the
* obligation reserves at zero, stopping at the first solution. A solution keeping every reserve
* would have been found with them, so this one breaks one; report the first, in rule priority then
* occurrence order. Undefined when the obligations fail even without their reserves.
*/
export function* jointReserveConflict(
requirements: readonly Requirement[],
state: State,
context: SearchContext,
): PlanningSteps<PlanningConflictOutcome | undefined> {
const reserved = (rule: NormalizedRule): rule is NormalizedCalendarRule =>
rule.type === 'if_then' && rule.force === 'obligation' && !!rule.reserveDays;
const rules = context.rules.map((rule) =>
reserved(rule) ? { ...rule, reserveDays: 0 } : rule,
);
// Every cache and memo is keyed on the context, so a context of its own inherits no verdict
// reached with the reserves; it keeps the deadline and retains no incumbent.
const relaxed: SearchContext = { ...context, rules, retain: undefined };
const solution = yield* satisfyObligations(
requirements.map((requirement) => ({
...requirement,
rule: rules[context.rules.indexOf(requirement.rule)] as NormalizedCalendarRule,
})),
state,
relaxed,
);
if (!solution) return undefined;
for (const rule of context.rules.filter(reserved))
for (const occurrence of occurrences(rule, context)) {
const remaining = reserveRemaining(rule, occurrence, solution, context);
if (remaining < rule.reserveDays!)
return reserveConflictOutcome(rule, occurrence, remaining);
}
return undefined;
}
function reserveConflictOutcome(
rule: NormalizedCalendarRule,
occurrence: string,
remaining: number,
): PlanningConflictOutcome {
return {
kind: 'PlanningConflict',
conflictingRuleIds: [rule.id],
reasons: [
{
...reason(
'if-then-reserve',
`IF_THEN rule "${rule.name}" needs a reserve of ${rule.reserveDays} ${rule.placeType.toUpperCase()} days on ${occurrence}, but only ${remaining} would remain.`,
[rule.id],
),
reserve: { occurrence, remaining, required: rule.reserveDays! },
},
],
};
}
@@ -0,0 +1,500 @@
import {
evaluateRuleCandidate,
reconcileOptimizationProvenance,
supportingCalendarBenefit,
} from './candidate-evaluation';
import {
bundleCannotBeAccepted,
holidayWeekPlacementCandidates,
relocateForAddition,
relocationMayImprovePrefix,
timeOffPeriodPlacementCandidates,
workSequencePlacementCandidates,
} from './candidate-generation';
import { assignDateToBalance } from './placement';
import { isWorking, selectorMatches } from './search-context';
import { releasePlacement } from './state';
import {
activeObjectiveVector,
bestObjectiveValue,
isHolidayWeekValueMaximum,
isUnplacedQuantitySum,
objectiveVector,
preferenceStateKey,
tieBreakObjectives,
} from './state-objectives';
import type {
NormalizedCalendarRule,
NormalizedRule,
PlanningObjective,
PlanningObjectiveVector,
PlanningSteps,
SearchContext,
State,
} from './types';
import { addDays, isAtRisk, optimizationObservations } from '../plan-observations';
import { compareObjectiveLists, type OptimizationObservations } from '../planning-objectives';
interface RulePlacementSearch {
context: SearchContext;
throughIndex: number;
allowAdd: boolean;
rule?: NormalizedRule;
addingBalanceQuantity: boolean;
equivalentAdditionFunding: boolean;
fundingWindows: NormalizedCalendarRule[];
preferencePrefix: NormalizedRule[];
prefixBestValues: (number | undefined)[];
prefixBounds: (number | undefined)[];
dateInvariantObjectives: boolean;
}
/** `best`, `bestVector` and `beforeCalendar` change during the round: read them through the object. */
interface RulePlacementRound {
result: State;
active: PlanningObjective[];
baseline: PlanningObjective[];
beforeVector: PlanningObjectiveVector;
compareEquivalentFunding: boolean;
beforeCalendar: OptimizationObservations | undefined;
best: State;
bestVector: PlanningObjectiveVector;
consider: (candidate: State | null, addition?: boolean, onlyIfBetter?: boolean) => boolean;
}
function rulePlacementSearch(
context: SearchContext,
throughIndex: number,
allowAdd: boolean,
rule?: NormalizedRule,
): RulePlacementSearch {
const addingBalanceQuantity = allowAdd && rule !== undefined && isUnplacedQuantitySum(rule);
const equivalentAdditionFunding =
addingBalanceQuantity &&
throughIndex === 0 &&
!context.rules.some((item) => item.enabled && item.type === 'if_then') &&
context.rules.every(
(item) =>
!item.enabled ||
item.type !== 'optimization' ||
item.configuration.elements !== 'leave-balances' ||
item.configuration.aggregation !== 'maximum',
);
const fundingWindows = context.rules.filter(
(item): item is NormalizedCalendarRule => item.enabled && item.type === 'time_window',
);
const preferencePrefix = context.rules
.filter((item) => item.enabled && item.force === 'preference')
.slice(0, throughIndex + 1);
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)
)
? prefixBestValues[index]
: undefined,
);
const dateInvariantObjectives = context.rules
.filter((item) => item.force === 'preference')
.every(
(item) =>
item.type === 'optimization' &&
(item.configuration!.elements === 'leave-balances' ||
item.configuration!.elements === 'leave-placements'),
);
return {
context,
throughIndex,
allowAdd,
rule,
addingBalanceQuantity,
equivalentAdditionFunding,
fundingWindows,
preferencePrefix,
prefixBestValues,
prefixBounds,
dateInvariantObjectives,
};
}
function moveDestinations(result: State, context: SearchContext): readonly string[] {
// shortcut: loaded plans sample flexible move destinations, upgrade to interval search when a measured case misses a better plan.
return result.placements.size <= 24
? context.workingDays
: context.workingDays.filter(
(date, index) =>
!isWorking(addDays(date, -1), context.holidays) ||
!isWorking(addDays(date, 1), context.holidays) ||
context.declaredDates.has(addDays(date, -1)) ||
context.declaredDates.has(addDays(date, 1)) ||
index % 7 === 0 ||
context.rules.some(
(item) =>
item.type === 'time_window' &&
date >= item.startDate! &&
date <= item.endDate!,
),
);
}
function* rulePlacementBundles(
search: RulePlacementSearch,
round: RulePlacementRound,
): PlanningSteps<void> {
const { context, allowAdd, rule, preferencePrefix } = search;
const { result, baseline, consider } = round;
if (
allowAdd &&
rule?.type === 'optimization' &&
rule.configuration.elements === 'work-sequences'
)
yield* workSequencePlacementCandidates(result, rule, context, (candidate) =>
consider(candidate, true),
);
if (
allowAdd &&
rule?.type === 'optimization' &&
rule.configuration.elements === 'public-holiday-weeks' &&
rule.configuration.conditions.includes('complete') &&
rule.configuration.direction === 'maximize'
)
yield* holidayWeekPlacementCandidates(result, rule.id, context, consider, (current, open) =>
bundleCannotBeAccepted(current, open, preferencePrefix, baseline, context),
);
if (
allowAdd &&
rule?.type === 'optimization' &&
rule.configuration.elements === 'time-off-periods' &&
((rule.configuration.aggregation === 'maximum' &&
rule.configuration.direction === 'maximize') ||
(rule.configuration.aggregation === 'count' &&
rule.configuration.direction === 'minimize'))
)
yield* timeOffPeriodPlacementCandidates(
result,
rule.id,
context,
consider,
(current, open) =>
bundleCannotBeAccepted(current, open, preferencePrefix, baseline, context),
);
}
function* genericPlacementScan(
search: RulePlacementSearch,
round: RulePlacementRound,
dates: readonly string[],
moveDates: readonly string[],
): PlanningSteps<void> {
const {
context,
allowAdd,
rule,
addingBalanceQuantity,
fundingWindows,
dateInvariantObjectives,
} = search;
const { result, beforeVector, compareEquivalentFunding, consider } = round;
for (const date of dates) {
yield;
context.check();
if (context.declaredDates.has(date)) continue;
const existing = result.placements.get(date);
if (!existing && allowAdd) {
if (rule?.type === 'time_window' && (date < rule.startDate! || date > rule.endDate!))
continue;
const evaluatedFunding = new Set<string>();
for (const balance of result.balances) {
yield;
if (rule?.type === 'time_window' && !selectorMatches(rule.placeType, balance.type))
continue;
if (
balance.remaining <= 0 ||
balance.availableFrom > date ||
balance.expiryDate < date
)
continue;
// Complete single additions with equal expiry/window scores cannot beat the
// first evaluated funder. Recursive bundles still need every funding choice.
const fundingKey =
compareEquivalentFunding && isAtRisk(balance, context)
? `${balance.expiryDate}:${fundingWindows
.map((window) =>
Number(
date >= window.startDate! &&
date <= window.endDate! &&
selectorMatches(window.placeType, balance.type),
),
)
.join('')}`
: undefined;
if (fundingKey !== undefined && evaluatedFunding.has(fundingKey)) {
continue;
}
const assigned = assignDateToBalance(
result,
date,
balance.id,
context,
rule ? new Set([rule.id]) : new Set(),
);
if (assigned && rule?.type === 'optimization' && !isAtRisk(balance, context)) {
round.beforeCalendar ??= optimizationObservations(result, context);
assigned.placements.get(date)!.supporting = supportingCalendarBenefit(
round.beforeCalendar,
assigned,
context,
);
}
const evaluated = consider(assigned, true);
if (evaluated && fundingKey !== undefined) evaluatedFunding.add(fundingKey);
}
}
if (!existing || (addingBalanceQuantity && round.best !== result)) continue;
const without = releasePlacement(result, date);
// 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 (
balance.id === existing.balanceId ||
balance.remaining <= 0 ||
balance.availableFrom > date ||
balance.expiryDate < date
)
continue;
const reassigned = assignDateToBalance(
without,
date,
balance.id,
context,
existing.ruleIds,
);
if (reassigned)
reassigned.placements.get(date)!.supporting =
existing.supporting && !isAtRisk(balance, context);
consider(reassigned, false, true);
}
for (const destination of moveDates) {
yield;
context.check();
if (destination === date || context.declaredDates.has(destination)) continue;
const other = without.placements.get(destination);
if (other) {
if (other.balanceId === existing.balanceId) continue;
const swapped = releasePlacement(without, destination);
const first = assignDateToBalance(
swapped,
destination,
existing.balanceId,
context,
existing.ruleIds,
);
const second =
first &&
assignDateToBalance(first, date, other.balanceId, context, other.ruleIds);
if (second) {
second.placements.get(destination)!.supporting = existing.supporting;
second.placements.get(date)!.supporting = other.supporting;
}
consider(second, false, true);
} else {
const moved = assignDateToBalance(
without,
destination,
existing.balanceId,
context,
existing.ruleIds,
);
if (moved) moved.placements.get(destination)!.supporting = existing.supporting;
if (
moved &&
dateInvariantObjectives &&
compareObjectiveLists(
tieBreakObjectives(moved, context),
beforeVector.objectives.slice(-2),
) >= 0
) {
continue;
}
consider(moved, false, true);
}
}
}
}
function* relocationChains(
search: RulePlacementSearch,
round: RulePlacementRound,
): PlanningSteps<void> {
const {
context,
throughIndex,
allowAdd,
rule,
addingBalanceQuantity,
preferencePrefix,
prefixBestValues,
} = search;
const { result, active, baseline, consider } = round;
if (
allowAdd &&
(addingBalanceQuantity ||
(rule?.type === 'time_window' &&
Number(active[throughIndex].value) < rule.placeDays)) &&
compareObjectiveLists(round.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;
for (const date of result.placements.keys()) {
yield;
if (date < balance.availableFrom || date > balance.expiryDate) continue;
const sourceRuleApplies =
rule?.type !== 'time_window' ||
(date >= rule.startDate! &&
date <= rule.endDate! &&
selectorMatches(rule.placeType, balance.type));
yield* relocateForAddition(
result,
context,
date,
balance.id,
rule && sourceRuleApplies ? new Set([rule.id]) : new Set(),
false,
(candidate) => {
if (rule?.type === 'optimization' && !isAtRisk(balance, context)) {
round.beforeCalendar ??= optimizationObservations(result, context);
// No derivation: only the placement object is replaced, the key set is unchanged.
candidate.placements.set(date, {
...candidate.placements.get(date)!,
supporting: supportingCalendarBenefit(
round.beforeCalendar,
candidate,
context,
),
});
}
return consider(candidate, true);
},
);
}
}
}
}
/** Candidate additions need an active rule improvement; expiry and date ties only reshape existing placements. */
export function* optimizeRulePlacements(
state: State,
context: SearchContext,
throughIndex: number,
allowAdd: boolean,
rule?: NormalizedRule,
): PlanningSteps<State> {
let result = state;
const search = rulePlacementSearch(context, throughIndex, allowAdd, rule);
while (true) {
yield;
context.check();
const active = activeObjectiveVector(result, context);
const baseline = active.slice(0, throughIndex + 1);
const beforeVector = objectiveVector(result, context, active);
context.retain?.(result, beforeVector);
if (
allowAdd &&
search.prefixBounds.length > 0 &&
search.prefixBounds.every(
(bound, index) => bound !== undefined && active[index].value === bound,
)
) {
return result;
}
const genericStateKey =
allowAdd && result.balances.every(({ remaining }) => remaining === 0)
? preferenceStateKey(result)
: undefined;
const reuseGeneric =
genericStateKey !== undefined && context.completedGenericState === genericStateKey;
const round: RulePlacementRound = {
result,
active,
baseline,
beforeVector,
compareEquivalentFunding:
search.equivalentAdditionFunding &&
result.earnedActivations.length === 0 &&
Number.isSafeInteger(
result.balances.reduce((sum, balance) => sum + balance.remaining, 0),
),
beforeCalendar: undefined,
best: result,
bestVector: beforeVector,
consider: (
candidate: State | null,
addition = false,
onlyIfBetter = false,
): boolean => {
const evaluated = evaluateRuleCandidate(
result,
candidate,
context,
throughIndex,
addition,
baseline,
round.bestVector,
onlyIfBetter,
);
if (!evaluated) return false;
if (!evaluated.vector) return true;
const compared = compareObjectiveLists(
evaluated.vector.objectives,
round.bestVector.objectives,
);
if (compared >= 0) return true;
round.best = evaluated.state;
round.bestVector = evaluated.vector;
return true;
},
};
const dates = [...context.workingDays].sort(
(a, b) => Number(result.placements.has(a)) - Number(result.placements.has(b)),
);
const moveDates = moveDestinations(result, context);
yield* rulePlacementBundles(search, round);
// 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 =
allowAdd &&
round.best !== result &&
compareObjectiveLists(
round.bestVector.objectives.slice(1, throughIndex + 2),
baseline,
) < 0;
yield* genericPlacementScan(
search,
round,
reuseGeneric || deferGeneric ? [] : dates,
moveDates,
);
yield* relocationChains(search, round);
if (round.best === result) {
// Admit only a completed fixed point, after both bundles and the generic scan.
if (genericStateKey !== undefined) context.completedGenericState = genericStateKey;
return result;
}
round.best = reconcileOptimizationProvenance(
round.best,
context,
result,
round.bestVector.objectives,
);
context.retain?.(round.best);
result = round.best;
}
}
@@ -0,0 +1,157 @@
import { compareDateLists, isWeekend, selectorMatches } from './search-context';
import type {
LeaveSelector,
NormalizedCalendarRule,
NormalizedRule,
SearchContext,
State,
} from './types';
import type { DeclaredNonWorkingDay } from '../declared-non-working-days';
import { addDays, compareDate, utcDate } from '../plan-observations';
const occurrenceCache = new WeakMap<SearchContext, Map<string, string[]>>();
const calendarPatternCache = new WeakMap<SearchContext, Map<string, string[][]>>();
const declaredWindowCache = new WeakMap<SearchContext, Map<string, DeclaredNonWorkingDay[]>>();
export function occurrences(rule: NormalizedRule, context: SearchContext): string[] {
if (rule.type !== 'if_then') return [];
let cached = occurrenceCache.get(context);
if (!cached) {
cached = new Map();
occurrenceCache.set(context, cached);
}
let dates = cached.get(rule.id);
if (!dates) {
dates = [...context.holidays]
.filter(
(date) =>
date >= context.horizon.start &&
date < context.horizon.end &&
utcDate(date).getUTCDay() === rule.dayOfWeek,
)
.sort(compareDate);
cached.set(rule.id, dates);
}
return dates;
}
/**
* The `count` Monday-to-Friday dates next to `date` on one side. Only weekends
* are skipped: a weekday public holiday ends the side early, so no pattern can
* reach across it (8 May 2027 cannot be preceded by two days across Ascension).
*/
function workingNeighbors(
date: string,
direction: 1 | -1,
count: number,
context: SearchContext,
): string[] {
const result: string[] = [];
for (
let current = addDays(date, direction);
result.length < count;
current = addDays(current, direction)
) {
context.check?.();
if (!isWeekend(current)) {
if (context.holidays.has(current)) break;
result.push(current);
}
// A one-year horizon makes an unbounded malformed search unnecessary.
if (
compareDate(current, addDays(context.horizon.start, -400)) < 0 ||
compareDate(current, addDays(context.horizon.end, 400)) > 0
)
break;
}
return result;
}
export function patternsFor(
rule: NormalizedCalendarRule,
holiday: string,
context: SearchContext,
): string[][] {
let cached = calendarPatternCache.get(context);
if (!cached) {
cached = new Map();
calendarPatternCache.set(context, cached);
}
const key = `${rule.id}:${holiday}`;
const existing = cached.get(key);
if (existing) return existing;
const count = rule.placeDays;
const make = (before: number, after: number) =>
[
...workingNeighbors(holiday, -1, before, context),
...workingNeighbors(holiday, 1, after, context).reverse(),
].sort(compareDate);
const patterns: string[][] = [];
if (rule.placement === 'before') patterns.push(make(count, 0));
else if (rule.placement === 'after') patterns.push(make(0, count));
else if (rule.placement === 'around') {
for (let before = 1; before < count; before++) patterns.push(make(before, count - before));
} else {
for (let before = 0; before <= count; before++) patterns.push(make(before, count - before));
}
const eligible = patterns
.filter(
(pattern) =>
pattern.length === count &&
pattern.every(
(date) =>
compareDate(date, context.horizon.start) >= 0 &&
compareDate(date, context.horizon.end) < 0,
),
)
.sort(compareDateLists);
cached.set(key, eligible);
return eligible;
}
export function declaredWindowDays(rule: NormalizedRule, context: SearchContext) {
if (rule.type !== 'time_window' || !context.declaredDays.length) return [];
let byRule = declaredWindowCache.get(context);
if (!byRule) {
byRule = new Map();
declaredWindowCache.set(context, byRule);
}
let days = byRule.get(rule.id);
if (!days) {
days = context.declaredDays
.filter(
(day) =>
selectorMatches(rule.placeType, day.type) &&
day.date >= context.horizon.start &&
day.date < context.horizon.end &&
day.date >= rule.startDate! &&
day.date <= rule.endDate!,
)
.sort((a, b) => compareDate(a.date, b.date))
.slice(0, rule.placeDays);
byRule.set(rule.id, days);
}
return days;
}
export function declaredPatternDay(date: string, selector: LeaveSelector, context: SearchContext) {
if (!context.declaredDates.has(date)) return undefined;
return context.declaredDays.find(
(day) => day.date === date && selectorMatches(selector, day.type),
);
}
export function patternDateSatisfied(
date: string,
rule: NormalizedCalendarRule,
state: State,
context: SearchContext,
): boolean {
return Boolean(
declaredPatternDay(date, rule.placeType, context) ||
(state.placements.has(date) &&
selectorMatches(rule.placeType, state.placements.get(date)!.type)),
);
}
@@ -0,0 +1,472 @@
import { declaredPatternDay, occurrences, patternDateSatisfied, patternsFor } from './patterns';
import { compareText, isWorking, selectorMatches } from './search-context';
import { cloneState, copyPlacements } from './state';
import type {
EarnedActivation,
InternalBalance,
LeaveSelector,
LeaveType,
NormalizedBalance,
NormalizedCalendarRule,
PlanningSteps,
SearchContext,
State,
} from './types';
import type { DeclaredNonWorkingDay } from '../declared-non-working-days';
import { addDays, addPlacement, compareDate, periodBoundsHolding } from '../plan-observations';
import { addPlanningYears } from '../planning-date';
/**
* Balances and activations are only edited right after a state copies them, so a
* new placement shares them with its parent state, except the balance it debits.
*/
function debitBalance(state: State, balanceId: string): InternalBalance[] {
return state.balances.map((balance) =>
balance.id === balanceId ? { ...balance, remaining: balance.remaining - 1 } : balance,
);
}
/** The pattern satisfying an occurrence: complete, with the occurrence's IF_THEN reserve holding. */
export function selectedOccurrencePattern(
rule: NormalizedCalendarRule,
occurrence: string,
state: State,
context: SearchContext,
): string[] | undefined {
const activation = state.earnedActivations.find(
(item) => item.ruleId === rule.id && item.occurrence === occurrence,
);
const pattern = activation?.dates.every((date) =>
patternDateSatisfied(date, rule, state, context),
)
? activation.dates
: patternsFor(rule, occurrence, context).find((pattern) =>
pattern.every((date) => patternDateSatisfied(date, rule, state, context)),
);
return pattern && reserveHolds(rule, occurrence, state, context) ? pattern : undefined;
}
/** Whether an occurrence is satisfied: one of `patterns` is complete and its IF_THEN reserve holds. */
export function occurrenceSatisfied(
rule: NormalizedCalendarRule,
occurrence: string,
patterns: readonly (readonly string[])[],
state: State,
context: SearchContext,
): boolean {
return (
patterns.some((pattern) =>
pattern.every((date) => patternDateSatisfied(date, rule, state, context)),
) && reserveHolds(rule, occurrence, state, context)
);
}
export function reserveHolds(
rule: NormalizedCalendarRule,
occurrence: string,
state: State,
context: SearchContext,
): boolean {
return (
!rule.reserveDays || reserveRemaining(rule, occurrence, state, context) >= rule.reserveDays
);
}
interface ReserveScope {
/** The reported balances the reserve counts: of the requested type, usable on the occurrence date. */
balanceIds: ReadonlySet<string>;
reported: number;
/** The working days next to the occurrence: only non-working days separate them from it. */
neighbors: readonly string[];
/** Dates of the declared days of the requested type booked from those balances. */
declaredDates: readonly string[];
}
const reserveScopeCache = new WeakMap<SearchContext, Map<string, ReserveScope>>();
/** What an occurrence's reserve counts in every plan of the request, worked out once. */
export function reserveScope(
rule: NormalizedCalendarRule,
occurrence: string,
context: SearchContext,
): ReserveScope {
let scopes = reserveScopeCache.get(context);
if (!scopes) reserveScopeCache.set(context, (scopes = new Map()));
const key = `${rule.id}:${occurrence}`;
let scope = scopes.get(key);
if (!scope) {
const balances = context.initialBalances.filter(
(balance) =>
selectorMatches(rule.placeType, balance.type) &&
compareDate(balance.availableFrom, occurrence) <= 0 &&
compareDate(occurrence, balance.expiryDate) <= 0,
);
const balanceIds = new Set(balances.map(({ id }) => id));
let before = addDays(occurrence, -1);
while (!isWorking(before, context.holidays)) before = addDays(before, -1);
let after = addDays(occurrence, 1);
while (!isWorking(after, context.holidays)) after = addDays(after, 1);
scope = {
balanceIds,
reported: balances.reduce((sum, balance) => sum + balance.quantity, 0),
neighbors: [before, after],
declaredDates: context.declaredDays
.filter(
(day) =>
selectorMatches(rule.placeType, day.type) &&
balanceIds.has(declaredDayBalance(day, context)?.id ?? ''),
)
.map(({ date }) => date),
};
scopes.set(key, scope);
}
return scope;
}
/** The last day of the time-off period holding the occurrence, or the occurrence when none does. */
export function reservePeriodEnd(
rule: NormalizedCalendarRule,
occurrence: string,
state: State,
context: SearchContext,
): string {
const { neighbors } = reserveScope(rule, occurrence, context);
return periodBoundsHolding(state, context, neighbors)?.end ?? occurrence;
}
/** The quantity of the reserve's balances remaining on the occurrence date (ADR 0015). */
export function reserveRemaining(
rule: NormalizedCalendarRule,
occurrence: string,
state: State,
context: SearchContext,
): number {
const { balanceIds, reported, declaredDates } = reserveScope(rule, occurrence, context);
const end = reservePeriodEnd(rule, occurrence, state, context);
let remaining = reported;
for (const placement of state.placements.values())
if (placement.date <= end && balanceIds.has(placement.balanceId)) remaining--;
for (const date of declaredDates) if (date > end) remaining++;
return remaining;
}
/** The reported balance a declared day was booked from: the one it names when its date lies within the balance, else the first to expire usable on its date. */
function declaredDayBalance(
day: DeclaredNonWorkingDay,
context: SearchContext,
): NormalizedBalance | undefined {
const usable = context.initialBalances
.filter(
(balance) =>
balance.type === day.type &&
compareDate(balance.availableFrom, day.date) <= 0 &&
compareDate(day.date, balance.expiryDate) <= 0,
)
.sort((a, b) => compareDate(a.expiryDate, b.expiryDate) || compareText(a.id, b.id));
return usable.find(({ expiryDate }) => expiryDate === day.balanceExpiryDate) ?? usable[0];
}
export function assignDateVariants(
state: State,
date: string,
selector: LeaveSelector,
ruleId: string,
context: SearchContext,
): State[] {
context.check();
if (context.declaredDates.has(date)) return [];
const existing = state.placements.get(date);
if (existing) {
if (!selectorMatches(selector, existing.type)) {
return [];
}
if (ruleId) {
const rule = context.rules.find((item) => item.id === ruleId);
if (
rule?.type === 'time_window' &&
(compareDate(date, rule.startDate!) < 0 || compareDate(date, rule.endDate!) > 0)
) {
return [];
}
}
const result = cloneState(state);
if (ruleId) result.placements.get(date)!.ruleIds.add(ruleId);
return [result];
}
const balances = state.balances
.filter(
(balance) =>
balance.remaining > 0 &&
selectorMatches(selector, balance.type) &&
compareDate(balance.availableFrom, date) <= 0 &&
compareDate(date, balance.expiryDate) <= 0,
)
.sort((a, b) => {
if (selector === 'any') {
const sharedTypes = context.sharedTypesByDate.get(date) ?? new Set<LeaveType>();
if (sharedTypes.has(a.type) !== sharedTypes.has(b.type))
return sharedTypes.has(a.type) ? -1 : 1;
// A later typed preference can share a placement on this date. Prefer
// that type when an ANY preference has an otherwise equivalent choice;
// this preserves the later lexicographic criterion without consuming a
// scarce balance on a date it cannot use.
const protectedTypes =
context.protectedTypesByDate.get(date) ?? new Set<LeaveType>();
if (
protectedTypes.size &&
protectedTypes.has(a.type) !== protectedTypes.has(b.type)
)
return protectedTypes.has(a.type) ? -1 : 1;
if (context.reservedTypes.has(a.type) !== context.reservedTypes.has(b.type)) {
return context.reservedTypes.has(a.type) ? 1 : -1;
}
}
return compareDate(a.expiryDate, b.expiryDate) || compareText(a.id, b.id);
});
return balances.map((balance) => {
const placements = copyPlacements(state);
addPlacement(state.placements, placements, date, {
date,
balanceId: balance.id,
type: balance.type,
ruleIds: ruleId ? new Set([ruleId]) : new Set(),
supporting: false,
});
return {
balances: debitBalance(state, balance.id),
placements,
earnedActivations: state.earnedActivations,
};
});
}
export function assignDateToBalance(
state: State,
date: string,
balanceId: string,
context: SearchContext,
ruleIds = new Set<string>(),
): State | null {
context.check();
if (context.declaredDates.has(date)) return null;
if (state.placements.has(date)) {
return null;
}
const balance = state.balances.find((item) => item.id === balanceId);
if (
!balance ||
balance.remaining <= 0 ||
compareDate(balance.availableFrom, date) > 0 ||
compareDate(date, balance.expiryDate) > 0
) {
return null;
}
// Reject impossible mandatory moves before copying; validate complete patterns later.
if (!mandatoryRelocationDate(date, balance, ruleIds, context)) return null;
// Existing placements stay read-only; this assignment owns only its new placement.
const placements = new Map(state.placements);
addPlacement(state.placements, placements, date, {
date,
balanceId,
type: balance.type,
ruleIds: new Set(ruleIds),
supporting: false,
});
return {
balances: debitBalance(state, balanceId),
placements,
earnedActivations: state.earnedActivations,
};
}
export function addEarnedBalance(
state: State,
rule: NormalizedCalendarRule,
occurrence: string,
dates: string[],
context: SearchContext,
): State {
if (!rule.rewardDays || !rule.rewardType) return state;
const result = cloneState(state);
const id = `earned:${rule.id}:${occurrence}`;
const activation = { id, ruleId: rule.id, occurrence, dates: [...dates] };
if (!result.earnedActivations.some((item) => item.id === id))
result.earnedActivations.push(activation);
const bounds = earnedPeriodBounds(state, activation, context);
if (bounds.availableFrom <= context.request.calculationDate) return result;
if (!result.balances.some((balance) => balance.id === id)) {
result.balances.push({
id,
type: rule.rewardType,
quantity: rule.rewardDays,
remaining: rule.rewardDays,
...bounds,
earned: true,
sourceRuleId: rule.id,
});
}
return result;
}
const earnedBoundsCache = new WeakMap<
SearchContext,
Map<string, { readonly availableFrom: string; readonly expiryDate: string }>
>();
export function earnedPeriodBounds(
state: State,
activation: EarnedActivation,
context: SearchContext,
): { readonly availableFrom: string; readonly expiryDate: string } {
const allDates = [...activation.dates, activation.occurrence].sort(compareDate);
let start = allDates[0] ?? activation.occurrence;
let end = allDates[allDates.length - 1] ?? activation.occurrence;
const mergedPeriod = periodBoundsHolding(state, context, activation.dates);
if (mergedPeriod) {
start = mergedPeriod.start;
end = mergedPeriod.end;
}
// The same few periods recur across obligation solutions; the date arithmetic runs once each.
let known = earnedBoundsCache.get(context);
if (!known) earnedBoundsCache.set(context, (known = new Map()));
// The rule fixes the requested type, so its id stands for the selector in the key.
const key = `${activation.ruleId}|${start}|${end}`;
let bounds = known.get(key);
if (!bounds) {
while (!isWorking(addDays(start, -1), context.holidays)) start = addDays(start, -1);
while (!isWorking(addDays(end, 1), context.holidays)) end = addDays(end, 1);
const availableFrom = addDays(end, 1);
const rule = context.rules.find((item) => item.id === activation.ruleId);
const leaveYearEnd = context.initialBalances
.filter(
(balance) =>
rule?.type === 'if_then' &&
selectorMatches(rule.placeType, balance.type) &&
compareDate(balance.availableFrom, availableFrom) <= 0 &&
compareDate(availableFrom, balance.expiryDate) <= 0,
)
.map(({ expiryDate }) => expiryDate)
.sort(compareDate)[0];
bounds = { availableFrom, expiryDate: leaveYearEnd ?? addPlanningYears(availableFrom, 1) };
known.set(key, bounds);
}
return bounds;
}
/**
* Reconcile generated balances whenever a branch gains placements.
* A later placement can extend the generating merged period, so a
* provisional reward must not finance an earlier placement in that same final
* period.
*/
export function finalizeEarnedState(state: State, context: SearchContext): State | null {
let reconciled = state;
// Earning follows actual completed patterns, including those another rule already placed.
// Both comparison sides must contain these rights before an objective can rank them.
for (const rule of context.rules) {
if (rule.type !== 'if_then' || !rule.rewardDays) continue;
for (const occurrence of occurrences(rule, context)) {
if (
reconciled.earnedActivations.some(
(activation) =>
activation.ruleId === rule.id && activation.occurrence === occurrence,
)
)
continue;
const pattern = selectedOccurrencePattern(rule, occurrence, reconciled, context);
if (pattern)
reconciled = addEarnedBalance(reconciled, rule, occurrence, pattern, context);
}
}
if (!reconciled.earnedActivations.length) return reconciled;
let result = cloneState(reconciled);
for (const activation of result.earnedActivations) {
context.check();
const bounds = earnedPeriodBounds(result, activation, context);
if (bounds.availableFrom <= context.request.calculationDate) {
if (
[...result.placements.values()].some(
(placement) => placement.balanceId === activation.id,
)
)
return null;
result.balances = result.balances.filter((balance) => balance.id !== activation.id);
continue;
}
let balance = result.balances.find((item) => item.id === activation.id);
if (!balance) {
const rule = context.rules.find(
(rule): rule is NormalizedCalendarRule =>
rule.type === 'if_then' && rule.id === activation.ruleId,
);
if (!rule) return null;
result = addEarnedBalance(
result,
rule,
activation.occurrence,
activation.dates,
context,
);
balance = result.balances.find((item) => item.id === activation.id);
if (!balance) continue;
}
balance.availableFrom = bounds.availableFrom;
balance.expiryDate = bounds.expiryDate;
for (const placement of result.placements.values()) {
if (
placement.balanceId === activation.id &&
(compareDate(placement.date, balance.availableFrom) < 0 ||
compareDate(placement.date, balance.expiryDate) > 0)
)
return null;
}
}
return result;
}
export function* assignDatesVariants(
state: State,
dates: string[],
rule: NormalizedCalendarRule,
context: SearchContext,
): PlanningSteps<State[]> {
if (!dates.length) return [state];
const [date, ...rest] = dates;
if (
!isWorking(date, context.holidays) ||
compareDate(date, context.horizon.start) < 0 ||
compareDate(date, context.horizon.end) >= 0
)
return [];
if (context.declaredDates.has(date)) {
if (declaredPatternDay(date, rule.placeType, context))
return yield* assignDatesVariants(state, rest, rule, context);
return [];
}
const result: State[] = [];
for (const next of assignDateVariants(state, date, rule.placeType, rule.id, context)) {
yield;
result.push(...(yield* assignDatesVariants(next, rest, rule, context)));
}
return result;
}
export function mandatoryRelocationDate(
date: string,
balance: InternalBalance,
ruleIds: ReadonlySet<string>,
context: SearchContext,
): boolean {
return [...ruleIds].every((id) => {
const rule = context.rules.find((item) => item.id === id);
if (rule?.force !== 'obligation') return true;
if (!selectorMatches(rule.placeType, balance.type)) return false;
return rule.type === 'time_window'
? date >= rule.startDate! && date <= rule.endDate!
: occurrences(rule, context).some((occurrence) =>
patternsFor(rule, occurrence, context).some((pattern) =>
pattern.includes(date),
),
);
});
}
@@ -0,0 +1,634 @@
import { reconcileOptimizationProvenance } from './candidate-evaluation';
import {
conflictExplanation,
makePlan,
planExplanation,
planningStages,
ruleStage,
} from './explanation';
import { normalizeRequest } from './normalize';
import { jointReserveConflict, obligationConflict, satisfyObligations } from './obligations';
import { optimizeRulePlacements } from './optimize';
import { declaredPatternDay, occurrences, patternsFor } from './patterns';
import { addEarnedBalance, finalizeEarnedState, reserveHolds } from './placement';
import { applyPreferenceStep } from './preferences';
import {
buildRequirements,
compareRequirements,
futurePreferenceProtection,
obligationBranchEstimate,
obligationFundingProducers,
} from './requirements';
import {
createSearchContext,
DeadlineReached,
EXACT_OBLIGATION_BRANCH_LIMIT,
now,
OBLIGATION_SOLUTION_LIMIT,
observeCallback,
prepareCalendar,
reason,
UserCancelled,
} from './search-context';
import { cloneState, planningStateSnapshot } from './state';
import {
objectiveVector,
obligationPreviewObjectives,
preferenceReason,
preferenceResultsForState,
preferenceStateKey,
unsatisfiedObligationCount,
} from './state-objectives';
import type {
IncompleteExplanation,
InterruptionReason,
InvalidInputOutcome,
LeaveType,
NormalizedCalendarRule,
NormalizedRule,
PlanningCalendar,
PlanningConflictOutcome,
PlanningEmit,
PlanningExplanation,
PlanningIncompleteOutcome,
PlanningObjective,
PlanningObjectiveVector,
PlanningOutcome,
PlanningStateSnapshot,
PlanningSteps,
PlanOutcome,
PreferenceResult,
Requirement,
SearchContext,
State,
} from './types';
import { compareObjectiveLists } from '../planning-objectives';
function markProgress(context: SearchContext, stage: string): void {
const { emit } = context;
if (emit) observeCallback(context, () => emit({ type: 'progress', stage }));
}
type RetainedIncumbent = {
state: State;
preferences: PreferenceResult[];
vector: PlanningObjectiveVector;
/** The retained state is never edited, so its key is built once. */
key?: string;
};
/** The mutable locals the planning stages share; `stages` and `preferences` are reused, never replaced. */
interface PlanningWorkspace {
context: SearchContext;
emit?: PlanningEmit;
initialState: State;
state: State;
stages: string[];
preferences: PreferenceResult[];
checkpoint?: PlanOutcome;
checkpointState?: State;
}
function cancelledDuringPreparation(
calculationDate: PlanningIncompleteOutcome['calculationDate'],
emit?: PlanningEmit,
): PlanningIncompleteOutcome {
const outcome: PlanningIncompleteOutcome = {
kind: 'PlanningIncomplete',
calculationDate,
completedStages: ['validation'],
lastCompletedStage: 'validation',
reasons: [reason('user-cancelled', 'The calculation was cancelled by the user.')],
};
const explanation: IncompleteExplanation = {
kind: 'IncompleteExplanation',
calculationDate,
reason: outcome.reasons[0],
completedStages: outcome.completedStages,
uncompletedStages: ['preparation', 'obligations'],
};
emit?.({ type: 'result', outcome });
emit?.({ type: 'explanation', explanation });
emit?.({ type: 'artifacts', artifacts: { explanation } });
return outcome;
}
function createIncumbentRetention(
context: SearchContext,
initialState: State,
stages: string[],
emit?: PlanningEmit,
): {
retain: (state: State, vector?: PlanningObjectiveVector) => void;
current: () => RetainedIncumbent | undefined;
} {
let retained: RetainedIncumbent | undefined;
const retain = (candidate: State, candidateVector?: PlanningObjectiveVector): void => {
const check = context.check;
context.check = () => undefined;
try {
const finalized = candidateVector ? candidate : finalizeEarnedState(candidate, context);
if (!finalized) return;
if (unsatisfiedObligationCount(finalized, context)) return;
if (
retained &&
(retained.key ??= preferenceStateKey(retained.state)) ===
preferenceStateKey(finalized)
)
return;
const vector = candidateVector ?? objectiveVector(finalized, context);
const compared = retained
? compareObjectiveLists(vector.objectives, retained.vector.objectives)
: -1;
// Calendar association can complete provenance after the scoring candidate is retained.
const provenanceRefresh =
compared === 0 &&
!!retained &&
JSON.stringify(retained.state.balances) === JSON.stringify(finalized.balances) &&
retained.state.placements.size === finalized.placements.size &&
[...retained.state.placements].every(([date, previous]) => {
const placement = finalized.placements.get(date);
return (
placement &&
placement.balanceId === previous.balanceId &&
placement.type === previous.type &&
placement.supporting === previous.supporting
);
}) &&
JSON.stringify(retained.state.earnedActivations) ===
JSON.stringify(finalized.earnedActivations);
const chosen = compared < 0 || provenanceRefresh;
if (chosen) {
const firstValidCandidate = !retained;
const candidatePreferences = preferenceResultsForState(finalized, context);
retained = {
state: cloneState(
reconcileOptimizationProvenance(
finalized,
context,
retained?.state ?? initialState,
vector.objectives,
),
),
vector,
preferences: candidatePreferences,
};
if (firstValidCandidate && emit)
observeCallback(context, () =>
emit({
type: 'checkpoint',
plan: makePlan(retained!.state, context, retained!.preferences, stages),
state: planningStateSnapshot(retained!.state, context),
}),
);
}
} finally {
context.check = check;
}
};
return { retain, current: () => retained };
}
function outcomeExplanation(
outcome: PlanningOutcome,
explanationState: State | undefined,
context: SearchContext,
): PlanningExplanation | undefined {
if (outcome.kind === 'Plan' && explanationState)
return planExplanation(
explanationState,
context,
outcome.placements,
outcome.timeOffPeriods,
outcome.preferences,
outcome.remainingBalances,
outcome.metrics,
);
if (outcome.kind === 'PlanningIncomplete') {
if (outcome.incumbent && explanationState) {
const incumbentExplanation = planExplanation(
explanationState,
context,
outcome.incumbent.placements,
outcome.incumbent.timeOffPeriods,
outcome.incumbent.preferences,
outcome.incumbent.remainingBalances,
outcome.incumbent.metrics,
);
return {
...incumbentExplanation,
incomplete: {
kind: 'IncompleteExplanation',
reason: outcome.reasons[0],
completedStages: [...outcome.completedStages],
uncompletedStages: planningStages(context).filter(
(stage) => !outcome.completedStages.includes(stage),
),
},
};
}
return {
kind: 'IncompleteExplanation',
reason: outcome.reasons[0],
completedStages: [...outcome.completedStages],
uncompletedStages: planningStages(context).filter(
(stage) => !outcome.completedStages.includes(stage),
),
};
}
if (outcome.kind === 'PlanningConflict') return conflictExplanation(outcome, context);
return undefined;
}
function finishPlanning(
context: SearchContext,
emit: PlanningEmit | undefined,
started: number,
outcome: PlanningOutcome,
explanationState?: State,
): PlanningOutcome {
outcome.calculationDate = context.request.calculationDate;
const planningFinishedAt = now();
const planningExcludedTime = context.observerTime;
emit?.({ type: 'result', outcome });
// Explanation materialization is post-outcome work and must not consume or
// inherit the planning deadline.
context.check = () => undefined;
let explanation: PlanningExplanation | undefined;
let explanationError: InterruptionReason | undefined;
let finalState: PlanningStateSnapshot | undefined;
try {
explanation = outcomeExplanation(outcome, explanationState, context);
} catch (error) {
explanationError = reason(
'explanation-error',
error instanceof Error ? error.message : String(error),
);
}
try {
if (explanationState) finalState = planningStateSnapshot(explanationState, context);
} catch (error) {
explanationError ??= reason(
'explanation-error',
error instanceof Error ? error.message : String(error),
);
}
if (explanation) explanation.calculationDate = context.request.calculationDate;
try {
emit?.({ type: 'explanation', explanation, explanationError, finalState });
} catch (error) {
explanationError ??= reason(
'explanation-error',
error instanceof Error ? error.message : String(error),
);
}
emit?.({
type: 'artifacts',
artifacts: {
explanation,
finalState,
explanationError,
timings: {
planningWorkMs: Math.max(0, planningFinishedAt - started - planningExcludedTime),
},
},
});
return outcome;
}
function publishCheckpoint(run: PlanningWorkspace): void {
const { context, emit } = run;
run.state = reconcileOptimizationProvenance(
run.state,
context,
run.checkpointState ?? run.initialState,
);
context.retain?.(run.state);
run.checkpoint = makePlan(run.state, context, run.preferences, run.stages);
run.checkpointState = cloneState(run.state);
if (emit) {
observeCallback(context, () =>
emit({
type: 'checkpoint',
plan: run.checkpoint!,
state: planningStateSnapshot(run.checkpointState!, context),
}),
);
}
}
function* addDeclaredEarnedBalances(run: PlanningWorkspace): PlanningSteps<void> {
const { context } = run;
// Entirely fixed patterns already hold before any placement choices,
// including preference producers needed by mandatory consumers.
if (context.declaredDays.length) {
for (const rule of context.rules) {
if (!rule.enabled || rule.type !== 'if_then' || !rule.rewardDays) continue;
for (const occurrence of occurrences(rule, context)) {
yield;
const pattern = patternsFor(rule, occurrence, context).find((dates) =>
dates.every((date) => declaredPatternDay(date, rule.placeType, context)),
);
if (pattern && reserveHolds(rule, occurrence, run.state, context))
run.state = addEarnedBalance(run.state, rule, occurrence, pattern, context);
}
}
if (run.state !== run.initialState) context.retain?.(run.state);
}
}
function* obligationStage(
normalized: ReturnType<typeof normalizeRequest>,
context: SearchContext,
state: State,
): PlanningSteps<{
requirements: Requirement[];
solutions: State[];
conflict?: PlanningConflictOutcome;
}> {
// Equivalent obligation placements can share compatible dates with active preferences.
context.protectedTypesByDate = futurePreferenceProtection(normalized.rules, 0, context);
markProgress(context, 'obligations');
yield true;
const obligationRequirements = buildRequirements(normalized.rules, context, 'obligation');
context.reservedTypes = new Set(
obligationRequirements
.filter((requirement) => requirement.requiredPlacements > 0)
.map((requirement) => requirement.rule.placeType)
.filter((selector): selector is LeaveType => selector !== 'any'),
);
for (const requirement of obligationRequirements) {
yield;
if (
!requirement.candidates ||
!requirement.requiredPlacements ||
requirement.candidates.length !== 1 ||
requirement.rule.placeType === 'any'
)
continue;
const types =
context.sharedTypesByDate.get(requirement.candidates[0]) ?? new Set<LeaveType>();
types.add(requirement.rule.placeType);
context.sharedTypesByDate.set(requirement.candidates[0], types);
}
const obligationSolutions: State[] = [];
const optionalProducers = obligationRequirements.some(
(requirement) => requirement.requiredPlacements > 0,
)
? obligationFundingProducers(
buildRequirements(normalized.rules, context, 'preference').filter(
(requirement) =>
requirement.patterns?.length &&
requirement.rule.rewardDays &&
requirement.requiredPlacements > 0,
),
obligationRequirements,
).map((requirement) => ({ ...requirement, optional: true }))
: [];
const jointRequirements = optionalProducers.length
? [...obligationRequirements, ...optionalProducers].sort(compareRequirements)
: obligationRequirements;
const hasEarnedObligation =
optionalProducers.length > 0 ||
obligationRequirements.some((requirement) => (requirement.rule.rewardDays ?? 0) > 0);
const obligationSolutionLimit =
hasEarnedObligation ||
obligationBranchEstimate(obligationRequirements) <= EXACT_OBLIGATION_BRANCH_LIMIT
? 0
: OBLIGATION_SOLUTION_LIMIT;
yield* satisfyObligations(
jointRequirements,
state,
context,
0,
obligationSolutions,
obligationSolutionLimit,
);
if (!obligationSolutions.length) {
const conflict = yield* obligationConflict(
obligationRequirements,
context,
normalized.rules.some(
(rule) =>
rule.type === 'if_then' && rule.force === 'obligation' && rule.reserveDays,
)
? jointReserveConflict(jointRequirements, state, context)
: undefined,
);
return { requirements: obligationRequirements, solutions: obligationSolutions, conflict };
}
return { requirements: obligationRequirements, solutions: obligationSolutions };
}
function* rankObligationSolutions(
obligationSolutions: State[],
context: SearchContext,
): PlanningSteps<State[]> {
if (obligationSolutions.length <= 1) return obligationSolutions;
// shortcut: preferences run on the best-ranked obligation-only plan only, so a lower-ranked one that would end better is missed (ADR 0010); revisit if the comparison record grows.
const ranked: { state: State; objectives: PlanningObjective[] }[] = [];
for (const candidate of obligationSolutions) {
yield;
context.check();
ranked.push({
state: candidate,
objectives: obligationPreviewObjectives({ state: candidate }, context),
});
}
// The sort is stable, so equal ranks keep enumeration order.
ranked.sort((a, b) => compareObjectiveLists(a.objectives, b.objectives));
return ranked.map(({ state }) => state);
}
/** Runs the preference, expiry and dates stages on one obligation solution; false when its earned leave comes too late. */
function* planObligationSolution(
run: PlanningWorkspace,
obligationSolution: State,
preferenceRules: NormalizedRule[],
): PlanningSteps<boolean> {
const { context, stages, preferences } = run;
// A solution whose earned leave comes too late restarts the stages on the next one.
run.state = obligationSolution;
stages.length = 1;
preferences.length = 0;
run.checkpointState = undefined;
stages.push('obligations');
publishCheckpoint(run);
for (let preferenceIndex = 0; preferenceIndex < preferenceRules.length; preferenceIndex++) {
yield;
const rule = preferenceRules[preferenceIndex];
markProgress(context, ruleStage(rule));
yield true;
run.state = yield* applyPreferenceStep(
run.state,
preferenceRules,
preferenceIndex,
preferences,
context,
);
stages.push(ruleStage(rule));
publishCheckpoint(run);
}
markProgress(context, 'expiry');
yield true;
run.state = yield* optimizeRulePlacements(
run.state,
context,
preferenceRules.length - 1,
false,
);
stages.push('expiry');
publishCheckpoint(run);
markProgress(context, 'dates');
yield true;
stages.push('dates');
const finalized = finalizeEarnedState(run.state, context);
if (!finalized) return false;
run.state = finalized;
publishCheckpoint(run);
markProgress(context, 'complete');
yield true;
return true;
}
function interruptionOutcome(
run: PlanningWorkspace,
error: unknown,
retained: RetainedIncumbent | undefined,
rules: SearchContext['rules'],
): PlanningIncompleteOutcome {
const { context, stages } = run;
if (error instanceof UserCancelled && retained) {
// Freeze the chosen valid candidate, rather than exposing a temporary search state.
context.check = () => undefined;
context.retain = undefined;
run.checkpointState = retained.state;
const partialPreferences = retained.preferences.map((preference) => ({
...preference,
reason: preferenceReason(
rules.find(
(rule): rule is NormalizedCalendarRule =>
rule.type !== 'optimization' && rule.id === preference.ruleId,
)!,
preference.satisfied,
context,
retained.state,
),
}));
run.checkpoint = makePlan(run.checkpointState, context, partialPreferences, stages);
}
const interruption =
error instanceof UserCancelled
? reason('user-cancelled', 'The calculation was cancelled by the user.')
: error instanceof DeadlineReached
? reason(
'deadline',
`Planning stopped after ${context.deadline}ms before all quality stages completed.`,
)
: reason('planner-error', error instanceof Error ? error.message : String(error));
return {
kind: 'PlanningIncomplete',
incumbent: run.checkpoint,
completedStages: [...stages],
lastCompletedStage: stages[stages.length - 1],
reasons: [interruption],
};
}
export function* calculatePlanningSteps(
request: unknown,
emit?: PlanningEmit,
retainIncumbents = false,
): PlanningSteps<PlanningOutcome> {
const normalized = normalizeRequest(request);
const source = normalized.request;
if (normalized.reasons.length) {
const outcome: InvalidInputOutcome = {
kind: 'InvalidInput',
reasons: normalized.reasons,
calculationDate: source.calculationDate,
};
emit?.({ type: 'result', outcome });
emit?.({ type: 'artifacts', artifacts: {} });
return outcome;
}
const horizon = normalized.horizon!;
let calendar: PlanningCalendar;
try {
emit?.({ type: 'progress', stage: 'preparation' });
yield true;
calendar = yield* prepareCalendar(horizon, () =>
emit?.({ type: 'progress', stage: 'preparation' }),
);
} catch (error) {
if (!(error instanceof UserCancelled)) throw error;
return cancelledDuringPreparation(source.calculationDate, emit);
}
const started =
typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now();
const context = createSearchContext(normalized, horizon, calendar, source.deadlineMs, started);
context.check = () => {
context.nodes++;
if (context.deadline <= 1 || context.nodes % 16 === 0) {
if (now() - context.started - context.observerTime >= context.deadline)
throw new DeadlineReached();
}
};
context.emit = emit;
const initialState: State = {
balances: normalized.balances.map((balance) => ({
...balance,
remaining: balance.quantity,
})),
placements: new Map(),
earnedActivations: [],
};
const run: PlanningWorkspace = {
context,
emit,
initialState,
state: initialState,
stages: ['validation'],
preferences: [],
};
const retention = createIncumbentRetention(context, initialState, run.stages, emit);
if (retainIncumbents) context.retain = retention.retain;
const finish = (outcome: PlanningOutcome, explanationState?: State): PlanningOutcome =>
finishPlanning(context, emit, started, outcome, explanationState);
try {
markProgress(context, 'validation');
yield true;
yield* addDeclaredEarnedBalances(run);
const obligations = yield* obligationStage(normalized, context, run.state);
if (obligations.conflict) {
run.stages.push('obligations');
return finish(obligations.conflict);
}
const preferenceRules = normalized.rules.filter(
(item) => item.enabled && item.force === 'preference',
);
const rankedSolutions = yield* rankObligationSolutions(obligations.solutions, context);
for (const obligationSolution of rankedSolutions) {
if (yield* planObligationSolution(run, obligationSolution, preferenceRules))
return finish(run.checkpoint!, run.state);
}
// As when every preview failed, several failing solutions report the obligation conflict.
if (rankedSolutions.length > 1)
return finish(yield* obligationConflict(obligations.requirements, context));
return finish({
kind: 'PlanningConflict',
conflictingRuleIds: run.state.earnedActivations.map((activation) => activation.ruleId),
reasons: [
reason(
'earned-entitlement-order',
'Generated leave became available only after its final merged time-off period.',
),
],
});
} catch (error) {
return finish(
interruptionOutcome(run, error, retention.current(), normalized.rules),
run.checkpointState,
);
}
}
@@ -0,0 +1,468 @@
import { finalizeRuleCandidate, supportingCalendarBenefit } from './candidate-evaluation';
import { optimizeRulePlacements } from './optimize';
import { declaredPatternDay, declaredWindowDays, occurrences, patternsFor } from './patterns';
import {
addEarnedBalance,
assignDateToBalance,
assignDateVariants,
finalizeEarnedState,
reserveHolds,
reservePeriodEnd,
reserveRemaining,
reserveScope,
selectedOccurrencePattern,
} from './placement';
import { futurePreferenceProtection, patternConflictScore } from './requirements';
import { compareDateLists, selectorMatches } from './search-context';
import { cloneState, releasePlacement } from './state';
import {
activeObjectiveVector,
compareObligationPreviews,
preferenceReason,
preferenceResult,
preferenceResultsForState,
preferenceStateKey,
unsatisfiedObligationCount,
} from './state-objectives';
import type {
InternalPlacement,
NormalizedCalendarRule,
NormalizedRule,
PlanningObjective,
PlanningSteps,
PreferenceResult,
SearchContext,
State,
} from './types';
import { isAtRisk, optimizationObservations } from '../plan-observations';
import { compareObjectiveLists, firstDifferentObjective } from '../planning-objectives';
function associateCalendarPreference(
state: State,
rule: NormalizedCalendarRule,
context: SearchContext,
): State {
const result = cloneState(state);
const dates =
rule.type === 'time_window'
? [...result.placements.values()]
.filter(
(placement) =>
placement.date >= rule.startDate! &&
placement.date <= rule.endDate! &&
selectorMatches(rule.placeType, placement.type),
)
.sort((a, b) => Number(b.ruleIds.has(rule.id)) - Number(a.ruleIds.has(rule.id)))
.slice(
0,
Math.max(0, rule.placeDays - declaredWindowDays(rule, context).length),
)
.map((placement) => placement.date)
: occurrences(rule, context).flatMap(
(occurrence) =>
selectedOccurrencePattern(rule, occurrence, result, context) ?? [],
);
for (const date of dates) {
const placement = result.placements.get(date);
if (!placement) continue;
placement.ruleIds.add(rule.id);
placement.supporting = false;
}
return result;
}
/** Complete the entire typed pattern before checking the ordered objectives. */
function* preferencePatternVariants(
state: State,
pattern: string[],
rule: NormalizedCalendarRule,
context: SearchContext,
): PlanningSteps<State[]> {
let variants = [state];
for (const date of pattern) {
yield;
const next: State[] = [];
for (const current of variants) {
yield;
const existing = current.placements.get(date);
if (!existing || selectorMatches(rule.placeType, existing.type)) {
if (declaredPatternDay(date, rule.placeType, context)) next.push(current);
else {
const assigned = assignDateVariants(
current,
date,
rule.placeType,
rule.id,
context,
);
next.push(
...(assigned.length || existing
? assigned
: movedOntoPattern(current, date, pattern, rule, context)),
);
}
continue;
}
const without = releasePlacement(current, date);
for (const balance of without.balances) {
yield;
if (!selectorMatches(rule.placeType, balance.type)) continue;
const reassigned = assignDateToBalance(
without,
date,
balance.id,
context,
new Set([rule.id]),
);
if (reassigned) next.push(reassigned);
}
for (const other of without.placements.values()) {
yield;
if (pattern.includes(other.date) || !selectorMatches(rule.placeType, other.type))
continue;
const released = releasePlacement(without, other.date);
const first = assignDateToBalance(
released,
date,
other.balanceId,
context,
new Set([...other.ruleIds, rule.id]),
);
const swapped =
first &&
assignDateToBalance(
first,
other.date,
existing.balanceId,
context,
existing.ruleIds,
);
if (!swapped) continue;
swapped.placements.get(date)!.supporting = other.supporting;
swapped.placements.get(other.date)!.supporting = existing.supporting;
next.push(swapped);
}
}
variants = next;
if (!variants.length) break;
}
return variants;
}
function* preferenceIfThen(
state: State,
rule: NormalizedCalendarRule,
context: SearchContext,
preferenceIndex: number,
): PlanningSteps<{ state: State; count: number }> {
const matchingOccurrences = occurrences(rule, context);
let bestState = state;
let bestCount = 0;
const baseline = activeObjectiveVector(state, context, preferenceIndex);
const search = function* (index: number, current: State, count: number): PlanningSteps<void> {
yield;
context.check();
const maximumCount = count + matchingOccurrences.length - index;
if (
maximumCount < bestCount &&
baseline.slice(0, preferenceIndex).every((objective) => {
if (objective.direction === 'minimize') return objective.value === 0;
const earlier = context.rules.find(
(item) => `preference:${item.id}` === objective.id,
);
return (
earlier &&
objective.value ===
(earlier.type === 'time_window'
? earlier.placeDays
: occurrences(earlier, context).length)
);
})
) {
return;
}
if (index >= matchingOccurrences.length) {
let finalized = finalizeRuleCandidate(current, context, state);
if (!finalized || unsatisfiedObligationCount(finalized, context)) {
return;
}
if (
compareObjectiveLists(
activeObjectiveVector(finalized, context, preferenceIndex),
baseline,
) > 0
) {
finalized = placeEarnedForEarlierObjective(
finalized,
rule,
state,
baseline,
preferenceIndex,
context,
);
if (!finalized) return;
}
context.retain?.(finalized);
const better =
compareObligationPreviews({ state: finalized }, { state: bestState }, context) < 0;
if (better) {
// A later pattern sharing a time-off period can break an earlier counted reserve.
bestCount = rule.reserveDays
? preferenceResult(rule, finalized, context).satisfied
: count;
bestState = finalized;
}
return;
}
const occurrence = matchingOccurrences[index];
const patterns = [...patternsFor(rule, occurrence, context)].sort(
(a, b) =>
patternConflictScore(rule.placeType, a, context) -
patternConflictScore(rule.placeType, b, context) || compareDateLists(a, b),
);
for (const pattern of patterns) {
yield;
const variants = yield* preferencePatternVariants(current, pattern, rule, context);
for (const variant of variants) {
yield;
// An occurrence whose reserve cannot hold places nothing.
const reserved = keptReserve(variant, rule, occurrence, context);
if (!reserved) continue;
const finalized = finalizeEarnedState(
addEarnedBalance(reserved, rule, occurrence, pattern, context),
context,
);
if (!finalized) continue;
yield* search(index + 1, finalized, count + 1);
}
}
// A preference may leave an occurrence unplaced. Exploring this branch after
// complete patterns keeps the result deterministic while still maximizing the
// number of complete occurrences.
yield* search(index + 1, current, count);
};
yield* search(0, state, 0);
context.retain?.(bestState);
return {
state: bestState,
count: rule.reserveDays ? preferenceResult(rule, bestState, context).satisfied : bestCount,
};
}
/**
* When earlier objectives already placed all the requested leave, move the first such placement
* onto a free pattern date; the earlier objectives judge the move at the leaf.
*/
function movedOntoPattern(
state: State,
date: string,
pattern: string[],
rule: NormalizedCalendarRule,
context: SearchContext,
): State[] {
for (const other of state.placements.values()) {
const balance = state.balances.find((item) => item.id === other.balanceId);
if (
!balance ||
date < balance.availableFrom ||
date > balance.expiryDate ||
pattern.includes(other.date) ||
!selectorMatches(rule.placeType, other.type) ||
[...other.ruleIds].some(
(id) => context.rules.find((item) => item.id === id)?.type !== 'optimization',
)
)
continue;
const moved = assignDateToBalance(
releasePlacement(state, other.date),
date,
other.balanceId,
context,
new Set([rule.id]),
);
if (moved) return [moved];
}
return [];
}
/**
* When earlier objectives already placed the leave an occurrence's IF_THEN reserve counts, move
* placements held only by optimization rules, latest first, from the occurrence's time-off period or
* before it to the first free dates after it; the earlier objectives judge the moves at the leaf.
* Each move adds a day to the reserve, so at most the missing days move. Undefined when it cannot hold.
*/
function keptReserve(
state: State,
rule: NormalizedCalendarRule,
occurrence: string,
context: SearchContext,
): State | undefined {
if (reserveHolds(rule, occurrence, state, context)) return state;
const { balanceIds } = reserveScope(rule, occurrence, context);
let result = state;
let remaining = reserveRemaining(rule, occurrence, result, context);
while (remaining < rule.reserveDays!) {
const end = reservePeriodEnd(rule, occurrence, result, context);
let source: InternalPlacement | undefined;
for (const placement of result.placements.values())
if (
placement.date <= end &&
(!source || placement.date > source.date) &&
balanceIds.has(placement.balanceId) &&
[...placement.ruleIds].every(
(id) => context.rules.find((item) => item.id === id)?.type === 'optimization',
)
)
source = placement;
if (!source) return undefined;
const released = releasePlacement(result, source.date);
const before = remaining;
for (const date of context.workingDays) {
if (date <= end) continue;
const moved = assignDateToBalance(
released,
date,
source.balanceId,
context,
source.ruleIds,
);
if (!moved) continue;
// A date next to the period joins it and frees nothing.
const after = reserveRemaining(rule, occurrence, moved, context);
if (after <= remaining) continue;
moved.placements.get(date)!.supporting = source.supporting;
result = moved;
remaining = after;
break;
}
if (remaining === before) return undefined;
}
return result;
}
/**
* Leave earned inside its leave year can make a candidate worse on an earlier leave-balance
* objective until it is placed. Place each such day on its first valid date, as that objective
* would, and keep the candidate only if the earlier objectives are then no worse than the baseline.
*/
function placeEarnedForEarlierObjective(
candidate: State,
rule: NormalizedCalendarRule,
before: State,
baseline: readonly PlanningObjective[],
preferenceIndex: number,
context: SearchContext,
): State | null {
const vector = activeObjectiveVector(candidate, context, preferenceIndex);
const worse = vector[firstDifferentObjective(vector, baseline)];
const earlier = context.rules.find(
(item) =>
item.type === 'optimization' &&
item.configuration.elements === 'leave-balances' &&
`optimization:${item.id}` === worse?.id,
);
if (!earlier) return null;
let result = candidate;
for (const { id, sourceRuleId } of candidate.balances) {
if (sourceRuleId !== rule.id) continue;
for (const date of context.workingDays) {
const balance = result.balances.find((item) => item.id === id);
if (!balance || balance.remaining <= 0 || date > balance.expiryDate) break;
// The first working day after the generating period would extend it and move availability.
if (date <= balance.availableFrom) continue;
const assigned = assignDateToBalance(result, date, id, context, new Set([earlier.id]));
if (!assigned) continue;
if (!isAtRisk(balance, context))
assigned.placements.get(date)!.supporting = supportingCalendarBenefit(
optimizationObservations(result, context),
assigned,
context,
);
result = finalizeRuleCandidate(assigned, context, before) ?? result;
}
}
return result !== candidate &&
compareObjectiveLists(activeObjectiveVector(result, context, preferenceIndex), baseline) <=
0
? result
: null;
}
export function* applyPreferenceStep(
state: State,
preferenceRules: NormalizedRule[],
preferenceIndex: number,
preferences: PreferenceResult[],
context: SearchContext,
): PlanningSteps<State> {
let result = state;
const apply = function* (index: number): PlanningSteps<void> {
const rule = preferenceRules[index];
context.protectedTypesByDate = futurePreferenceProtection(
preferenceRules,
index + 1,
context,
);
if (context.completedPreferenceStates.get(index) === preferenceStateKey(result)) {
return;
}
if (rule.type === 'optimization')
result = yield* optimizeRulePlacements(result, context, index, true, rule);
else if (rule.type === 'time_window')
result = associateCalendarPreference(
yield* optimizeRulePlacements(result, context, index, true, rule),
rule,
context,
);
else
result = associateCalendarPreference(
(yield* preferenceIfThen(result, rule, context, index)).state,
rule,
context,
);
context.completedPreferenceStates.set(index, preferenceStateKey(result));
};
yield* apply(preferenceIndex);
// An earned entitlement produced later can satisfy an earlier preference.
let previous: PlanningObjective[];
do {
previous = activeObjectiveVector(result, context);
const entitlements = result.balances
.map(
({ id, quantity, availableFrom, expiryDate }) =>
`${id}:${quantity}:${availableFrom}:${expiryDate}`,
)
.join('|');
for (let index = 0; index < preferenceIndex; index++) {
yield;
yield* apply(index);
}
if (
compareObjectiveLists(activeObjectiveVector(result, context), previous) < 0 ||
result.balances
.map(
({ id, quantity, availableFrom, expiryDate }) =>
`${id}:${quantity}:${availableFrom}:${expiryDate}`,
)
.join('|') !== entitlements
)
yield* apply(preferenceIndex);
} while (compareObjectiveLists(activeObjectiveVector(result, context), previous) < 0);
preferences.splice(
0,
preferences.length,
...preferenceResultsForState(result, context).map((preference) => ({
...preference,
reason: preferenceReason(
context.rules.find(
(rule): rule is NormalizedCalendarRule =>
rule.type !== 'optimization' && rule.id === preference.ruleId,
)!,
preference.satisfied,
context,
result,
),
})),
);
return result;
}
@@ -0,0 +1,247 @@
import { declaredPatternDay, declaredWindowDays, occurrences, patternsFor } from './patterns';
import { compareDateLists, EXACT_OBLIGATION_BRANCH_LIMIT, selectorMatches } from './search-context';
import type {
LeaveSelector,
LeaveType,
NormalizedRule,
Requirement,
RuleForce,
SearchContext,
} from './types';
import { addDays, compareDate } from '../plan-observations';
const obligationRequirementCache = new WeakMap<SearchContext, Requirement[]>();
export function futurePreferenceProtection(
rules: NormalizedRule[],
startIndex: number,
context: SearchContext,
): Map<string, Set<LeaveType>> {
const protectedTypes = new Map<string, Set<LeaveType>>();
context.preferenceDemandByDate = new Map();
context.anyPreferenceDemandByDate = new Map();
const futureRules = rules.slice(startIndex);
for (const [offset, rule] of futureRules.entries()) {
if (!rule.enabled || rule.force !== 'preference' || rule.type === 'optimization') continue;
if (
rule.type === 'time_window' &&
declaredWindowDays(rule, context).length >= rule.placeDays
)
continue;
const priorityWeight = futureRules.length - offset;
const dates =
rule.type === 'time_window'
? context.workingDays.filter(
(date) =>
!context.declaredDates.has(date) &&
compareDate(date, rule.startDate!) >= 0 &&
compareDate(date, rule.endDate!) <= 0,
)
: occurrences(rule, context).flatMap((occurrence) => {
const patterns = patternsFor(rule, occurrence, context);
return patterns.some((pattern) =>
pattern.every((date) =>
declaredPatternDay(date, rule.placeType, context),
),
)
? []
: patterns.flat().filter((date) => !context.declaredDates.has(date));
});
for (const date of dates) {
context.preferenceDemandByDate.set(
date,
(context.preferenceDemandByDate.get(date) ?? 0) + priorityWeight,
);
if (rule.placeType === 'any') {
context.anyPreferenceDemandByDate.set(
date,
(context.anyPreferenceDemandByDate.get(date) ?? 0) + priorityWeight,
);
continue;
}
const types = protectedTypes.get(date) ?? new Set<LeaveType>();
types.add(rule.placeType);
protectedTypes.set(date, types);
}
}
return protectedTypes;
}
export function buildRequirements(
rules: NormalizedRule[],
context: SearchContext,
force: RuleForce,
): Requirement[] {
if (force === 'obligation' && rules === context.rules) {
const cached = obligationRequirementCache.get(context);
if (cached) return cached;
}
const requirements: Requirement[] = [];
let index = 0;
for (const rule of rules) {
if (!rule.enabled || rule.force !== force || rule.type === 'optimization') continue;
if (rule.type === 'time_window') {
const start =
compareDate(rule.startDate!, context.horizon.start) < 0
? context.horizon.start
: rule.startDate!;
const end =
compareDate(rule.endDate!, context.horizon.end) >= 0
? addDays(context.horizon.end, -1)
: rule.endDate!;
const candidates =
compareDate(start, end) <= 0
? context.workingDays.filter(
(date) =>
!context.declaredDates.has(date) &&
compareDate(date, start) >= 0 &&
compareDate(date, end) <= 0,
)
: [];
const orderedCandidates = candidates.sort(
(a, b) =>
preferenceDateConflictScore(rule.placeType, a, context) -
preferenceDateConflictScore(rule.placeType, b, context) ||
compareDate(a, b),
);
requirements.push({
rule,
requiredPlacements: rule.placeDays - declaredWindowDays(rule, context).length,
anchor: start,
index: index++,
candidates: orderedCandidates,
});
} else {
for (const occurrence of occurrences(rule, context)) {
const patterns = patternsFor(rule, occurrence, context).sort(
(a, b) =>
patternConflictScore(rule.placeType, a, context) -
patternConflictScore(rule.placeType, b, context) ||
compareDateLists(a, b),
);
requirements.push({
rule,
requiredPlacements: Math.min(
rule.placeDays,
...patterns.map(
(pattern) =>
pattern.filter(
(date) => !declaredPatternDay(date, rule.placeType, context),
).length,
),
),
anchor: occurrence,
occurrenceDate: occurrence,
index: index++,
patterns,
});
}
}
}
// IF_THEN occurrences are entitlement producers. Resolve them before a
// TIME_WINDOW consumer even when the window starts earlier; availability
// checks still prevent an earned balance from funding an earlier date, while
// this ordering keeps valid later chains visible to the joint search.
const ordered = requirements.sort(compareRequirements);
if (force === 'obligation' && rules === context.rules)
obligationRequirementCache.set(context, ordered);
return ordered;
}
export function compareRequirements(a: Requirement, b: Requirement): number {
return (
Number(a.rule.type !== 'if_then') - Number(b.rule.type !== 'if_then') ||
compareDate(a.anchor, b.anchor) ||
a.index - b.index
);
}
/**
* 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.
*/
export 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));
}
export function obligationBranchEstimate(requirements: Requirement[]): number {
let estimate = 1;
for (const requirement of requirements) {
let branches = requirement.patterns?.length ?? 1;
if (!requirement.patterns) {
const candidates = requirement.candidates?.length ?? 0;
const needed = requirement.requiredPlacements;
branches = 1;
for (let index = 1; index <= needed; index++) {
if (index > candidates) {
branches = 1;
break;
}
branches = Math.min(
EXACT_OBLIGATION_BRANCH_LIMIT + 1,
(branches * (candidates - needed + index)) / index,
);
}
}
estimate = Math.min(EXACT_OBLIGATION_BRANCH_LIMIT + 1, estimate * branches);
if (estimate > EXACT_OBLIGATION_BRANCH_LIMIT) return estimate;
}
return estimate;
}
function preferenceDateConflictScore(
selector: LeaveSelector,
date: string,
context: SearchContext,
): number {
const protectedTypes = context.protectedTypesByDate.get(date);
const demand = context.preferenceDemandByDate.get(date) ?? 0;
const anyDemand = context.anyPreferenceDemandByDate.get(date) ?? 0;
if (!protectedTypes?.size && !demand) return 0;
// An ANY preference should prefer a date protected by a later preference:
// sharing one compatible placement lets both lexicographic criteria win.
if (selector === 'any') return -(demand * 2 + (protectedTypes?.size ?? 0));
if (protectedTypes?.has(selector)) return -(demand * 2 + 1);
// An untyped future preference can share any leave type, while a typed
// future preference for another type must not be allowed to steal this slot.
if (protectedTypes?.size) return anyDemand ? -anyDemand : protectedTypes.size;
return demand ? -demand : 0;
}
export function patternConflictScore(
selector: LeaveSelector,
pattern: string[],
context: SearchContext,
): number {
return pattern.reduce(
(score, date) => score + preferenceDateConflictScore(selector, date, context),
0,
);
}
@@ -0,0 +1,174 @@
import type { normalizeRequest } from './normalize';
import type {
HolidayWeekCandidate,
LeaveSelector,
LeaveType,
PlanningCalendar,
PlanningReason,
PlanningSteps,
SearchContext,
} from './types';
import { frenchPublicHolidaysForYear } from '../declared-non-working-days';
import { addDays, compareDate, dateRange, utcDate } from '../plan-observations';
export function now(): number {
return typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now();
}
export function observeCallback(context: SearchContext, callback: () => void): void {
const started = now();
try {
callback();
} finally {
context.observerTime += now() - started;
}
}
export class DeadlineReached extends Error {}
export class UserCancelled extends Error {}
// ponytail: cap the number of feasible obligation branches ranked for a
// loaded year; replace with bounded branch-and-bound if mobile evidence shows
// that this ceiling misses a better lexicographic assignment.
export const OBLIGATION_SOLUTION_LIMIT = 4096;
export const EXACT_OBLIGATION_BRANCH_LIMIT = 10_000;
export function compareText(a: string, b: string): number {
return a < b ? -1 : a > b ? 1 : 0;
}
export function isWeekend(key: string): boolean {
const day = utcDate(key).getUTCDay();
return day === 0 || day === 6;
}
export function isWorking(key: string, holidays: Set<string>): boolean {
return !isWeekend(key) && !holidays.has(key);
}
function holidayWeekCandidates(context: SearchContext): HolidayWeekCandidate[] {
const candidates = new Map<string, HolidayWeekCandidate>();
const inHorizon = (date: string) => date >= context.horizon.start && date < context.horizon.end;
for (const holiday of [...context.holidays].sort(compareDate)) {
const weekday = utcDate(holiday).getUTCDay();
if (weekday < 1 || weekday > 5) continue;
const start = addDays(holiday, 1 - weekday);
const weekdays = dateRange(start, addDays(start, 5));
const dates = weekdays.filter((date) => isWorking(date, context.holidays));
if (
!dates.length ||
!dates.some(inHorizon) ||
(!inHorizon(holiday) && !dates.some((date) => context.declaredDates.has(date))) ||
dates.some((date) => !inHorizon(date) && !context.declaredDates.has(date))
)
continue;
const value = weekdays.reduce(
(sum, date, index) =>
sum + (context.holidays.has(date) ? Math.min(index + 1, 5 - index) : 0),
0,
);
candidates.set(start, { start, dates, value });
}
return [...candidates.values()].sort(
(a, b) => b.value - a.value || compareDate(a.start, b.start),
);
}
export function reason<Code extends string>(
code: Code,
message: string,
ruleIds?: string[],
): PlanningReason & { code: Code } {
return ruleIds?.length ? { code, message, ruleIds } : { code, message };
}
export function compareDateLists(a: readonly string[], b: readonly string[]): number {
for (let index = 0; index < Math.min(a.length, b.length); index++) {
const compared = compareDate(a[index], b[index]);
if (compared) return compared;
}
return a.length - b.length;
}
export function selectorMatches(selector: LeaveSelector, type: LeaveType): boolean {
return selector === 'any' || selector === type;
}
export function* prepareCalendar(
horizon: {
start: string;
end: string;
},
progress: () => void,
): PlanningSteps<PlanningCalendar> {
const start = addDays(horizon.start, -400);
const end = addDays(horizon.end, 400);
const holidays = new Set<string>();
for (let year = Number(start.slice(0, 4)); year <= Number(end.slice(0, 4)); year++) {
yield true;
for (const holiday of frenchPublicHolidaysForYear(year)) holidays.add(holiday);
progress();
}
const workingDays: string[] = [];
const calendarDays: string[] = [];
const calendarIndex = new Map<string, number>();
const workingCalendar = new Set<string>();
const workingPrefix = [0];
for (let date = start; compareDate(date, end) < 0; date = addDays(date, 1)) {
yield;
calendarIndex.set(date, calendarDays.length);
calendarDays.push(date);
const working = isWorking(date, holidays);
if (working) {
workingCalendar.add(date);
if (date >= horizon.start && date < horizon.end) workingDays.push(date);
}
workingPrefix.push(workingPrefix[workingPrefix.length - 1] + Number(working));
}
return { holidays, workingDays, calendarDays, calendarIndex, workingCalendar, workingPrefix };
}
export function createSearchContext(
normalized: ReturnType<typeof normalizeRequest>,
horizon: { start: string; end: string },
calendar: PlanningCalendar,
deadline = Number.POSITIVE_INFINITY,
started = 0,
): SearchContext {
const context: SearchContext = {
...calendar,
horizon,
holidayWeeks: [],
declaredDays: normalized.declaredDays,
declaredDates: new Set(normalized.declaredDays.map(({ date }) => date)),
initialBalances: normalized.balances,
rules: normalized.rules,
deadline,
started,
request: normalized.request,
nodes: 0,
check: () => undefined,
reservedTypes: new Set<LeaveType>(),
sharedTypesByDate: new Map<string, Set<LeaveType>>(),
protectedTypesByDate: new Map<string, Set<LeaveType>>(),
preferenceDemandByDate: new Map<string, number>(),
anyPreferenceDemandByDate: new Map<string, number>(),
observerTime: 0,
completedPreferenceStates: new Map<number, string>(),
};
context.holidayWeeks = holidayWeekCandidates(context);
return context;
}
/** The context for reading a finished plan (checkpoint explanation, date analysis): calendar built at once, no deadline. */
export function finishedPlanContext(
normalized: ReturnType<typeof normalizeRequest>,
horizon: { start: string; end: string },
): SearchContext {
const steps = prepareCalendar(horizon, () => undefined);
let step = steps.next();
while (!step.done) step = steps.next();
return createSearchContext(normalized, horizon, step.value);
}
@@ -0,0 +1,435 @@
import { declaredWindowDays, occurrences, patternsFor } from './patterns';
import { occurrenceSatisfied } from './placement';
import { buildRequirements } from './requirements';
import { reason, selectorMatches } from './search-context';
import type {
NormalizedCalendarRule,
NormalizedRule,
PlanningObjective,
PlanningObjectiveComparison,
PlanningObjectiveDelta,
PlanningObjectiveId,
PlanningObjectiveVector,
PlanningReason,
PreferenceResult,
SearchContext,
State,
} from './types';
import {
compareDate,
evaluateStateOptimization,
expiryTieKey,
optimizationBalanceObservations,
optimizationObservations,
placementTieKey,
} from '../plan-observations';
import {
compareObjectiveLists,
evaluateValidatedOptimization,
firstDifferentObjective,
type OptimizationObservations,
} from '../planning-objectives';
const preferencePatternCache = new WeakMap<
SearchContext,
Map<string, (readonly [occurrence: string, patterns: string[][]])[]>
>();
export 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'
);
}
export 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. */
export 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. */
export 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';
}
export function preferenceReason(
rule: NormalizedCalendarRule,
count: number,
context: SearchContext,
state: State,
): PlanningReason | undefined {
const requested = rule.type === 'if_then' ? occurrences(rule, context).length : rule.placeDays;
if (count >= requested) return undefined;
const candidateDates =
rule.type === 'time_window'
? context.workingDays.filter(
(date) =>
!context.declaredDates.has(date) &&
compareDate(date, rule.startDate!) >= 0 &&
compareDate(date, rule.endDate!) <= 0,
)
: occurrences(rule, context).flatMap((occurrence) =>
patternsFor(rule, occurrence, context).flat(),
);
if (!candidateDates.length)
return reason(
'horizon',
`Preference "${rule.name}" has no placeable date in the horizon.`,
[rule.id],
);
// Include generated balances: an earned entitlement is a real source for
// later preferences and must participate in both type and exhaustion reasons.
const matchingBalances = state.balances.filter((balance) =>
selectorMatches(rule.placeType, balance.type),
);
const availableBalances = matchingBalances.filter((balance) =>
candidateDates.some(
(date) =>
compareDate(balance.availableFrom, date) <= 0 &&
compareDate(date, balance.expiryDate) <= 0,
),
);
const currentRuleIndex = context.rules.findIndex((item) => item.id === rule.id);
const consumedByHigherPriority = matchingBalances.some(
(balance) =>
balance.remaining === 0 &&
[...state.placements.values()].some(
(placement) =>
placement.balanceId === balance.id &&
[...placement.ruleIds].some((id) => {
const index = context.rules.findIndex((item) => item.id === id);
return (
index >= 0 &&
(context.rules[index].force === 'obligation' ||
index < currentRuleIndex)
);
}),
),
);
const freeEligibleDate = candidateDates.some(
(date) =>
!state.placements.has(date) &&
state.balances.some(
(balance) =>
balance.remaining > 0 &&
selectorMatches(rule.placeType, balance.type) &&
compareDate(balance.availableFrom, date) <= 0 &&
compareDate(date, balance.expiryDate) <= 0,
),
);
const compatibleExisting = candidateDates.some((date) => {
const placement = state.placements.get(date);
return placement && selectorMatches(rule.placeType, placement.type);
});
const blockedByHigherPriority = candidateDates.some((date) => {
const placement = state.placements.get(date);
return (
placement &&
!selectorMatches(rule.placeType, placement.type) &&
[...placement.ruleIds].some((id) => {
const index = context.rules.findIndex((item) => item.id === id);
return (
index >= 0 &&
(context.rules[index].force === 'obligation' || index < currentRuleIndex)
);
})
);
});
let code: string;
if (blockedByHigherPriority && !freeEligibleDate && !compatibleExisting)
code = 'higher-priority';
else if (!matchingBalances.length && !compatibleExisting) code = 'type';
else if (!availableBalances.length) code = 'availability';
else if (consumedByHigherPriority && !freeEligibleDate && !compatibleExisting)
code = 'higher-priority';
else code = 'capacity';
return reason(code, `Preference "${rule.name}" could not be completely satisfied.`, [rule.id]);
}
export function preferenceStateKey(state: State): string {
// Preserve iteration order: a coordinated allocator may keep its first valid branch.
return JSON.stringify([
state.balances,
[...state.placements].map(([date, placement]) => [
date,
{ ...placement, ruleIds: [...placement.ruleIds] },
]),
state.earnedActivations,
]);
}
export function activeObjectiveVector(
state: State,
context: SearchContext,
throughIndex = Number.POSITIVE_INFINITY,
): PlanningObjective[] {
return [...activeObjectives(state, context, throughIndex)];
}
export function* activeObjectives(
state: State,
context: SearchContext,
throughIndex = Number.POSITIVE_INFINITY,
only?: ReadonlySet<PlanningObjectiveId>,
): Generator<PlanningObjective> {
let balances: OptimizationObservations | undefined;
let calendar: OptimizationObservations | undefined;
let index = 0;
for (const rule of context.rules) {
if (!rule.enabled || rule.force !== 'preference') continue;
if (index++ > throughIndex) return;
if (
only &&
!only.has(`${rule.type === 'optimization' ? 'optimization' : 'preference'}:${rule.id}`)
)
continue;
if (rule.type === 'optimization') {
const observations =
rule.configuration.elements === 'leave-balances'
? (balances ??= {
leaveBalances: optimizationBalanceObservations(state, context),
publicHolidayWeeks: [],
timeOffPeriods: [],
workSequences: [],
leavePlacements: [],
})
: (calendar ??= optimizationObservations(state, context));
yield {
id: `optimization:${rule.id}`,
direction: rule.configuration.direction,
value: evaluateStateOptimization(rule.configuration, state, context, observations),
label: rule.name,
};
} else {
yield {
id: `preference:${rule.id}`,
direction: 'maximize',
value: preferenceResult(rule, state, context).satisfied,
label: rule.name,
};
}
}
}
export function tieBreakObjectives(state: State, context: SearchContext): PlanningObjective[] {
return [
{
id: 'balance-expiry',
direction: 'minimize',
value: expiryTieKey(state),
label: 'Balance expiry tie-break',
},
{
id: 'placement-date',
direction: 'minimize',
value: placementTieKey(state, context),
label: 'Placement date tie-break',
},
];
}
export function obligationPreviewObjectives(
preview: { state: State },
context: SearchContext,
): PlanningObjective[] {
return [
...activeObjectiveVector(preview.state, context),
...tieBreakObjectives(preview.state, context),
];
}
/** Compare complete previews so obligation DFS does not commit to its first feasible branch. */
export function compareObligationPreviews(
a: { state: State },
b: { state: State },
context: SearchContext,
): number {
return compareObjectiveLists(
obligationPreviewObjectives(a, context),
obligationPreviewObjectives(b, context),
);
}
export function unsatisfiedObligationCount(state: State, context: SearchContext): number {
let unsatisfied = 0;
for (const requirement of buildRequirements(context.rules, context, 'obligation')) {
if (!requirement.patterns) {
let placed = 0;
for (const placement of state.placements.values())
if (placement.ruleIds.has(requirement.rule.id)) placed++;
if (placed !== requirement.requiredPlacements) unsatisfied++;
continue;
}
if (
!occurrenceSatisfied(
requirement.rule,
requirement.occurrenceDate!,
requirement.patterns,
state,
context,
)
)
unsatisfied++;
}
return unsatisfied;
}
export function objectiveVector(
state: State,
context: SearchContext,
active = activeObjectiveVector(state, context),
unsatisfiedObligations = unsatisfiedObligationCount(state, context),
): PlanningObjectiveVector {
return {
objectives: [
{
id: 'obligation-validity',
direction: 'minimize',
value: unsatisfiedObligations,
label: 'Unsatisfied obligations',
},
...active,
...tieBreakObjectives(state, context),
],
};
}
function sameObjectiveValue(a: number | string, b: number | string): boolean {
return a === b;
}
export function objectiveComparison(
before: PlanningObjectiveVector,
after: PlanningObjectiveVector,
): PlanningObjectiveComparison {
const delta: PlanningObjectiveDelta[] = after.objectives.map((objective, index) => {
const previous = before.objectives[index];
const value =
typeof objective.value === 'number' && typeof previous?.value === 'number'
? objective.value - previous.value
: sameObjectiveValue(objective.value, previous?.value ?? objective.value)
? 0
: null;
return {
id: objective.id,
direction: objective.direction,
value,
label: objective.label,
};
});
const first = firstDifferentObjective(after.objectives, before.objectives);
const decisive = first >= 0 ? after.objectives[first].id : undefined;
return {
before,
after,
delta,
firstDecisiveObjective: decisive,
tieBreak:
decisive === 'balance-expiry'
? 'balance-expiry'
: decisive === 'placement-date'
? 'placement-date'
: undefined,
};
}
export function preferenceResult(
rule: NormalizedCalendarRule,
state: State,
context: SearchContext,
): PreferenceResult {
if (rule.type === 'time_window') {
// Stops at the requested quantity: later placements cannot raise a capped count.
let satisfied = Math.min(rule.placeDays, declaredWindowDays(rule, context).length);
if (satisfied < rule.placeDays)
for (const placement of state.placements.values())
if (
placement.date >= rule.startDate! &&
placement.date <= rule.endDate! &&
selectorMatches(rule.placeType, placement.type) &&
++satisfied === rule.placeDays
)
break;
return { ruleId: rule.id, requested: rule.placeDays, satisfied, completeOccurrences: 0 };
}
let patternsByRule = preferencePatternCache.get(context);
if (!patternsByRule) {
patternsByRule = new Map(
context.rules
.filter(
(item): item is NormalizedCalendarRule =>
item.enabled && item.force === 'preference' && item.type === 'if_then',
)
.map((item) => [
item.id,
occurrences(item, context).map(
(occurrence) =>
[occurrence, patternsFor(item, occurrence, context)] as const,
),
]),
);
preferencePatternCache.set(context, patternsByRule);
}
const occurrencePatterns = patternsByRule.get(rule.id) ?? [];
const satisfied = occurrencePatterns.filter(([occurrence, patterns]) =>
occurrenceSatisfied(rule, occurrence, patterns, state, context),
).length;
return {
ruleId: rule.id,
requested: occurrencePatterns.length,
satisfied,
completeOccurrences: satisfied,
};
}
export function preferenceResultsForState(
state: State,
context: SearchContext,
): PreferenceResult[] {
return context.rules
.filter(
(rule): rule is NormalizedCalendarRule =>
rule.enabled && rule.force === 'preference' && rule.type !== 'optimization',
)
.map((rule) => preferenceResult(rule, state, context));
}
@@ -0,0 +1,76 @@
import { compareText } from './search-context';
import type { PlanningStateSnapshot, SearchContext, State } from './types';
import { compareDate, derivePlacements, removePlacement } from '../plan-observations';
export function copyPlacements(state: State): State['placements'] {
// Replacing a value while iterating keeps the Map's order and skips an intermediate array.
const copy = new Map(state.placements);
for (const [date, placement] of copy)
copy.set(date, { ...placement, ruleIds: new Set(placement.ruleIds) });
return copy;
}
export function cloneState(state: State): State {
const placements = copyPlacements(state);
derivePlacements(state.placements, placements);
return {
balances: state.balances.map((balance) => ({ ...balance })),
placements,
earnedActivations: state.earnedActivations.map((activation) => ({
...activation,
dates: [...activation.dates],
})),
};
}
export function planningStateSnapshot(state: State, context: SearchContext): PlanningStateSnapshot {
return {
calculationDate: context.request.calculationDate,
horizon: context.horizon,
...(context.declaredDays.length ? { declaredDays: context.declaredDays } : {}),
balances: state.balances.map((balance) => ({ ...balance })),
placements: [...state.placements.values()]
.sort((a, b) => compareDate(a.date, b.date) || compareText(a.balanceId, b.balanceId))
.map((placement) => ({
...placement,
ruleIds: [...placement.ruleIds].sort(),
})),
earnedActivations: state.earnedActivations.map((activation) => ({
...activation,
dates: [...activation.dates],
})),
};
}
export function releasePlacement(state: State, date: string): State {
// Removing a slot never edits surviving placements. Later assignments and
// metadata reconciliation still detach their placements before changing them.
const result: State = {
balances: state.balances.map((balance) => ({ ...balance })),
placements: new Map(state.placements),
earnedActivations: state.earnedActivations.map((activation) => ({
...activation,
dates: [...activation.dates],
})),
};
const placement = result.placements.get(date)!;
removePlacement(state.placements, result.placements, date);
result.balances.find((balance) => balance.id === placement.balanceId)!.remaining++;
return result;
}
export function stateFromPlanningSnapshot(state: PlanningStateSnapshot): State {
return {
balances: state.balances.map((balance) => ({ ...balance })),
placements: new Map(
state.placements.map((placement) => [
placement.date,
{ ...placement, ruleIds: new Set(placement.ruleIds) },
]),
),
earnedActivations: state.earnedActivations.map((activation) => ({
...activation,
dates: [...activation.dates],
})),
};
}
@@ -0,0 +1,550 @@
import type { DeclaredNonWorkingDay } from '../declared-non-working-days';
import type { OptimizationConfiguration } from '../planning-objectives';
/** Date-only values are serialized as YYYY-MM-DD at the planning boundary. */
export type PlanningDate = string;
export type LeaveType = 'cp' | 'rtt' | 'other';
export type LeaveSelector = LeaveType | 'any';
export type RuleForce = 'obligation' | 'preference';
export type PlacementMode = 'before' | 'after' | 'around' | 'auto';
export interface PlanningHorizon {
start: PlanningDate;
end: PlanningDate;
}
export interface LeaveBalanceInput {
id: string;
type: LeaveType | string;
quantity: number;
availableFrom?: PlanningDate;
expiryDate: PlanningDate;
name?: string;
label?: string;
}
export interface TimeWindowPlanningRule {
id: string;
name?: string;
type: 'time_window' | 'TIME_WINDOW' | string;
enabled?: boolean;
force?: RuleForce | string;
startDate: PlanningDate;
endDate: PlanningDate;
placeDays: number;
placeType: LeaveSelector | string;
}
export interface IfThenPlanningRule {
id: string;
name?: string;
type: 'if_then' | 'IF_THEN' | string;
enabled?: boolean;
force?: RuleForce | string;
dayOfWeek: number;
placeDays: number;
placeType: LeaveSelector | string;
placement: PlacementMode | string;
rewardDays: number;
rewardType?: LeaveType | string;
/** Days of the requested leave type that must remain on the occurrence date; absent means 0. */
reserveDays?: number;
}
export interface OptimizationPlanningRule {
id: string;
name?: string;
type: 'optimization';
enabled?: boolean;
force?: 'preference';
configuration: OptimizationConfiguration;
}
export type PlanningRule = TimeWindowPlanningRule | IfThenPlanningRule | OptimizationPlanningRule;
export interface PlanningRequest {
horizon: PlanningHorizon;
balances: readonly LeaveBalanceInput[];
rules: readonly PlanningRule[];
declaredDays?: readonly DeclaredNonWorkingDay[];
/** Optional caller-owned display identities copied into a calculation snapshot. */
identities?: Readonly<Record<string, string>>;
/** Optional caller-owned human-readable labels copied into a calculation snapshot. */
labels?: Readonly<Record<string, string>>;
/** Opt-in planning-work budget in milliseconds; omitted means run until completion or cancellation. */
deadlineMs?: number;
/** Read by the planning service only, which strips it before a job; the engine reports stages through `emit`. */
progress?: (stage: string) => void;
}
/** A planning request as a job carries it to the planner: data only, dated by its calculation. */
export type SubmittedRequest = Omit<PlanningRequest, 'progress'> & { calculationDate?: string };
export interface PlanningReason {
code: string;
message: string;
ruleIds?: string[];
reserve?: Readonly<{ occurrence: string; remaining: number; required: number }>;
}
export interface InvalidInputOutcome {
kind: 'InvalidInput';
calculationDate?: string;
reasons: PlanningReason[];
}
export interface PlanningConflictOutcome {
kind: 'PlanningConflict';
calculationDate?: string;
reasons: PlanningReason[];
conflictingRuleIds: string[];
}
export type RemainingClassification = 'unavoidable-expiry' | 'at-risk' | 'deferred';
export interface RemainingBalance {
id: string;
type: LeaveType;
quantity: number;
availableFrom: string;
expiryDate: string;
classification: RemainingClassification;
reason: PlanningReason;
earned: boolean;
sourceRuleId?: string;
}
export interface LeavePlacement {
date: string;
balanceId: string;
type: LeaveType;
ruleIds: string[];
supporting: boolean;
}
export interface TimeOffPeriod {
start: string;
end: string;
duration: number;
placementDates: string[];
declaredDates?: string[];
nonWorkingDates: string[];
nonWorkingDayGain: number;
}
export interface TimeWindowContribution {
ruleId: string;
label: string;
requested: number;
declaredDays: readonly DeclaredNonWorkingDay[];
placementDates: readonly string[];
}
export interface IfThenContribution extends TimeWindowContribution {
occurrence: string;
earnedEntitlement?: Readonly<{
id: string;
type: LeaveType;
quantity: number;
availableFrom: string;
expiryDate: string;
added: boolean;
}>;
}
/** An occurrence whose IF_THEN reserve kept the displayed plan from earning its day. */
export interface IfThenReservePrevention {
ruleId: string;
occurrence: string;
/** The reserve's balances remaining on the occurrence date, or that the plan would leave with the pattern placed. */
remaining: number;
required: number;
patternInPlace: boolean;
}
export interface PreferenceResult {
ruleId: string;
requested: number;
satisfied: number;
completeOccurrences: number;
reason?: PlanningReason;
}
export type PlanningObjectiveId =
| 'obligation-validity'
| 'unplaced-at-risk'
| `preference:${string}`
| `optimization:${string}`
| 'holiday-week-value'
| 'non-working-day-gain'
| 'longest-work-sequence'
| 'short-sequence-deficit'
| 'supporting-placements'
| 'balance-expiry'
| 'placement-date';
export interface PlanningObjective {
id: PlanningObjectiveId;
direction: 'minimize' | 'maximize';
value: number | string;
label?: string;
}
/** The real ordered objective values. It deliberately has no scalar score. */
export interface PlanningObjectiveVector {
objectives: readonly PlanningObjective[];
}
export interface PlanningObjectiveDelta {
id: PlanningObjectiveId;
direction: 'minimize' | 'maximize';
value: number | string | null;
label?: string;
}
export interface PlanningObjectiveComparison {
before: PlanningObjectiveVector;
after: PlanningObjectiveVector;
delta: readonly PlanningObjectiveDelta[];
firstDecisiveObjective?: PlanningObjectiveId;
tieBreak?: 'balance-expiry' | 'placement-date';
}
export interface PlacementContribution {
kind: 'entitlement' | 'rule' | 'at-risk' | 'supporting' | 'time-off-period' | 'metric';
code: string;
label: string;
ruleId?: string;
value?: number;
dates?: readonly string[];
}
export interface PlacementExplanation {
placement: LeavePlacement;
balance?: Readonly<LeaveBalanceInput>;
ruleIds: readonly string[];
supporting: boolean;
timeOffPeriod?: TimeOffPeriod;
remainingBalance?: RemainingBalance;
remainingQuantity: number;
contributions: readonly PlacementContribution[];
finalMetrics: PlanningMetrics;
objectiveVector: PlanningObjectiveVector;
/** The final-plan comparison with this placement removed and restored here. */
comparison: PlanningObjectiveComparison;
firstDecisiveObjective?: PlanningObjectiveId;
}
export interface PlanExplanation {
kind: 'PlanExplanation';
calculationDate?: string;
declaredDays?: readonly DeclaredNonWorkingDay[];
timeOffPeriods?: readonly TimeOffPeriod[];
timeWindowContributions?: readonly TimeWindowContribution[];
ifThenContributions?: readonly IfThenContribution[];
placements: readonly PlacementExplanation[];
/** Present when the explained plan is the incumbent of an interrupted calculation. */
incomplete?: IncompleteExplanation;
}
export interface ConflictExplanation {
kind: 'ConflictExplanation';
calculationDate?: string;
conflictingRules: readonly Readonly<{ id: string; label: string }>[];
bottleneck: PlanningReason;
}
export interface IncompleteExplanation {
kind: 'IncompleteExplanation';
calculationDate?: string;
reason: InterruptionReason;
completedStages: readonly string[];
uncompletedStages: readonly string[];
}
export type PlanningExplanation = PlanExplanation | ConflictExplanation | IncompleteExplanation;
export interface PlanningSnapshot {
calculationDate?: string;
declaredDays?: readonly DeclaredNonWorkingDay[];
horizon: Readonly<{ start: string; end: string }>;
balances: readonly Readonly<LeaveBalanceInput>[];
rules: readonly Readonly<PlanningRule>[];
identities: Readonly<Record<string, string>>;
labels: Readonly<Record<string, string>>;
}
export interface PlanningStateSnapshot {
calculationDate?: string;
declaredDays?: readonly DeclaredNonWorkingDay[];
horizon: Readonly<{ start: string; end: string }>;
balances: readonly Readonly<{
id: string;
type: LeaveType;
quantity: number;
remaining: number;
availableFrom: string;
expiryDate: string;
earned: boolean;
sourceRuleId?: string;
}>[];
placements: readonly LeavePlacement[];
earnedActivations: readonly Readonly<{
id: string;
ruleId: string;
occurrence: string;
dates: readonly string[];
}>[];
}
export interface PlanningArtifactTimings {
planningWorkMs: number;
}
export type CounterfactualReasonCode =
| 'non-working'
| 'declared-day'
| 'occupied'
| 'unavailable'
| 'expired'
| 'type-incompatible'
| 'rule-invalid';
export interface CounterfactualDateResult {
date: string;
status: 'eligible' | 'ineligible';
reason?: PlanningReason & { code: CounterfactualReasonCode };
comparison?: PlanningObjectiveComparison;
}
export interface CounterfactualAnalysis {
kind: 'Counterfactual';
calculationId: string;
placement: LeavePlacement;
hypothetical: true;
baseline: PlanningObjectiveVector;
results: readonly CounterfactualDateResult[];
}
export interface StaleCounterfactualAnalysis {
kind: 'CounterfactualStale';
calculationId: string;
placement: LeavePlacement;
hypothetical: true;
results: readonly [];
}
export type CounterfactualSelection = LeavePlacement | string;
export interface PlanningMetrics {
unplacedAtRisk: number;
holidayWeekValue: number;
nonWorkingDayGain: number;
longestWorkSequence: number;
averageWorkSequence: number | null;
averageTimeOffPeriod: number | null;
longestTimeOffPeriod: number | null;
shortSequenceDeficit: number;
supportingPlacements: number;
preferenceSatisfaction: number[];
}
export interface PlanOutcome {
kind: 'Plan';
calculationDate?: string;
declaredDays?: readonly DeclaredNonWorkingDay[];
timeWindowContributions?: readonly TimeWindowContribution[];
ifThenContributions?: readonly IfThenContribution[];
ifThenReservePreventions?: readonly IfThenReservePrevention[];
horizon: { start: string; end: string };
placements: LeavePlacement[];
timeOffPeriods: TimeOffPeriod[];
preferences: PreferenceResult[];
remainingBalances: RemainingBalance[];
metrics: PlanningMetrics;
completedStages: string[];
lastCompletedStage: string;
}
export type InterruptionReasonCode =
| 'user-cancelled'
| 'stale-calculation'
| 'connection-lost'
| 'worker-error'
| 'worker-unavailable'
| 'planner-error'
| 'explanation-error'
| 'deadline';
export type InterruptionReason = PlanningReason & { code: InterruptionReasonCode };
export interface PlanningIncompleteOutcome {
kind: 'PlanningIncomplete';
calculationDate?: string;
incumbent?: PlanOutcome;
completedStages: string[];
lastCompletedStage?: string;
reasons: InterruptionReason[];
}
export type PlanningOutcome =
| InvalidInputOutcome
| PlanningConflictOutcome
| PlanningIncompleteOutcome
| PlanOutcome;
export interface NormalizedBalance {
id: string;
type: LeaveType;
quantity: number;
availableFrom: string;
expiryDate: string;
earned: boolean;
sourceRuleId?: string;
}
interface NormalizedBaseRule {
id: string;
name: string;
enabled: boolean;
force: RuleForce;
}
export interface NormalizedCalendarRule extends NormalizedBaseRule {
type: 'time_window' | 'if_then';
placeDays: number;
placeType: LeaveSelector;
startDate?: string;
endDate?: string;
dayOfWeek?: number;
placement?: PlacementMode;
rewardDays?: number;
rewardType?: LeaveType;
reserveDays?: number;
}
export interface NormalizedOptimizationRule extends NormalizedBaseRule {
type: 'optimization';
force: 'preference';
configuration: OptimizationConfiguration;
}
export type NormalizedRule = NormalizedCalendarRule | NormalizedOptimizationRule;
export interface InternalBalance extends NormalizedBalance {
remaining: number;
}
export interface InternalPlacement {
date: string;
balanceId: string;
type: LeaveType;
ruleIds: Set<string>;
supporting: boolean;
}
export interface EarnedActivation {
id: string;
ruleId: string;
occurrence: string;
dates: string[];
}
export interface State {
balances: InternalBalance[];
placements: Map<string, InternalPlacement>;
earnedActivations: EarnedActivation[];
}
/** What the planner reads from a request once validation has normalized it. */
export type ValidatedRequest = Pick<
PlanningRequest,
'balances' | 'identities' | 'labels' | 'deadlineMs'
> & { calculationDate: string };
export interface Requirement {
rule: NormalizedCalendarRule;
requiredPlacements: number;
anchor: string;
index: number;
occurrenceDate?: string;
optional?: boolean;
patterns?: string[][];
candidates?: string[];
}
export interface SearchContext {
declaredDays: readonly DeclaredNonWorkingDay[];
declaredDates: ReadonlySet<string>;
horizon: { start: string; end: string };
holidays: Set<string>;
holidayWeeks: HolidayWeekCandidate[];
calendarDays: string[];
calendarIndex: Map<string, number>;
workingCalendar: Set<string>;
workingPrefix: number[];
workingDays: string[];
initialBalances: NormalizedBalance[];
rules: NormalizedRule[];
deadline: number;
started: number;
request: ValidatedRequest;
emit?: PlanningEmit;
nodes: number;
check: () => void;
reservedTypes: Set<LeaveType>;
sharedTypesByDate: Map<string, Set<LeaveType>>;
protectedTypesByDate: Map<string, Set<LeaveType>>;
preferenceDemandByDate: Map<string, number>;
anyPreferenceDemandByDate: Map<string, number>;
observerTime: number;
completedPreferenceStates: Map<number, string>;
completedGenericState?: string;
/** A supplied vector was evaluated after reconciling earned entitlement dates. */
retain?: (state: State, vector?: PlanningObjectiveVector) => void;
}
export type PlanningCalendar = Pick<
SearchContext,
| 'holidays'
| 'workingDays'
| 'calendarDays'
| 'calendarIndex'
| 'workingCalendar'
| 'workingPrefix'
>;
// A true value asks the asynchronous driver to pause immediately at a phase boundary.
export type PlanningSteps<T> = Generator<boolean | undefined, T, void>;
export interface HolidayWeekCandidate {
start: string;
dates: string[];
value: number;
}
export interface PlanningArtifacts {
explanation?: PlanningExplanation;
finalState?: PlanningStateSnapshot;
explanationError?: InterruptionReason;
timings?: PlanningArtifactTimings;
}
/** What a calculation reports, in order: progress and checkpoints, then exactly one result, at most one explanation, and exactly one artifacts, last. */
export type PlanningEvent =
| { type: 'progress'; stage: string }
| { type: 'checkpoint'; plan: PlanOutcome; state?: PlanningStateSnapshot }
| { type: 'result'; outcome: PlanningOutcome }
| {
type: 'explanation';
explanation?: PlanningExplanation;
explanationError?: InterruptionReason;
finalState?: PlanningStateSnapshot;
}
| { type: 'artifacts'; artifacts: PlanningArtifacts };
export type PlanningEmit = (event: PlanningEvent) => void;
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff. Show more