@enyo-energy/energy-app-sdk 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +245 -5
  2. package/dist/cjs/energy-app-package-definition.cjs +1 -0
  3. package/dist/cjs/energy-app-package-definition.d.cts +1 -0
  4. package/dist/cjs/energy-app-permission.type.cjs +2 -0
  5. package/dist/cjs/energy-app-permission.type.d.cts +3 -1
  6. package/dist/cjs/energy-app.cjs +22 -0
  7. package/dist/cjs/energy-app.d.cts +21 -0
  8. package/dist/cjs/enyo-energy-app-sdk.d.cts +3 -0
  9. package/dist/cjs/implementations/appliances/appliance-manager.cjs +6 -0
  10. package/dist/cjs/implementations/pricing/compose-electricity-prices.cjs +255 -0
  11. package/dist/cjs/implementations/pricing/compose-electricity-prices.d.cts +125 -0
  12. package/dist/cjs/implementations/pricing/price-component-validators.cjs +238 -0
  13. package/dist/cjs/implementations/pricing/price-component-validators.d.cts +57 -0
  14. package/dist/cjs/implementations/pricing/price-schedule-resolver.cjs +182 -0
  15. package/dist/cjs/implementations/pricing/price-schedule-resolver.d.cts +95 -0
  16. package/dist/cjs/index.cjs +7 -0
  17. package/dist/cjs/index.d.cts +7 -0
  18. package/dist/cjs/packages/energy-app-charge.d.cts +8 -81
  19. package/dist/cjs/packages/energy-app-electricity-tariff.d.cts +153 -41
  20. package/dist/cjs/packages/energy-app-grid-fee.cjs +2 -0
  21. package/dist/cjs/packages/energy-app-grid-fee.d.cts +199 -0
  22. package/dist/cjs/packages/energy-app-modbus.d.cts +12 -0
  23. package/dist/cjs/types/enyo-charge.d.cts +0 -71
  24. package/dist/cjs/types/enyo-data-bus-value.d.cts +7 -0
  25. package/dist/cjs/types/enyo-electricity-tariff.cjs +73 -13
  26. package/dist/cjs/types/enyo-electricity-tariff.d.cts +260 -50
  27. package/dist/cjs/types/enyo-energy-prices.d.cts +9 -3
  28. package/dist/cjs/types/enyo-grid-fee.cjs +26 -0
  29. package/dist/cjs/types/enyo-grid-fee.d.cts +247 -0
  30. package/dist/cjs/types/enyo-price-composition.cjs +15 -0
  31. package/dist/cjs/types/enyo-price-composition.d.cts +147 -0
  32. package/dist/cjs/types/enyo-price-schedule.cjs +45 -0
  33. package/dist/cjs/types/enyo-price-schedule.d.cts +137 -0
  34. package/dist/cjs/version.cjs +1 -1
  35. package/dist/cjs/version.d.cts +1 -1
  36. package/dist/energy-app-package-definition.d.ts +1 -0
  37. package/dist/energy-app-package-definition.js +1 -0
  38. package/dist/energy-app-permission.type.d.ts +3 -1
  39. package/dist/energy-app-permission.type.js +2 -0
  40. package/dist/energy-app.d.ts +21 -0
  41. package/dist/energy-app.js +22 -0
  42. package/dist/enyo-energy-app-sdk.d.ts +3 -0
  43. package/dist/implementations/appliances/appliance-manager.js +6 -0
  44. package/dist/implementations/pricing/compose-electricity-prices.d.ts +125 -0
  45. package/dist/implementations/pricing/compose-electricity-prices.js +248 -0
  46. package/dist/implementations/pricing/price-component-validators.d.ts +57 -0
  47. package/dist/implementations/pricing/price-component-validators.js +230 -0
  48. package/dist/implementations/pricing/price-schedule-resolver.d.ts +95 -0
  49. package/dist/implementations/pricing/price-schedule-resolver.js +175 -0
  50. package/dist/index.d.ts +7 -0
  51. package/dist/index.js +7 -0
  52. package/dist/packages/energy-app-charge.d.ts +8 -81
  53. package/dist/packages/energy-app-electricity-tariff.d.ts +153 -41
  54. package/dist/packages/energy-app-grid-fee.d.ts +199 -0
  55. package/dist/packages/energy-app-grid-fee.js +1 -0
  56. package/dist/packages/energy-app-modbus.d.ts +12 -0
  57. package/dist/types/enyo-charge.d.ts +0 -71
  58. package/dist/types/enyo-data-bus-value.d.ts +7 -0
  59. package/dist/types/enyo-electricity-tariff.d.ts +260 -50
  60. package/dist/types/enyo-electricity-tariff.js +71 -11
  61. package/dist/types/enyo-energy-prices.d.ts +9 -3
  62. package/dist/types/enyo-grid-fee.d.ts +247 -0
  63. package/dist/types/enyo-grid-fee.js +23 -0
  64. package/dist/types/enyo-price-composition.d.ts +147 -0
  65. package/dist/types/enyo-price-composition.js +12 -0
  66. package/dist/types/enyo-price-schedule.d.ts +137 -0
  67. package/dist/types/enyo-price-schedule.js +42 -0
  68. package/dist/version.d.ts +1 -1
  69. package/dist/version.js +1 -1
  70. package/package.json +2 -2
@@ -0,0 +1,248 @@
1
+ import { EnyoPriceComponentEnum } from '../../types/enyo-electricity-tariff.js';
2
+ import { EnyoPriceComponentOriginEnum, } from '../../types/enyo-price-composition.js';
3
+ import { EnyoPriceAppliesToEnum } from '../../types/enyo-price-schedule.js';
4
+ import { resolvePriceSchedule } from './price-schedule-resolver.js';
5
+ /**
6
+ * Adapts a tariff price series from `useElectricityPrices().getPrices()` into
7
+ * composer input.
8
+ *
9
+ * @param entries - Price entries as returned by the electricity prices API
10
+ * @param direction - Which price to take; defaults to consumption. Feed-in
11
+ * entries without a `feedInPricePerKwh` are skipped.
12
+ * @returns Composable energy price entries
13
+ */
14
+ export function fromEnergyPriceEntries(entries, direction = EnyoPriceAppliesToEnum.Consumption) {
15
+ if (direction === EnyoPriceAppliesToEnum.FeedIn) {
16
+ return entries
17
+ .filter(entry => entry.feedInPricePerKwh !== undefined)
18
+ .map(entry => ({ timestampIso: entry.timestampIso, pricePerKwh: entry.feedInPricePerKwh }));
19
+ }
20
+ return entries.map(entry => ({
21
+ timestampIso: entry.timestampIso,
22
+ pricePerKwh: entry.consumptionPricePerKwh,
23
+ }));
24
+ }
25
+ /**
26
+ * Converts a grid fee series from `useGridFee().getGridFeeValues()` into the
27
+ * unit the composer works in.
28
+ *
29
+ * This is the **only** place cent meets currency in the pricing path, and it
30
+ * exists so the conversion happens once, visibly, instead of at every call site.
31
+ * Grid fees are published and read as gross **cent** per kWh because that is how
32
+ * they are quoted and configured; energy prices are in whole currency units
33
+ * (EUR/kWh), so a fee added to a price without dividing by 100 overstates it by
34
+ * a factor of 100 — a mistake that survives review because both numbers look
35
+ * plausible.
36
+ *
37
+ * Pass the result as {@link EnyoComposeElectricityPricesInput.gridFees}. Whether
38
+ * the amounts include the fee's additional charges is decided when the series is
39
+ * fetched, not here.
40
+ *
41
+ * @param series - The series returned by `getGridFeeValues()`, or `null`
42
+ * @returns The same series with amounts in currency per kWh, or `null` when the input was
43
+ */
44
+ export function fromGridFeeEntries(series) {
45
+ if (series == null) {
46
+ return null;
47
+ }
48
+ return {
49
+ appliesTo: series.appliesTo,
50
+ entries: series.entries.map(entry => ({
51
+ timestampIso: entry.timestampIso,
52
+ feePerKwh: entry.grossCentPerKwh / 100,
53
+ })),
54
+ };
55
+ }
56
+ /**
57
+ * Adapts an EPEX SPOT day-ahead series into composer input.
58
+ *
59
+ * Spot prices are the raw exchange result and contain neither grid fees nor
60
+ * levies, taxes or supplier margin — so a series built from them should declare
61
+ * no included components at all.
62
+ *
63
+ * @param entries - Spot price entries as returned by the EPEX SPOT price API
64
+ * @returns Composable energy price entries
65
+ */
66
+ export function fromEpexSpotEntries(entries) {
67
+ return entries.map(entry => ({ timestampIso: entry.timestampIso, pricePerKwh: entry.pricePerKwh }));
68
+ }
69
+ function appliesToDirection(componentAppliesTo, direction) {
70
+ return componentAppliesTo === EnyoPriceAppliesToEnum.Both || componentAppliesTo === direction;
71
+ }
72
+ /**
73
+ * Resolves a tariff's bonuses over a time range and combines them per interval
74
+ * according to the SDK's stacking rule.
75
+ *
76
+ * **Stacking rule:** overlapping bonuses add up, unless at least one bonus
77
+ * covering the interval is {@link EnyoTariffBonus.exclusive} — then the
78
+ * exclusive bonus with the highest `priority` applies alone (ties are broken by
79
+ * array order). Bonuses whose `appliesTo` does not match the requested
80
+ * direction, and intervals outside a bonus's validity window, contribute
81
+ * nothing.
82
+ *
83
+ * @param bonuses - The tariff's bonuses
84
+ * @param options - Range and direction to resolve for
85
+ * @returns A map from interval start (ISO) to the total discount and the contributing bonus ids
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * const resolved = resolveTariffBonuses(tariff.bonuses ?? [], {
90
+ * fromIso: '2026-09-02T00:00:00Z',
91
+ * untilIso: '2026-09-03T00:00:00Z',
92
+ * });
93
+ * ```
94
+ */
95
+ export function resolveTariffBonuses(bonuses, options) {
96
+ const direction = options.appliesTo ?? EnyoPriceAppliesToEnum.Consumption;
97
+ const resolved = bonuses
98
+ .filter(bonus => appliesToDirection(bonus.appliesTo, direction))
99
+ .map(bonus => {
100
+ const entries = resolvePriceSchedule(bonus.schedule, {
101
+ fromIso: options.fromIso,
102
+ untilIso: options.untilIso,
103
+ timezone: bonus.timezone,
104
+ validFromIso: bonus.validFromIso,
105
+ validUntilIso: bonus.validUntilIso,
106
+ });
107
+ const amountByTimestamp = new Map();
108
+ for (const entry of entries) {
109
+ if (entry.amountPerKwh > 0) {
110
+ amountByTimestamp.set(entry.timestampIso, entry.amountPerKwh);
111
+ }
112
+ }
113
+ return { bonus, amountByTimestamp };
114
+ });
115
+ const timestamps = new Set();
116
+ for (const candidate of resolved) {
117
+ for (const timestampIso of candidate.amountByTimestamp.keys()) {
118
+ timestamps.add(timestampIso);
119
+ }
120
+ }
121
+ const combined = new Map();
122
+ for (const timestampIso of timestamps) {
123
+ const active = resolved.filter(candidate => candidate.amountByTimestamp.has(timestampIso));
124
+ const exclusive = active.filter(candidate => candidate.bonus.exclusive === true);
125
+ if (exclusive.length > 0) {
126
+ const winner = exclusive.reduce((best, candidate) => (candidate.bonus.priority ?? 0) > (best.bonus.priority ?? 0) ? candidate : best);
127
+ combined.set(timestampIso, {
128
+ bonusPerKwh: winner.amountByTimestamp.get(timestampIso),
129
+ appliedBonusIds: [winner.bonus.id],
130
+ });
131
+ continue;
132
+ }
133
+ combined.set(timestampIso, {
134
+ bonusPerKwh: active.reduce((sum, candidate) => sum + candidate.amountByTimestamp.get(timestampIso), 0),
135
+ appliedBonusIds: active.map(candidate => candidate.bonus.id),
136
+ });
137
+ }
138
+ return combined;
139
+ }
140
+ function gridFeeByTimestamp(series) {
141
+ const map = new Map();
142
+ for (const entry of series?.entries ?? []) {
143
+ map.set(entry.timestampIso, entry.feePerKwh);
144
+ }
145
+ return map;
146
+ }
147
+ /**
148
+ * Composes the effective electricity price per 15-minute interval from an energy
149
+ * price series, a grid fee and a tariff's bonuses.
150
+ *
151
+ * The three inputs come from three independent sources and are deliberately not
152
+ * coupled: energy prices from the tariff or the spot market, the grid fee from
153
+ * `useGridFee()`, the bonuses from the tariff. Pass whichever apply.
154
+ *
155
+ * This runs **in the energy app**, never in the host, because only the app knows
156
+ * what its provider's API already returns: some providers deliver all-in prices
157
+ * with the network charge baked in, others deliver the pure energy price. Pass
158
+ * the price series' `includes` as `energyPriceComposition` and the composer
159
+ * reports each component without adding one that is already included.
160
+ *
161
+ * Every component is reported separately — `gridFeePerKwh` with its
162
+ * {@link EnyoPriceComponentOriginEnum}, the total `bonusPerKwh` and the
163
+ * `appliedBonusIds` behind it — so a UI can explain the number and an optimizer
164
+ * can reason about the parts.
165
+ *
166
+ * Entries are produced for the intervals present in `energyPrices`; grid fee and
167
+ * bonus values are matched by `timestampIso`, and an interval without a matching
168
+ * fee or bonus simply contributes `0`.
169
+ *
170
+ * @param input - Energy prices, what they already include, the grid fee and the bonuses
171
+ * @returns Composed entries in the order of the input energy prices
172
+ *
173
+ * @example
174
+ * ```typescript
175
+ * const series = await energyApp.useElectricityTariff().getPrices(direction, {fromIso, untilIso});
176
+ * const fees = await energyApp.useGridFee().getGridFeeValues({fromIso, untilIso});
177
+ * const spot = await energyApp.useEpexSpotPrices().getPrices({fromIso, untilIso});
178
+ *
179
+ * const prices = composeElectricityPrices({
180
+ * energyPrices: fromEpexSpotEntries(spot.entries),
181
+ * energyPriceComposition: series?.includes,
182
+ * gridFees: fees,
183
+ * bonuses: myBonuses,
184
+ * currency: 'EUR',
185
+ * });
186
+ *
187
+ * const cheapest = prices.reduce((a, b) => (b.effectivePricePerKwh < a.effectivePricePerKwh ? b : a));
188
+ * ```
189
+ */
190
+ export function composeElectricityPrices(input) {
191
+ const direction = input.appliesTo ?? EnyoPriceAppliesToEnum.Consumption;
192
+ const gridFeeIncluded = input.energyPriceComposition?.includes(EnyoPriceComponentEnum.GridFee) === true;
193
+ const bonusesIncluded = input.energyPriceComposition?.includes(EnyoPriceComponentEnum.Bonuses) === true;
194
+ const gridFeeSeriesApplies = input.gridFees != null && appliesToDirection(input.gridFees.appliesTo, direction);
195
+ const resolvedGridFees = gridFeeSeriesApplies ? gridFeeByTimestamp(input.gridFees) : new Map();
196
+ const constantGridFee = !gridFeeSeriesApplies && input.constantGridFeePerKwh !== undefined ? input.constantGridFeePerKwh : undefined;
197
+ const hasGridFeeSource = gridFeeSeriesApplies || constantGridFee !== undefined;
198
+ const range = {
199
+ fromIso: input.energyPrices[0]?.timestampIso,
200
+ untilIso: input.energyPrices[input.energyPrices.length - 1]?.timestampIso,
201
+ };
202
+ const resolvedBonuses = input.bonuses === undefined || input.bonuses.length === 0 || range.fromIso === undefined
203
+ ? new Map()
204
+ : resolveTariffBonuses(input.bonuses, {
205
+ fromIso: range.fromIso,
206
+ // The last entry starts the final interval, so extend past it.
207
+ untilIso: new Date(Date.parse(range.untilIso) + 1).toISOString(),
208
+ appliesTo: direction,
209
+ });
210
+ return input.energyPrices.map(entry => {
211
+ const gridFeePerKwh = hasGridFeeSource
212
+ ? constantGridFee ?? resolvedGridFees.get(entry.timestampIso) ?? 0
213
+ : 0;
214
+ const gridFeeOrigin = !hasGridFeeSource
215
+ ? EnyoPriceComponentOriginEnum.NotApplicable
216
+ : gridFeeIncluded
217
+ ? EnyoPriceComponentOriginEnum.Included
218
+ : EnyoPriceComponentOriginEnum.Added;
219
+ const bonus = resolvedBonuses.get(entry.timestampIso);
220
+ const bonusPerKwh = bonus?.bonusPerKwh ?? 0;
221
+ const bonusOrigin = bonus === undefined
222
+ ? EnyoPriceComponentOriginEnum.NotApplicable
223
+ : bonusesIncluded
224
+ ? EnyoPriceComponentOriginEnum.Included
225
+ : EnyoPriceComponentOriginEnum.Added;
226
+ let effectivePricePerKwh = entry.pricePerKwh;
227
+ if (gridFeeOrigin === EnyoPriceComponentOriginEnum.Added) {
228
+ effectivePricePerKwh += gridFeePerKwh;
229
+ }
230
+ if (bonusOrigin === EnyoPriceComponentOriginEnum.Added) {
231
+ effectivePricePerKwh -= bonusPerKwh;
232
+ }
233
+ if (input.minEffectivePricePerKwh !== undefined) {
234
+ effectivePricePerKwh = Math.max(effectivePricePerKwh, input.minEffectivePricePerKwh);
235
+ }
236
+ return {
237
+ timestampIso: entry.timestampIso,
238
+ energyPricePerKwh: entry.pricePerKwh,
239
+ gridFeePerKwh,
240
+ gridFeeOrigin,
241
+ bonusPerKwh,
242
+ bonusOrigin,
243
+ appliedBonusIds: bonus?.appliedBonusIds ?? [],
244
+ effectivePricePerKwh,
245
+ currency: input.currency,
246
+ };
247
+ });
248
+ }
@@ -0,0 +1,57 @@
1
+ import { EnyoTariffBonus } from '../../types/enyo-electricity-tariff.js';
2
+ import { EnyoDynamicGridFeeRegistration } from '../../types/enyo-grid-fee.js';
3
+ import { EnyoPriceSchedule } from '../../types/enyo-price-schedule.js';
4
+ /**
5
+ * Thrown when a grid fee, tariff bonus or price schedule violates one of the
6
+ * invariants enforced by this module. The message names the offending field or
7
+ * window index so callers can surface it directly to the user.
8
+ */
9
+ export declare class PriceComponentValidationError extends Error {
10
+ constructor(message: string);
11
+ }
12
+ /**
13
+ * Validates a {@link EnyoPriceSchedule}. Throws on the first violation.
14
+ *
15
+ * Enforces finite, non-negative amounts, well-formed `HH:mm` times, day and
16
+ * month ranges, ordered absolute windows, and that no two windows which can
17
+ * occur on the same day overlap in time — an overlap would make the resolved
18
+ * amount depend on array order rather than on the schedule itself.
19
+ *
20
+ * Overlap detection for recurring windows is conservative: two windows are only
21
+ * compared when their day-of-week and month sets can intersect. A window that
22
+ * wraps past midnight is compared on both of its legs.
23
+ *
24
+ * @param schedule - The schedule to validate
25
+ * @param label - Prefix used in error messages, e.g. `'gridFee.schedule'`
26
+ * @throws {PriceComponentValidationError} On the first invariant violation
27
+ */
28
+ export declare function validatePriceSchedule(schedule: EnyoPriceSchedule, label?: string): void;
29
+ /**
30
+ * Validates a dynamic grid fee registration. Throws on the first violation.
31
+ *
32
+ * @param registration - The grid fee to validate
33
+ * @throws {PriceComponentValidationError} On the first invariant violation
34
+ *
35
+ * @example
36
+ * ```typescript
37
+ * validateDynamicGridFee(registration);
38
+ * await energyApp.useGridFee().registerGridFee(registration);
39
+ * ```
40
+ */
41
+ export declare function validateDynamicGridFee(registration: EnyoDynamicGridFeeRegistration): void;
42
+ /**
43
+ * Validates a single tariff bonus. Throws on the first violation.
44
+ *
45
+ * @param bonus - The bonus to validate
46
+ * @param label - Prefix used in error messages, e.g. `'bonuses[0]'`
47
+ * @throws {PriceComponentValidationError} On the first invariant violation
48
+ */
49
+ export declare function validateTariffBonus(bonus: EnyoTariffBonus, label?: string): void;
50
+ /**
51
+ * Validates a tariff's bonus list: every bonus is individually valid and ids are
52
+ * unique within the tariff.
53
+ *
54
+ * @param bonuses - The bonuses to validate
55
+ * @throws {PriceComponentValidationError} On the first invariant violation
56
+ */
57
+ export declare function validateTariffBonuses(bonuses: EnyoTariffBonus[]): void;
@@ -0,0 +1,230 @@
1
+ import { EnyoPriceAppliesToEnum, EnyoPriceScheduleTypeEnum, } from '../../types/enyo-price-schedule.js';
2
+ import { parseTimeOfDay } from './price-schedule-resolver.js';
3
+ /**
4
+ * Thrown when a grid fee, tariff bonus or price schedule violates one of the
5
+ * invariants enforced by this module. The message names the offending field or
6
+ * window index so callers can surface it directly to the user.
7
+ */
8
+ export class PriceComponentValidationError extends Error {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = 'PriceComponentValidationError';
12
+ }
13
+ }
14
+ function fail(message) {
15
+ throw new PriceComponentValidationError(message);
16
+ }
17
+ function requireNonEmpty(value, field) {
18
+ if (value === undefined || value.trim().length === 0) {
19
+ fail(`${field} must be a non-empty string`);
20
+ }
21
+ }
22
+ function requireValidTimezone(timezone, field) {
23
+ requireNonEmpty(timezone, field);
24
+ try {
25
+ new Intl.DateTimeFormat('en-US', { timeZone: timezone });
26
+ }
27
+ catch {
28
+ fail(`${field} must be a valid IANA time zone identifier, got '${timezone}'`);
29
+ }
30
+ }
31
+ function requireNonNegativeAmount(amount, field) {
32
+ if (!Number.isFinite(amount)) {
33
+ fail(`${field} must be a finite number`);
34
+ }
35
+ if (amount < 0) {
36
+ fail(`${field} must not be negative — amounts are unsigned magnitudes; ` +
37
+ `grid fees are added to and bonuses subtracted from the energy price`);
38
+ }
39
+ }
40
+ function requireIsoTimestamp(value, field) {
41
+ const parsed = Date.parse(value);
42
+ if (Number.isNaN(parsed)) {
43
+ fail(`${field} must be a valid ISO timestamp, got '${value}'`);
44
+ }
45
+ return parsed;
46
+ }
47
+ function requireValidityRange(validFromIso, validUntilIso, label) {
48
+ const from = validFromIso === undefined ? undefined : requireIsoTimestamp(validFromIso, `${label}.validFromIso`);
49
+ const until = validUntilIso === undefined ? undefined : requireIsoTimestamp(validUntilIso, `${label}.validUntilIso`);
50
+ if (from !== undefined && until !== undefined && until <= from) {
51
+ fail(`${label}.validUntilIso must be after ${label}.validFromIso`);
52
+ }
53
+ }
54
+ function requireAppliesTo(appliesTo, field) {
55
+ if (!Object.values(EnyoPriceAppliesToEnum).includes(appliesTo)) {
56
+ fail(`${field} must be one of ${Object.values(EnyoPriceAppliesToEnum).join(', ')}`);
57
+ }
58
+ }
59
+ function toMinuteIntervals(start, end) {
60
+ return start < end
61
+ ? [{ start, end }]
62
+ : [{ start, end: 1440 }, { start: 0, end }];
63
+ }
64
+ function intervalsOverlap(a, b) {
65
+ return a.some(left => b.some(right => left.start < right.end && right.start < left.end));
66
+ }
67
+ function setsIntersect(a, b) {
68
+ if (a === undefined || b === undefined) {
69
+ return true;
70
+ }
71
+ return a.some(value => b.includes(value));
72
+ }
73
+ /**
74
+ * Validates a {@link EnyoPriceSchedule}. Throws on the first violation.
75
+ *
76
+ * Enforces finite, non-negative amounts, well-formed `HH:mm` times, day and
77
+ * month ranges, ordered absolute windows, and that no two windows which can
78
+ * occur on the same day overlap in time — an overlap would make the resolved
79
+ * amount depend on array order rather than on the schedule itself.
80
+ *
81
+ * Overlap detection for recurring windows is conservative: two windows are only
82
+ * compared when their day-of-week and month sets can intersect. A window that
83
+ * wraps past midnight is compared on both of its legs.
84
+ *
85
+ * @param schedule - The schedule to validate
86
+ * @param label - Prefix used in error messages, e.g. `'gridFee.schedule'`
87
+ * @throws {PriceComponentValidationError} On the first invariant violation
88
+ */
89
+ export function validatePriceSchedule(schedule, label = 'schedule') {
90
+ if (schedule === null || typeof schedule !== 'object') {
91
+ fail(`${label} must be an object`);
92
+ }
93
+ if (schedule.type === EnyoPriceScheduleTypeEnum.Constant) {
94
+ requireNonNegativeAmount(schedule.amountPerKwh, `${label}.amountPerKwh`);
95
+ return;
96
+ }
97
+ if (schedule.type === EnyoPriceScheduleTypeEnum.Absolute) {
98
+ if (schedule.windows.length === 0) {
99
+ fail(`${label}.windows must contain at least one window`);
100
+ }
101
+ const ranges = schedule.windows.map((window, index) => {
102
+ const start = requireIsoTimestamp(window.startIso, `${label}.windows[${index}].startIso`);
103
+ const end = requireIsoTimestamp(window.endIso, `${label}.windows[${index}].endIso`);
104
+ if (end <= start) {
105
+ fail(`${label}.windows[${index}].endIso must be after startIso`);
106
+ }
107
+ requireNonNegativeAmount(window.amountPerKwh, `${label}.windows[${index}].amountPerKwh`);
108
+ return { start, end, index };
109
+ }).sort((a, b) => a.start - b.start);
110
+ for (let i = 1; i < ranges.length; i++) {
111
+ if (ranges[i].start < ranges[i - 1].end) {
112
+ fail(`${label}.windows[${ranges[i].index}] overlaps windows[${ranges[i - 1].index}]`);
113
+ }
114
+ }
115
+ return;
116
+ }
117
+ if (schedule.type === EnyoPriceScheduleTypeEnum.Recurring) {
118
+ if (schedule.windows.length === 0) {
119
+ fail(`${label}.windows must contain at least one window`);
120
+ }
121
+ const parsed = schedule.windows.map((window, index) => {
122
+ const start = parseTimeOfDay(window.startTimeOfDay);
123
+ const end = parseTimeOfDay(window.endTimeOfDay);
124
+ if (start === null) {
125
+ fail(`${label}.windows[${index}].startTimeOfDay must be a 'HH:mm' time, got '${window.startTimeOfDay}'`);
126
+ }
127
+ if (end === null) {
128
+ fail(`${label}.windows[${index}].endTimeOfDay must be a 'HH:mm' time, got '${window.endTimeOfDay}'`);
129
+ }
130
+ if (start === end) {
131
+ fail(`${label}.windows[${index}] must not start and end at the same time of day`);
132
+ }
133
+ if (window.daysOfWeek !== undefined) {
134
+ if (window.daysOfWeek.length === 0) {
135
+ fail(`${label}.windows[${index}].daysOfWeek must not be empty — omit it for 'every day'`);
136
+ }
137
+ for (const day of window.daysOfWeek) {
138
+ if (!Number.isInteger(day) || day < 0 || day > 6) {
139
+ fail(`${label}.windows[${index}].daysOfWeek must contain integers 0 (Sunday) to 6 (Saturday), got ${day}`);
140
+ }
141
+ }
142
+ }
143
+ if (window.months !== undefined) {
144
+ if (window.months.length === 0) {
145
+ fail(`${label}.windows[${index}].months must not be empty — omit it for 'every month'`);
146
+ }
147
+ for (const month of window.months) {
148
+ if (!Number.isInteger(month) || month < 1 || month > 12) {
149
+ fail(`${label}.windows[${index}].months must contain integers 1 to 12, got ${month}`);
150
+ }
151
+ }
152
+ }
153
+ requireNonNegativeAmount(window.amountPerKwh, `${label}.windows[${index}].amountPerKwh`);
154
+ return { window, index, intervals: toMinuteIntervals(start, end) };
155
+ });
156
+ for (let i = 0; i < parsed.length; i++) {
157
+ for (let j = i + 1; j < parsed.length; j++) {
158
+ const left = parsed[i];
159
+ const right = parsed[j];
160
+ if (!setsIntersect(left.window.daysOfWeek, right.window.daysOfWeek)) {
161
+ continue;
162
+ }
163
+ if (!setsIntersect(left.window.months, right.window.months)) {
164
+ continue;
165
+ }
166
+ if (intervalsOverlap(left.intervals, right.intervals)) {
167
+ fail(`${label}.windows[${right.index}] overlaps windows[${left.index}]`);
168
+ }
169
+ }
170
+ }
171
+ return;
172
+ }
173
+ fail(`${label}.type must be one of ${Object.values(EnyoPriceScheduleTypeEnum).join(', ')}`);
174
+ }
175
+ /**
176
+ * Validates a dynamic grid fee registration. Throws on the first violation.
177
+ *
178
+ * @param registration - The grid fee to validate
179
+ * @throws {PriceComponentValidationError} On the first invariant violation
180
+ *
181
+ * @example
182
+ * ```typescript
183
+ * validateDynamicGridFee(registration);
184
+ * await energyApp.useGridFee().registerGridFee(registration);
185
+ * ```
186
+ */
187
+ export function validateDynamicGridFee(registration) {
188
+ requireNonEmpty(registration.name, 'gridFee.name');
189
+ requireNonEmpty(registration.gridOperator, 'gridFee.gridOperator');
190
+ requireNonEmpty(registration.currency, 'gridFee.currency');
191
+ requireValidTimezone(registration.timezone, 'gridFee.timezone');
192
+ requireAppliesTo(registration.appliesTo, 'gridFee.appliesTo');
193
+ requireValidityRange(registration.validFromIso, registration.validUntilIso, 'gridFee');
194
+ validatePriceSchedule(registration.schedule, 'gridFee.schedule');
195
+ }
196
+ /**
197
+ * Validates a single tariff bonus. Throws on the first violation.
198
+ *
199
+ * @param bonus - The bonus to validate
200
+ * @param label - Prefix used in error messages, e.g. `'bonuses[0]'`
201
+ * @throws {PriceComponentValidationError} On the first invariant violation
202
+ */
203
+ export function validateTariffBonus(bonus, label = 'bonus') {
204
+ requireNonEmpty(bonus.id, `${label}.id`);
205
+ requireNonEmpty(bonus.name, `${label}.name`);
206
+ requireValidTimezone(bonus.timezone, `${label}.timezone`);
207
+ requireAppliesTo(bonus.appliesTo, `${label}.appliesTo`);
208
+ requireValidityRange(bonus.validFromIso, bonus.validUntilIso, label);
209
+ if (bonus.priority !== undefined && !Number.isFinite(bonus.priority)) {
210
+ fail(`${label}.priority must be a finite number`);
211
+ }
212
+ validatePriceSchedule(bonus.schedule, `${label}.schedule`);
213
+ }
214
+ /**
215
+ * Validates a tariff's bonus list: every bonus is individually valid and ids are
216
+ * unique within the tariff.
217
+ *
218
+ * @param bonuses - The bonuses to validate
219
+ * @throws {PriceComponentValidationError} On the first invariant violation
220
+ */
221
+ export function validateTariffBonuses(bonuses) {
222
+ const seen = new Set();
223
+ bonuses.forEach((bonus, index) => {
224
+ validateTariffBonus(bonus, `bonuses[${index}]`);
225
+ if (seen.has(bonus.id)) {
226
+ fail(`bonuses[${index}].id '${bonus.id}' is used more than once in the same tariff`);
227
+ }
228
+ seen.add(bonus.id);
229
+ });
230
+ }
@@ -0,0 +1,95 @@
1
+ import { EnyoPriceSchedule, EnyoResolvedPriceEntry } from '../../types/enyo-price-schedule.js';
2
+ /**
3
+ * Length of one resolved interval, in minutes. Matches the resolution of
4
+ * `useElectricityPrices().getPrices()` so resolved schedules can be combined
5
+ * with a price series interval by interval.
6
+ */
7
+ export declare const PRICE_SCHEDULE_INTERVAL_MINUTES = 15;
8
+ /**
9
+ * Wall-clock calendar fields of an instant, as seen in a specific time zone.
10
+ */
11
+ export interface ZonedDateParts {
12
+ /** Full year, e.g. `2026`. */
13
+ year: number;
14
+ /** Month, `1` = January … `12` = December. */
15
+ month: number;
16
+ /** Day of the month, starting at `1`. */
17
+ day: number;
18
+ /** Day of the week, `0` = Sunday … `6` = Saturday. */
19
+ weekday: number;
20
+ /** Hour in 24-hour notation, `0`–`23`. */
21
+ hour: number;
22
+ /** Minute, `0`–`59`. */
23
+ minute: number;
24
+ /** Minutes since local midnight (`hour * 60 + minute`). */
25
+ minutesOfDay: number;
26
+ }
27
+ /**
28
+ * Projects an instant onto the wall clock of a time zone.
29
+ *
30
+ * Uses `Intl.DateTimeFormat`, so daylight-saving transitions are handled by the
31
+ * platform's time zone database without pulling in a dependency.
32
+ *
33
+ * @param date - The instant to project
34
+ * @param timezone - IANA time zone identifier, e.g. `'Europe/Berlin'`
35
+ * @returns The wall-clock calendar fields of `date` in `timezone`
36
+ * @throws {RangeError} If `timezone` is not a valid IANA identifier
37
+ */
38
+ export declare function getZonedDateParts(date: Date, timezone: string): ZonedDateParts;
39
+ /**
40
+ * Parses an `HH:mm` wall-clock time into minutes since midnight.
41
+ *
42
+ * @param value - Time in 24-hour `HH:mm` notation, e.g. `'22:00'`
43
+ * @returns Minutes since midnight, or `null` when the value is malformed
44
+ */
45
+ export declare function parseTimeOfDay(value: string): number | null;
46
+ /**
47
+ * Rounds an instant down to the start of its 15-minute interval.
48
+ *
49
+ * @param timestampMs - Epoch milliseconds
50
+ * @returns Epoch milliseconds of the interval start
51
+ */
52
+ export declare function floorToInterval(timestampMs: number): number;
53
+ /**
54
+ * Options for {@link resolvePriceSchedule}.
55
+ */
56
+ export interface ResolvePriceScheduleOptions {
57
+ /** Start of the range to resolve, in ISO format (inclusive). */
58
+ fromIso: string;
59
+ /** End of the range to resolve, in ISO format (exclusive). */
60
+ untilIso: string;
61
+ /** IANA time zone the schedule's wall-clock times are expressed in. */
62
+ timezone: string;
63
+ /** Optional start of the component's validity in ISO format (inclusive). */
64
+ validFromIso?: string;
65
+ /** Optional end of the component's validity in ISO format (exclusive). */
66
+ validUntilIso?: string;
67
+ }
68
+ /**
69
+ * Expands a price schedule into a flat 15-minute series over a time range.
70
+ *
71
+ * The range start is rounded down to the enclosing 15-minute interval. Intervals
72
+ * no window covers resolve to `amountPerKwh: 0`; intervals outside the
73
+ * component's validity window are omitted entirely, so an empty result means
74
+ * "this component does not apply here" rather than "it is free here".
75
+ *
76
+ * Windows are evaluated in array order and the first match wins — schedules are
77
+ * expected to be overlap-free, which the validators enforce at registration
78
+ * time.
79
+ *
80
+ * @param schedule - The schedule to expand
81
+ * @param options - Range, time zone and optional validity bounds
82
+ * @returns Resolved entries sorted ascending by `timestampIso`
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * const entries = resolvePriceSchedule(
87
+ * {
88
+ * type: EnyoPriceScheduleTypeEnum.Recurring,
89
+ * windows: [{ startTimeOfDay: '22:00', endTimeOfDay: '06:00', amountPerKwh: 0.05 }],
90
+ * },
91
+ * { fromIso: '2026-09-02T00:00:00Z', untilIso: '2026-09-03T00:00:00Z', timezone: 'Europe/Berlin' },
92
+ * );
93
+ * ```
94
+ */
95
+ export declare function resolvePriceSchedule(schedule: EnyoPriceSchedule, options: ResolvePriceScheduleOptions): EnyoResolvedPriceEntry[];