@operato/ops-contract 0.9.46 → 0.9.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tariff.js ADDED
@@ -0,0 +1,376 @@
1
+ /**
2
+ * **Electricity tariff rules** — the words of a time-of-use tariff and how to read it.
3
+ *
4
+ * ── Why this is in the contract (2026-11-27) ────────────────────────────────────────────────────────────────────
5
+ * The tariff is site master data and is stored by ops-master (`ElectricityTariff` · `ElectricityTariffBand`). What
6
+ * lives here is the reading: which band applies at a moment, and whether a tariff's bands cover every day. Once the
7
+ * twin prices usage per band (the kernel's `electricityCost({ energyChargeFromPeriods })`), ops-master's screen and the
8
+ * twin must give the same answer for the same moment - a rule two implementations share belongs to the contract.
9
+ * Storage, approval and screens stay with ops-master.
10
+ *
11
+ * Field names are the declaration's (`EMS_DECLARATION` `tariff.*`): `demandChargePerKW`, `energyChargePerKWh`,
12
+ * `currency`. The contract power (`contract.kW`) and billing demand (`tariff.billingDemandKW`) are not tariff rows -
13
+ * one is a property of the supply point, the other a per-cycle fact from the supplier.
14
+ *
15
+ * ── Which price wins ────────────────────────────────────────────────────────────────────────────────────────────
16
+ * A source fact's own price (`EnergyUsagePeriodData.unitPrice`) is what was charged; it wins. A band price from the
17
+ * master is used only for a period whose fact carries no price. The master is a declaration, the fact an observation.
18
+ *
19
+ * ── Times are the site's wall clock ─────────────────────────────────────────────────────────────────────────────
20
+ * Bands are set in local time ("weekdays 09:00-10:00 are on-peak"). These functions do not know time zones: the
21
+ * caller converts an instant to the site's month, day, weekday and minute (`LocalMoment`). Cutting in UTC would make
22
+ * Seoul's 09:00 into 00:00.
23
+ *
24
+ * ── A band does not cross midnight ──────────────────────────────────────────────────────────────────────────────
25
+ * "22:00-08:00 off-peak" is written as two rows (22:00-24:00, 00:00-08:00). A single row would have to say which day
26
+ * it belongs to (does Saturday night run into Sunday morning?), and tariffs answer that differently.
27
+ *
28
+ * ── A new country is rows, not code (2026-11-27) ───────────────────────────────────────────────────────────────
29
+ * Tariff systems differ by country and supplier: how many bands and what they are called, whether a holiday is priced
30
+ * like Sunday, whether demand is charged per band, which days are holidays. A new country must be written as tariff,
31
+ * band and calendar rows - never as a change here, in the kernel or on a screen. So:
32
+ * · the band **code** is the tariff's own (`base` · `intermedia` · `punta`, `super-off-peak` …); only its
33
+ * **load class** - for comparing across tariffs - is a closed, ordered vocabulary (`TARIFF_LOAD_CLASSES`);
34
+ * · `sunday` and `holiday` are separate day kinds; a tariff pricing them alike writes two rows;
35
+ * · the tariff's `demandChargePerKW` is the facility demand charge (any time); a band may carry its own
36
+ * time-of-use `demandChargePerKW`;
37
+ * · the tariff names its holiday calendar (`holidayCalendar`); the calendar's days are not in the contract - the
38
+ * caller passes `isHoliday`.
39
+ * Season bounds are fixed `MM-DD`. A tariff whose season moves each year ("from the first Sunday of April") is written
40
+ * as one tariff per year with its effective dates - not yet seen to need more (to check against CFE tariffs).
41
+ *
42
+ * ── Issues are structured ───────────────────────────────────────────────────────────────────────────────────────
43
+ * Checks return `{ field, code, params }`, not sentences: a screen turns the code into its own language, and
44
+ * `tariffIssueText` gives the one-line English `field: reason` other contract checks use.
45
+ */
46
+ /**
47
+ * Load class of a band - **ordered from lightest to heaviest load**, for comparing bands across tariffs
48
+ * ("how much is shifted out of the heaviest hours"). The band's own code is the tariff's: Mexico's `base` ·
49
+ * `intermedia` · `punta` are classed `off-peak` · `mid-peak` · `on-peak`; a US `super-off-peak` band is that class.
50
+ */
51
+ export const TARIFF_LOAD_CLASSES = ['super-off-peak', 'off-peak', 'mid-peak', 'on-peak'];
52
+ /**
53
+ * Which days a band applies to. `all` ignores the day.
54
+ *
55
+ * `holiday` is a day of the tariff's holiday calendar (`holidayCalendar`) and **comes before the weekday**: a holiday
56
+ * falling on a Saturday is a holiday. A tariff that prices holidays like Sundays writes a `sunday` row and a `holiday`
57
+ * row. A tariff with no `holiday` row does not price holidays apart - its holidays are read as their weekday.
58
+ */
59
+ export const TARIFF_DAY_KINDS = ['all', 'weekday', 'saturday', 'sunday', 'holiday'];
60
+ /** The kinds a concrete day can be - every day is exactly one of these. */
61
+ const CONCRETE_DAY_KINDS = ['weekday', 'saturday', 'sunday', 'holiday'];
62
+ export const TARIFF_ISSUE_CODES = [
63
+ /** A required field is empty. */
64
+ 'required',
65
+ /** An amount is not a number. */
66
+ 'not-a-number',
67
+ /** An amount is below zero. */
68
+ 'negative',
69
+ /** A value is outside its vocabulary - `params.allowed`. */
70
+ 'not-in-vocabulary',
71
+ /** A text is not in its format - `params.format`. */
72
+ 'format',
73
+ /** An amount is written without a currency. */
74
+ 'currency-required',
75
+ /** Season start and end must be written together or both left empty. */
76
+ 'season-pair',
77
+ /** End time is not after the start - a band crossing midnight is two rows. */
78
+ 'end-not-after-start',
79
+ /** The tariff has bands and a flat energy charge - which one prices an hour cannot be said. */
80
+ 'flat-and-bands',
81
+ /** `params.count` bands break the row rules and were left out of the coverage check. */
82
+ 'broken-bands',
83
+ /** No band covers `params.from`..`params.to` on `params.dayKind` days `params.days`. */
84
+ 'gap',
85
+ /** Bands `params.bands` overlap `params.from`..`params.to` on `params.dayKind` days `params.days`. */
86
+ 'overlap'
87
+ ];
88
+ /** One English line, `field: reason` - the form other contract checks use. */
89
+ export function tariffIssueText(issue) {
90
+ const p = issue.params ?? {};
91
+ switch (issue.code) {
92
+ case 'required':
93
+ return `${issue.field}: required${p.because ? ` (${p.because})` : ''}`;
94
+ case 'not-a-number':
95
+ return `${issue.field}: not a number (${p.value})`;
96
+ case 'negative':
97
+ return `${issue.field}: must be 0 or more (${p.value})`;
98
+ case 'not-in-vocabulary':
99
+ return `${issue.field}: must be one of ${p.allowed} ("${p.value}")`;
100
+ case 'format':
101
+ return `${issue.field}: must be ${p.format} ("${p.value}")`;
102
+ case 'currency-required':
103
+ return `${issue.field}: required when an amount is written`;
104
+ case 'season-pair':
105
+ return `${issue.field}: seasonFrom and seasonTo go together, or both empty for all year`;
106
+ case 'end-not-after-start':
107
+ return `${issue.field}: must be after fromTime (${p.from}~${p.to}); a band crossing midnight is two rows`;
108
+ case 'flat-and-bands':
109
+ return `${issue.field}: the tariff has bands - leave its flat charge empty`;
110
+ case 'broken-bands':
111
+ return `${issue.field}: ${p.count} band(s) break the row rules and were left out`;
112
+ case 'gap':
113
+ return `${issue.field}: ${p.dayKind} ${p.days} - no band ${p.from}~${p.to}`;
114
+ case 'overlap':
115
+ return `${issue.field}: ${p.dayKind} ${p.days} - ${p.bands} overlap ${p.from}~${p.to}`;
116
+ }
117
+ }
118
+ const empty = (v) => v === undefined || v === null || (typeof v === 'string' && v.trim() === '');
119
+ /** An ISO 4217 code - three upper-case letters (KRW, USD). */
120
+ export function isIso4217Code(value) {
121
+ return typeof value === 'string' && /^[A-Z]{3}$/.test(value);
122
+ }
123
+ /** An amount field - empty gives `undefined`; not a number or below zero is an issue. */
124
+ function amountOf(v, field, issues) {
125
+ if (empty(v))
126
+ return undefined;
127
+ const n = Number(v);
128
+ if (!Number.isFinite(n)) {
129
+ issues.push({ field, code: 'not-a-number', params: { value: String(v) } });
130
+ return undefined;
131
+ }
132
+ if (n < 0) {
133
+ issues.push({ field, code: 'negative', params: { value: n } });
134
+ return undefined;
135
+ }
136
+ return n;
137
+ }
138
+ /** `HH:mm` → minutes from midnight. `24:00` is 1440 and is only an end. */
139
+ export function minutesOf(text) {
140
+ const m = /^(\d{2}):(\d{2})$/.exec(String(text ?? '').trim());
141
+ if (!m)
142
+ return undefined;
143
+ const h = Number(m[1]);
144
+ const min = Number(m[2]);
145
+ if (min > 59)
146
+ return undefined;
147
+ if (h === 24 && min === 0)
148
+ return 1440;
149
+ if (h > 23)
150
+ return undefined;
151
+ return h * 60 + min;
152
+ }
153
+ const DAYS_IN_MONTH = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
154
+ /** `MM-DD` → day of a leap year (0..365). Takes 02-29 - that day too must fall in some season. */
155
+ export function dayOfYearOf(text) {
156
+ const m = /^(\d{2})-(\d{2})$/.exec(String(text ?? '').trim());
157
+ if (!m)
158
+ return undefined;
159
+ const month = Number(m[1]);
160
+ const day = Number(m[2]);
161
+ if (month < 1 || month > 12 || day < 1 || day > DAYS_IN_MONTH[month - 1])
162
+ return undefined;
163
+ let n = 0;
164
+ for (let i = 0; i < month - 1; i++)
165
+ n += DAYS_IN_MONTH[i];
166
+ return n + day - 1;
167
+ }
168
+ /** One tariff row, before it is saved. Empty when it is sound. */
169
+ export function tariffIssues(row) {
170
+ const issues = [];
171
+ const d = amountOf(row.demandChargePerKW, 'demandChargePerKW', issues);
172
+ const e = amountOf(row.energyChargePerKWh, 'energyChargePerKWh', issues);
173
+ const currency = String(row.currency ?? '').trim();
174
+ /* An amount without a unit cannot be added to another amount - the same rule as the energy ingest. */
175
+ if ((d !== undefined || e !== undefined) && !currency)
176
+ issues.push({ field: 'currency', code: 'currency-required' });
177
+ if (currency && !isIso4217Code(currency))
178
+ issues.push({ field: 'currency', code: 'format', params: { format: 'ISO 4217 (KRW, USD)', value: currency } });
179
+ return issues;
180
+ }
181
+ /** One band row, before it is saved. Whether bands cover the day cannot be seen from one row - `tariffCoverageIssues`. */
182
+ export function tariffBandIssues(row) {
183
+ const issues = [];
184
+ if (empty(row.tariffName))
185
+ issues.push({ field: 'tariffName', code: 'required' });
186
+ if (empty(row.band))
187
+ issues.push({ field: 'band', code: 'required' });
188
+ const loadClass = String(row.loadClass ?? '').trim();
189
+ if (!loadClass)
190
+ issues.push({ field: 'loadClass', code: 'required' });
191
+ else if (!TARIFF_LOAD_CLASSES.includes(loadClass)) {
192
+ issues.push({ field: 'loadClass', code: 'not-in-vocabulary', params: { allowed: TARIFF_LOAD_CLASSES.join('|'), value: loadClass } });
193
+ }
194
+ const dayKind = empty(row.dayKind) ? 'all' : String(row.dayKind).trim();
195
+ if (!TARIFF_DAY_KINDS.includes(dayKind)) {
196
+ issues.push({ field: 'dayKind', code: 'not-in-vocabulary', params: { allowed: TARIFF_DAY_KINDS.join('|'), value: dayKind } });
197
+ }
198
+ const sFromEmpty = empty(row.seasonFrom);
199
+ const sToEmpty = empty(row.seasonTo);
200
+ if (sFromEmpty !== sToEmpty)
201
+ issues.push({ field: sFromEmpty ? 'seasonFrom' : 'seasonTo', code: 'season-pair' });
202
+ if (!sFromEmpty && dayOfYearOf(row.seasonFrom) === undefined)
203
+ issues.push({ field: 'seasonFrom', code: 'format', params: { format: 'MM-DD', value: String(row.seasonFrom) } });
204
+ if (!sToEmpty && dayOfYearOf(row.seasonTo) === undefined)
205
+ issues.push({ field: 'seasonTo', code: 'format', params: { format: 'MM-DD', value: String(row.seasonTo) } });
206
+ const from = minutesOf(row.fromTime);
207
+ const to = minutesOf(row.toTime);
208
+ if (from === undefined || from === 1440)
209
+ issues.push({ field: 'fromTime', code: 'format', params: { format: 'HH:mm 00:00..23:59', value: String(row.fromTime ?? '') } });
210
+ if (to === undefined || to === 0)
211
+ issues.push({ field: 'toTime', code: 'format', params: { format: 'HH:mm 00:01..24:00', value: String(row.toTime ?? '') } });
212
+ if (from !== undefined && to !== undefined && from < 1440 && to > 0 && from >= to) {
213
+ issues.push({ field: 'toTime', code: 'end-not-after-start', params: { from: String(row.fromTime), to: String(row.toTime) } });
214
+ }
215
+ /* A band without a price cannot price its hours. */
216
+ if (empty(row.energyChargePerKWh))
217
+ issues.push({ field: 'energyChargePerKWh', code: 'required' });
218
+ else
219
+ amountOf(row.energyChargePerKWh, 'energyChargePerKWh', issues);
220
+ amountOf(row.demandChargePerKW, 'demandChargePerKW', issues);
221
+ return issues;
222
+ }
223
+ /** Whether a season holds that day - takes a season wrapping the year. An empty season is all year. */
224
+ function seasonHas(band, dayOfYear) {
225
+ if (empty(band.seasonFrom) && empty(band.seasonTo))
226
+ return true;
227
+ const from = dayOfYearOf(band.seasonFrom);
228
+ const to = dayOfYearOf(band.seasonTo);
229
+ if (from === undefined || to === undefined)
230
+ return false;
231
+ return from <= to ? dayOfYear >= from && dayOfYear <= to : dayOfYear >= from || dayOfYear <= to;
232
+ }
233
+ /** Whether a tariff prices holidays apart - some band names the `holiday` day kind. */
234
+ function pricesHolidays(bands) {
235
+ return bands.some(b => String(b.dayKind ?? '').trim() === 'holiday');
236
+ }
237
+ /** The kind of a concrete day. A holiday comes before the weekday, but only for a tariff that prices holidays apart. */
238
+ function dayKindOf(at, holidays, isHoliday) {
239
+ if (holidays && isHoliday?.(at.month, at.day))
240
+ return 'holiday';
241
+ return at.weekday === 0 ? 'sunday' : at.weekday === 6 ? 'saturday' : 'weekday';
242
+ }
243
+ function dayKindHas(band, kind) {
244
+ const k = empty(band.dayKind) ? 'all' : String(band.dayKind).trim();
245
+ return k === 'all' || k === kind;
246
+ }
247
+ /** Bands still in force at `at` - a band whose end has passed was retired (rows are ended, not deleted). */
248
+ export function activeBands(bands, at) {
249
+ return bands.filter(b => empty(b.effectiveEnd) || new Date(b.effectiveEnd).getTime() > at.getTime());
250
+ }
251
+ const hhmm = (m) => `${String(Math.floor(m / 60)).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`;
252
+ function mmdd(dayOfYear) {
253
+ let month = 0;
254
+ let rest = dayOfYear;
255
+ while (rest >= DAYS_IN_MONTH[month])
256
+ rest -= DAYS_IN_MONTH[month++];
257
+ return `${String(month + 1).padStart(2, '0')}-${String(rest + 1).padStart(2, '0')}`;
258
+ }
259
+ /**
260
+ * Whether one tariff's bands cover **every minute of every day, once**.
261
+ *
262
+ * Looks at all 366 days of a leap year × the concrete day kinds (weekday, saturday, sunday, and holiday when the tariff
263
+ * prices holidays apart). An uncovered hour cannot be priced; an hour
264
+ * covered twice has two prices - either way its charge would be invented. The same problem over consecutive days is
265
+ * one issue (`params.days` like `06-01~08-31`).
266
+ *
267
+ * No bands is not an issue - it is a flat tariff (the tariff row's `energyChargePerKWh`). A tariff passes through
268
+ * wrong states while it is edited, so a screen shows this rather than refusing to save.
269
+ */
270
+ export function tariffCoverageIssues(tariff, bands) {
271
+ const issues = [];
272
+ if (!bands.length)
273
+ return issues;
274
+ const usable = bands.filter(b => tariffBandIssues(b).length === 0);
275
+ if (!empty(tariff.energyChargePerKWh))
276
+ issues.push({ field: 'energyChargePerKWh', code: 'flat-and-bands' });
277
+ /* Band prices are in the tariff's currency - a band amount without one cannot be added to anything. */
278
+ if (!String(tariff.currency ?? '').trim())
279
+ issues.push({ field: 'currency', code: 'currency-required' });
280
+ const holidays = pricesHolidays(usable);
281
+ if (holidays && empty(tariff.holidayCalendar)) {
282
+ issues.push({ field: 'holidayCalendar', code: 'required', params: { because: 'the tariff has holiday bands' } });
283
+ }
284
+ const broken = bands.length - usable.length;
285
+ if (broken)
286
+ issues.push({ field: 'bands', code: 'broken-bands', params: { count: broken } });
287
+ /* (day kind, problem) → the days it happened, in order */
288
+ const seen = new Map();
289
+ const note = (kind, day, code, from, to, names) => {
290
+ const key = [kind, code, from, to, names ?? ''].join('\u0000');
291
+ const entry = seen.get(key);
292
+ if (entry)
293
+ entry.days.push(day);
294
+ else {
295
+ const params = { dayKind: kind, from: hhmm(from), to: hhmm(to) };
296
+ if (names)
297
+ params.bands = names;
298
+ seen.set(key, { problem: { field: 'bands', code, params }, days: [day] });
299
+ }
300
+ };
301
+ /* A tariff that does not price holidays apart has no holiday to cover - its holidays are their weekdays. */
302
+ for (const kind of CONCRETE_DAY_KINDS.filter(k => k !== 'holiday' || holidays)) {
303
+ for (let day = 0; day < 366; day++) {
304
+ const today = usable
305
+ .filter(b => seasonHas(b, day) && dayKindHas(b, kind))
306
+ .map(b => ({ name: String(b.name ?? ''), from: minutesOf(b.fromTime), to: minutesOf(b.toTime) }))
307
+ .sort((a, b) => a.from - b.from || a.to - b.to);
308
+ let cursor = 0;
309
+ let last;
310
+ for (const b of today) {
311
+ if (b.from > cursor)
312
+ note(kind, day, 'gap', cursor, b.from);
313
+ if (last && b.from < last.to)
314
+ note(kind, day, 'overlap', b.from, Math.min(last.to, b.to), `${last.name}·${b.name}`);
315
+ if (b.to > cursor) {
316
+ cursor = b.to;
317
+ last = b;
318
+ }
319
+ }
320
+ if (cursor < 1440)
321
+ note(kind, day, 'gap', cursor, 1440);
322
+ }
323
+ }
324
+ for (const { problem, days } of seen.values()) {
325
+ const spans = [];
326
+ let start = days[0];
327
+ let prev = days[0];
328
+ for (const d of [...days.slice(1), Infinity]) {
329
+ if (d === prev + 1) {
330
+ prev = d;
331
+ continue;
332
+ }
333
+ spans.push(start === prev ? mmdd(start) : `${mmdd(start)}~${mmdd(prev)}`);
334
+ start = prev = d;
335
+ }
336
+ issues.push({ ...problem, params: { ...problem.params, days: spans.join(', ') } });
337
+ }
338
+ return issues;
339
+ }
340
+ /**
341
+ * The energy charge at this moment.
342
+ *
343
+ * Without bands the tariff's flat charge applies. With bands **exactly one** must match - none is `no-band`, more than
344
+ * one is `ambiguous`, and no price is picked (taking the first written would be chance).
345
+ */
346
+ export function bandAt(tariff, bands, at, isHoliday) {
347
+ const currency = String(tariff.currency ?? '').trim() || undefined;
348
+ const usable = bands.filter(b => tariffBandIssues(b).length === 0);
349
+ if (!usable.length) {
350
+ const flat = empty(tariff.energyChargePerKWh) ? NaN : Number(tariff.energyChargePerKWh);
351
+ if (!Number.isFinite(flat))
352
+ return { reason: 'no-price' };
353
+ return { energyChargePerKWh: flat, ...(currency ? { currency } : {}), holidayKnown: true };
354
+ }
355
+ const day = dayOfYearOf(`${String(at.month).padStart(2, '0')}-${String(at.day).padStart(2, '0')}`);
356
+ if (day === undefined)
357
+ return { reason: 'no-band' };
358
+ const holidays = pricesHolidays(usable);
359
+ const kind = dayKindOf(at, holidays, isHoliday);
360
+ const hits = usable.filter(b => seasonHas(b, day) && dayKindHas(b, kind) && minutesOf(b.fromTime) <= at.minutes && at.minutes < minutesOf(b.toTime));
361
+ if (!hits.length)
362
+ return { reason: 'no-band' };
363
+ if (hits.length > 1)
364
+ return { reason: 'ambiguous', bands: hits.map(b => String(b.name ?? '')) };
365
+ const hit = hits[0];
366
+ const demand = empty(hit.demandChargePerKW) ? undefined : Number(hit.demandChargePerKW);
367
+ return {
368
+ bandName: String(hit.name ?? '') || undefined,
369
+ band: String(hit.band).trim(),
370
+ loadClass: String(hit.loadClass).trim(),
371
+ energyChargePerKWh: Number(hit.energyChargePerKWh),
372
+ ...(demand !== undefined ? { demandChargePerKW: demand } : {}),
373
+ ...(currency ? { currency } : {}),
374
+ holidayKnown: !holidays || !!isHoliday
375
+ };
376
+ }