@olenbetong/appframe-core 2.11.10 → 2.13.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 (95) hide show
  1. package/dist/esm/af.common.js +1988 -626
  2. package/dist/esm/af.common.legacy.js +1942 -626
  3. package/dist/esm/af.common.legacy.min.js +4 -3
  4. package/dist/esm/af.common.legacy.min.js.map +1 -7
  5. package/dist/esm/af.common.min.js +4 -3
  6. package/dist/esm/af.common.min.js.map +1 -7
  7. package/dist/iife/af.common.js +2146 -708
  8. package/dist/iife/af.common.legacy.js +2100 -708
  9. package/dist/iife/af.common.legacy.min.js +4 -3
  10. package/dist/iife/af.common.legacy.min.js.map +1 -7
  11. package/dist/iife/af.common.min.js +4 -3
  12. package/dist/iife/af.common.min.js.map +1 -7
  13. package/es/alert.js +16 -1
  14. package/es/filter/convertFilter.d.ts +23 -0
  15. package/es/filter/convertFilter.js +26 -0
  16. package/es/filter/describeFilter.d.ts +13 -0
  17. package/es/filter/describeFilter.js +60 -0
  18. package/es/filter/describeFilter.test.d.ts +1 -0
  19. package/es/filter/describeFilter.test.js +68 -0
  20. package/es/filter/fields.d.ts +28 -0
  21. package/es/filter/fields.js +37 -0
  22. package/es/filter/fields.test.d.ts +1 -0
  23. package/es/filter/fields.test.js +49 -0
  24. package/es/filter/index.d.ts +8 -0
  25. package/es/filter/index.js +7 -0
  26. package/es/filter/operators.d.ts +37 -0
  27. package/es/filter/operators.js +235 -0
  28. package/es/filter/operators.test.d.ts +1 -0
  29. package/es/filter/operators.test.js +107 -0
  30. package/es/filter/savedFilters.d.ts +111 -0
  31. package/es/filter/savedFilters.js +118 -0
  32. package/es/filter/savedFilters.test.d.ts +1 -0
  33. package/es/filter/savedFilters.test.js +108 -0
  34. package/es/filter/standardLayout.d.ts +18 -0
  35. package/es/filter/standardLayout.js +55 -0
  36. package/es/filter/standardLayout.test.d.ts +1 -0
  37. package/es/filter/standardLayout.test.js +66 -0
  38. package/es/filter/tree.d.ts +70 -0
  39. package/es/filter/tree.js +185 -0
  40. package/es/filter/tree.test.d.ts +1 -0
  41. package/es/filter/tree.test.js +184 -0
  42. package/es/filter/types.d.ts +73 -0
  43. package/es/filter/types.js +1 -0
  44. package/es/index.d.ts +2 -0
  45. package/es/index.js +4 -2
  46. package/es/parseFunc.test.js +5 -6
  47. package/es/report/index.d.ts +6 -0
  48. package/es/report/index.js +5 -0
  49. package/es/report/parameterDefaults.d.ts +26 -0
  50. package/es/report/parameterDefaults.js +77 -0
  51. package/es/report/parameters.d.ts +46 -0
  52. package/es/report/parameters.js +188 -0
  53. package/es/report/parameters.test.d.ts +1 -0
  54. package/es/report/parameters.test.js +161 -0
  55. package/es/report/recordSource.d.ts +30 -0
  56. package/es/report/recordSource.js +105 -0
  57. package/es/report/render.d.ts +81 -0
  58. package/es/report/render.js +219 -0
  59. package/es/report/render.test.d.ts +1 -0
  60. package/es/report/render.test.js +144 -0
  61. package/es/report/report.d.ts +16 -0
  62. package/es/report/report.js +50 -0
  63. package/es/report/report.test.d.ts +1 -0
  64. package/es/report/report.test.js +86 -0
  65. package/es/report/types.d.ts +124 -0
  66. package/es/report/types.js +8 -0
  67. package/package.json +7 -7
  68. package/src/alert.ts +16 -1
  69. package/src/filter/convertFilter.ts +47 -0
  70. package/src/filter/describeFilter.test.ts +103 -0
  71. package/src/filter/describeFilter.ts +79 -0
  72. package/src/filter/fields.test.ts +58 -0
  73. package/src/filter/fields.ts +56 -0
  74. package/src/filter/index.ts +62 -0
  75. package/src/filter/operators.test.ts +137 -0
  76. package/src/filter/operators.ts +258 -0
  77. package/src/filter/savedFilters.test.ts +145 -0
  78. package/src/filter/savedFilters.ts +192 -0
  79. package/src/filter/standardLayout.test.ts +88 -0
  80. package/src/filter/standardLayout.ts +65 -0
  81. package/src/filter/tree.test.ts +258 -0
  82. package/src/filter/tree.ts +238 -0
  83. package/src/filter/types.ts +146 -0
  84. package/src/index.ts +3 -1
  85. package/src/parseFunc.test.ts +5 -6
  86. package/src/report/index.ts +37 -0
  87. package/src/report/parameterDefaults.ts +101 -0
  88. package/src/report/parameters.test.ts +218 -0
  89. package/src/report/parameters.ts +230 -0
  90. package/src/report/recordSource.ts +123 -0
  91. package/src/report/render.test.ts +230 -0
  92. package/src/report/render.ts +269 -0
  93. package/src/report/report.test.ts +104 -0
  94. package/src/report/report.ts +51 -0
  95. package/src/report/types.ts +135 -0
@@ -1,581 +1,1879 @@
1
- var af;
2
- (af ||= {}).common = (() => {
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
-
21
- // src/index.ts
22
- var index_exports = {};
23
- __export(index_exports, {
24
- ConfirmButtons: () => ConfirmButtons,
25
- SessionHandler: () => SessionHandler,
26
- UserSession: () => UserSession,
27
- alert: () => alert,
28
- confirm: () => confirm,
29
- downloadBlob: () => downloadBlob,
30
- downloadRequest: () => downloadRequest,
31
- expose: () => expose,
32
- getLocalizedString: () => getLocalizedString,
33
- getSessionData: () => getSessionData,
34
- getSettings: () => getSettings,
35
- getUserImage: () => getUserImage,
36
- invariant: () => invariant,
37
- localStorage: () => localStorage_default,
38
- localize: () => localize,
39
- logActivity: () => logActivity,
40
- logError: () => logError,
41
- mitt: () => mitt_default,
42
- openAlertDialog: () => openAlertDialog,
43
- saveSettings: () => saveSettings,
44
- startActivity: () => startActivity,
45
- time: () => time,
46
- toLocalDateTime: () => toLocalDateTime,
47
- toLocalISODate: () => toLocalISODate,
48
- toLocalISODateTime: () => toLocalISODateTime,
49
- version: () => version,
50
- waitForDialog: () => waitForDialog
51
- });
52
-
53
- // ../../node_modules/.pnpm/mitt@3.0.1/node_modules/mitt/dist/mitt.mjs
54
- function mitt_default(n) {
55
- return { all: n = n || /* @__PURE__ */ new Map(), on: function(t, e) {
56
- var i = n.get(t);
57
- i ? i.push(e) : n.set(t, [e]);
58
- }, off: function(t, e) {
59
- var i = n.get(t);
60
- i && (e ? i.splice(i.indexOf(e) >>> 0, 1) : n.set(t, []));
61
- }, emit: function(t, e) {
62
- var i = n.get(t);
63
- i && i.slice().map(function(n2) {
64
- n2(e);
65
- }), (i = n.get("*")) && i.slice().map(function(n2) {
66
- n2(t, e);
67
- });
68
- } };
69
- }
70
-
71
- // src/SessionHandler.ts
72
- var SessionHandler = class {
73
- eventHandler = mitt_default();
74
- authenticated() {
75
- this.eventHandler.emit("onAuthenticated");
76
- }
77
- async expired(callback, type) {
78
- try {
79
- let authPromise = new Promise((resolve) => {
80
- let eventHandler = () => {
81
- this.eventHandler.off("onAuthenticated", eventHandler);
82
- callback?.();
83
- resolve();
84
- };
85
- this.eventHandler.on("onAuthenticated", eventHandler);
86
- });
87
- let dialog = document.querySelector("dialog.session-expired-dialog");
88
- if (!dialog) {
89
- dialog = document.createElement("dialog");
90
- dialog.className = "session-expired-dialog";
91
- dialog.style.display = "flex";
92
- dialog.style.padding = "0";
93
- dialog.style.left = "50%";
94
- dialog.style.transform = "translateX(-50%)";
95
- let link = "/login?ReturnUrl=%2fapi/sessionexpired/remove";
96
- if (type !== "RequireTwoFactor") {
97
- await fetch("/logout", { method: "POST" });
98
- } else {
99
- link = "/login?RequireTwoFactor=1&ReturnUrl=%2fapi/sessionexpired/remove";
100
- }
101
- dialog.innerHTML = `<iframe sandbox="allow-same-origin allow-scripts allow-modals allow-top-navigation-by-user-activation allow-forms" src="${link}" style="border:0;width:min(500px,100vw);height:min(700px, 100vh);"></iframe>`;
102
- document.body.append(dialog);
103
- dialog.showModal();
104
- await authPromise;
105
- dialog.remove();
106
- } else {
107
- await authPromise;
108
- }
109
- } catch (_) {
110
- window.location.href = `/login?ReturnUrl=${encodeURIComponent(window.location.pathname)}${encodeURIComponent(
111
- window.location.search
112
- )}`;
113
- }
114
- }
115
- attachEvent(eventName, handler) {
116
- return this.eventHandler.on(eventName, handler);
117
- }
118
- detachEvent(eventName, handler) {
119
- return this.eventHandler.off(eventName, handler);
120
- }
121
- };
122
-
123
- // src/UserSession.ts
124
- var UserSession = class extends SessionHandler {
125
- amDesignator = "a.m.";
126
- dayNames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
127
- dayNamesShort = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
128
- decimalSeparator = ".";
129
- domain = "OB";
130
- email;
131
- formats;
132
- groupSeparator = null;
133
- integratedSecurity = false;
134
- isDeveloper = false;
135
- login = "";
136
- loginType;
137
- monthNames = [
138
- "january",
139
- "february",
140
- "march",
141
- "april",
142
- "may",
143
- "june",
144
- "july",
145
- "august",
146
- "september",
147
- "october",
148
- "november",
149
- "december",
150
- ""
151
- ];
152
- monthNamesShort = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "augt", "sep", "oct", "nov", "dec", ""];
153
- name;
154
- pmDesignator = "p.m.";
155
- shortDateFormat = "dd.MM.yyyy";
156
- culture = "en-GB";
157
- uiculture = "en-GB";
158
- constructor(userData) {
159
- super();
160
- this.formats = {};
161
- Object.assign(this, userData);
162
- }
163
- };
164
-
165
- // src/log.ts
166
- var article = window.af?.article?.id ?? window.window?.location.pathname.substring(1).split("/")[0];
167
- async function logActivity(activity, parameters = {}, timeElapsed = 0) {
168
- try {
169
- let response = await fetch("/api/logging/log-activity", {
170
- method: "POST",
171
- body: JSON.stringify({
172
- article,
173
- timeElapsed,
174
- action: activity,
175
- parameters: {
176
- ...parameters,
177
- _session: getSessionData()
178
- }
179
- }),
180
- headers: { "Content-Type": "application/json", Accept: "application/json" }
181
- });
182
- if (!response.ok) {
183
- if (response.headers.get("Content-Type")?.includes("application/json")) {
184
- let data = await response.json();
185
- console.error(data.error);
186
- } else {
187
- console.error(`${response.status} ${response.statusText}`);
188
- }
189
- }
190
- } catch {
191
- }
192
- }
193
- function startActivity(activity, startParameters = {}) {
194
- let start = performance.now();
195
- return (endParameters = {}) => logActivity(activity, { ...startParameters, ...endParameters }, performance.now() - start);
196
- }
197
- async function time(callback) {
198
- let start = performance.now();
199
- let returnValue = await callback();
200
- return [returnValue, performance.now() - start];
201
- }
202
- async function logError(error) {
203
- try {
204
- if (!error) return;
205
- let data = typeof error === "string" ? { error } : typeof error === "object" ? "message" in error ? {
206
- error: error.message,
207
- stack: error.stack ?? null
208
- } : { error: error.toString() } : { error: "Unspecified error" };
209
- console.error(error);
210
- let result = await fetch("/data/Logger/LogError", {
211
- method: "POST",
212
- body: JSON.stringify(data),
213
- headers: {
214
- "Content-Type": "application/json; charset=utf-8"
215
- }
216
- });
217
- if (result.ok) {
218
- return await result.json();
219
- }
220
- console.error(Error("Failed to log error"));
221
- } catch {
222
- }
223
- }
224
- function getSessionId() {
225
- return crypto.randomUUID?.();
226
- }
227
- var sessionStart = Date.now();
228
- var sessionId = getSessionId();
229
- var deviceId = "";
230
- var browserSessionId = "";
231
- if ("document" in window) {
232
- let startSession = () => logActivity("AfSessionInit", {
233
- "appframe-core": window.af?.common?.version,
234
- "appframe-data": window.af?.data?.version,
235
- "app-version": window.af?.article?.version
236
- });
237
- document.addEventListener("DOMContentLoaded", () => {
238
- deviceId = localStorage.getItem("_afDeviceId");
239
- browserSessionId = sessionStorage.getItem("_afSessionId");
240
- if (!deviceId) {
241
- deviceId = getSessionId();
242
- localStorage.setItem("_afDeviceId", deviceId);
243
- }
244
- if (!browserSessionId) {
245
- browserSessionId = sessionId;
246
- sessionStorage.setItem("_afSessionId", browserSessionId);
247
- }
248
- startSession();
249
- });
250
- document.addEventListener("visibilitychange", function logData() {
251
- if (document.visibilityState === "hidden") {
252
- navigator.sendBeacon(
253
- "/api/logging/log-activity",
254
- JSON.stringify({
255
- article,
256
- action: "AfSessionEnd",
257
- parameters: {
258
- _session: getSessionData()
259
- }
260
- })
261
- );
262
- } else {
263
- startSession();
264
- }
265
- });
266
- }
267
- function getSessionData() {
268
- return {
269
- browserSessionId,
270
- sessionStart,
271
- sessionLength: Date.now() - sessionStart,
272
- sessionId,
273
- deviceId
274
- };
275
- }
276
-
277
- // src/errorHandler.ts
278
- if (true) {
279
- window.window?.addEventListener("error", (event) => {
280
- if (typeof event === "object" && "error" in event) {
281
- logError(event.error);
282
- } else if (typeof event === "object" && "message" in event) {
283
- logError(event);
284
- }
285
- });
286
- }
287
-
288
- // src/localStorage.ts
289
- function getLocalKey(key) {
290
- return [af?.article?.id || "", "common", key].join(".");
291
- }
292
- var LocalStorage = class {
293
- isPersisted = () => true;
294
- getLocalStorageKey(key, global) {
295
- return global ? ["common", key].join(".") : getLocalKey(key);
296
- }
297
- get(key, defaultValue, global) {
298
- const lsKey = this.getLocalStorageKey(key, global);
299
- const value = localStorage.getItem(lsKey);
300
- return value !== null ? JSON.parse(value) : defaultValue;
301
- }
302
- set(key, value, global) {
303
- localStorage.setItem(this.getLocalStorageKey(key, global), JSON.stringify(value));
304
- }
305
- remove(key, global) {
306
- const lsKey = this.getLocalStorageKey(key, global);
307
- if (localStorage.getItem(lsKey) !== null) {
308
- localStorage.removeItem(lsKey);
309
- return true;
310
- } else {
311
- return false;
312
- }
313
- }
314
- clear() {
315
- const baseKey = getLocalKey("");
316
- for (let key in localStorage) {
317
- if (key.slice(0, baseKey.length) === baseKey) {
318
- localStorage.removeItem(key);
319
- }
320
- }
321
- }
322
- };
323
- var localStorage_default = new LocalStorage();
324
-
325
- // src/date.ts
326
- function toLocalISODate(date) {
327
- return date ? toLocalISODateTime(date).substring(0, 10) : null;
328
- }
329
- function pad(num, digits = 2) {
330
- return String(num).padStart(digits, "0");
331
- }
332
- function toLocalISODateTime(date) {
333
- return date ? `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(
334
- date.getMinutes()
335
- )}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}` : null;
336
- }
337
- function toLocalDateTime(date) {
338
- return date ? date.toISOString().substring(0, 16) : "";
339
- }
340
-
341
- // src/downloadBlob.ts
342
- function downloadBlob(blob, fileName) {
343
- return new Promise((resolve, reject) => {
344
- try {
345
- const url = URL.createObjectURL(blob);
346
- const parent = document.body;
347
- const anchor = document.createElement("a");
348
- anchor.setAttribute("download", fileName);
349
- anchor.href = url;
350
- parent.append(anchor);
351
- anchor.click();
352
- parent.removeChild(anchor);
353
- setTimeout(() => {
354
- URL.revokeObjectURL(url);
355
- resolve();
356
- }, 250);
357
- } catch (ex) {
358
- reject(ex);
359
- }
360
- });
361
- }
362
-
363
- // src/invariant.ts
364
- function invariant(condition, message) {
365
- if (condition) {
366
- return;
367
- }
368
- const provided = typeof message === "function" ? message() : message;
369
- throw new Error(provided ?? "Invariant failed");
370
- }
371
-
372
- // src/downloadRequest.ts
373
- async function downloadRequest(request, { fileName, signal, onProgress }) {
374
- let bytesReceived = 0;
375
- onProgress?.({ status: "requested" });
376
- try {
377
- let response = await fetch(request);
378
- if (!response.ok || !response.body) {
379
- if (response.headers.get("content-type")?.includes("application/json")) {
380
- let data = await response.json();
381
- invariant(!data.error, data.error);
382
- }
383
- throw new Error(`${response.status} ${response.statusText}`);
384
- }
385
- try {
386
- const reader = response.body.getReader();
387
- const stream = new ReadableStream({
388
- start: (controller) => {
389
- function pump() {
390
- return reader.read().then((read) => {
391
- if (read.done) {
392
- controller.close();
393
- return;
394
- }
395
- bytesReceived += read.value.length;
396
- onProgress?.({ bytesReceived, status: "downloading" });
397
- controller.enqueue(read.value);
398
- return pump();
399
- });
400
- }
401
- return pump();
402
- }
403
- });
404
- response = new Response(stream);
405
- } catch {
406
- }
407
- const blob = await response.blob();
408
- onProgress?.({ bytesReceived, status: "downloaded" });
409
- await downloadBlob(blob, fileName);
410
- onProgress?.({ bytesReceived, status: "completed" });
411
- } catch (err) {
412
- if (signal?.aborted) {
413
- onProgress?.({ status: "cancelled" });
414
- } else {
415
- onProgress?.({ error: err.message, status: "error" });
416
- }
417
- }
418
- }
419
-
420
- // src/parseFunc.ts
421
- var funcRegex = /^function(?:\s+([a-zA-Z$_][a-zA-Z0-9$_]*))?\s*\(((?:(?:\s*[a-zA-Z$_][a-zA-Z0-9$_]*)(?:\s*,\s*[a-zA-Z$_][a-zA-Z0-9$_]*)*)?)\s*\)\s*\{((?:.|\n|\r)*)\}$/;
422
- var arrowBlockRegex = /^(?:\(([^)]*)\)|([a-zA-Z$_][a-zA-Z0-9$_]*))\s*=>\s*\{([\s\S]*)\}$/;
423
- var arrowExpressionRegex = /^(?:\(([^)]*)\)|([a-zA-Z$_][a-zA-Z0-9$_]*))\s*=>\s*([\s\S]+)$/;
424
- var parseArguments = (args) => args.split(",").map((a) => a.trim()).filter(Boolean);
425
- function parseFunc(func) {
426
- const funcString = func.toString();
427
- const arrowBlockMatch = funcString.match(arrowBlockRegex);
428
- if (arrowBlockMatch) {
429
- const args = parseArguments(arrowBlockMatch[1] ?? arrowBlockMatch[2] ?? "");
430
- return { name: func.name, args, body: arrowBlockMatch[3] };
431
- }
432
- const arrowExpressionMatch = funcString.match(arrowExpressionRegex);
433
- if (arrowExpressionMatch) {
434
- const args = parseArguments(arrowExpressionMatch[1] ?? arrowExpressionMatch[2] ?? "");
435
- return { name: func.name, args, body: arrowExpressionMatch[3] };
436
- }
437
- const match = funcString.match(funcRegex);
438
- invariant(match, "Unable to parse function!");
439
- return { name: func.name ?? match[1], args: parseArguments(match[2]), body: match[3] };
440
- }
441
-
442
- // src/Namespace.ts
443
- function Namespace() {
444
- }
445
- Namespace.prototype = /* @__PURE__ */ Object.create(null);
446
- var Namespace_default = Namespace;
447
-
448
- // src/requireNamespace.ts
449
- function requireNamespace(root, namespace) {
450
- if (typeof root === "object") {
451
- if (typeof namespace === "string") {
452
- let path = namespace.split(".");
453
- return requireNamespace(root, path);
454
- } else if (Array.isArray(namespace)) {
455
- let current = root;
456
- for (let i = 0; i < namespace.length; i++) {
457
- current = current[namespace[i]] = current[namespace[i]] || new Namespace_default();
458
- }
459
- return current;
460
- }
461
- }
462
- }
463
-
464
- // src/expose.ts
465
- function expose(name, value, options = {}) {
466
- if (Array.isArray(value)) {
467
- for (let func of value) {
468
- const { name: funcName } = parseFunc(func);
469
- invariant(
470
- funcName,
471
- "Unable to detect name of function! Name it, or only supply one function and include name in first parameter."
472
- );
473
- expose(name, func);
474
- }
475
- } else {
476
- let keyName;
477
- let namespace;
478
- if (typeof value === "function") {
479
- keyName = parseFunc(value).name;
480
- }
481
- if (typeof name === "string") {
482
- let pathParts = name.split(".");
483
- if (!keyName) {
484
- keyName = pathParts[pathParts.length - 1];
485
- pathParts = pathParts.slice(0, pathParts.length - 1);
486
- }
487
- namespace = requireNamespace(window, pathParts);
488
- } else if (keyName && (typeof name === "object" || typeof name === "function")) {
489
- namespace = name;
490
- } else {
491
- invariant(false, "Invalid typeof parameter 'name', or unable to parse pValue!");
492
- }
493
- if (Object.hasOwn(namespace, keyName) && options?.overwrite !== true) {
494
- console.warn(`${[name, keyName].join(".")} is already defined!`);
495
- } else {
496
- namespace[keyName] = value;
497
- }
498
- }
499
- }
500
-
501
- // src/getLocalizedString.ts
502
- async function fetchLocalizedString(text) {
503
- try {
504
- let response = await fetch(`/api/user/localize/new/${af.article.id}`, {
505
- body: JSON.stringify({ text }),
506
- headers: {
507
- Accept: "application/json; */*",
508
- "Content-Type": "application/json",
509
- "X-Requested-With": "XMLHttpRequest"
510
- },
511
- method: "POST"
512
- });
513
- if (response.ok) {
514
- return await response.json();
515
- }
516
- } catch {
517
- }
518
- return text;
519
- }
520
- function getLocalizedString(string, wait) {
521
- if (typeof string === "string" && string.trim().length === 0) {
522
- return string;
523
- }
524
- if (string === void 0 || string === "" || string === null) {
525
- return;
526
- }
527
- if (window.af?.article?.i18n !== void 0) {
528
- if (!Object.hasOwn(af.article.i18n, string)) {
529
- af.article.i18n[string] = string;
530
- let promise = fetchLocalizedString(string).then((text) => {
531
- af.article.i18n[string] = text;
532
- return text;
533
- });
534
- if (wait) {
535
- return promise;
536
- }
537
- }
538
- return af.article.i18n[string];
539
- } else {
540
- return string;
541
- }
542
- }
543
-
544
- // src/getUserImage.ts
545
- var sizeMap = {
546
- xs: 64,
547
- sm: 128,
548
- md: 256,
549
- lg: 512,
550
- xl: void 0
551
- };
552
- function getUserImage(primKeyOrOptions, login, hash, size = "xs") {
553
- if (primKeyOrOptions && typeof primKeyOrOptions === "object") {
554
- return getUserImage(primKeyOrOptions.primKey, primKeyOrOptions.login, primKeyOrOptions.hash, primKeyOrOptions.size);
555
- }
556
- if (!primKeyOrOptions || !hash) {
557
- return "";
558
- }
559
- let sizePx = sizeMap[size];
560
- return `/api/data/blob/EmployeesLookup/${primKeyOrOptions}/Image/${encodeURIComponent(login ?? "")}${login ? "." : ""}${encodeURIComponent(hash)}.jpg${sizePx ? `?width=${sizePx}` : ""}`;
561
- }
562
-
563
- // src/localize.ts
564
- function localize(stringParts, ...args) {
565
- invariant(
566
- Array.isArray(stringParts) && stringParts.length === args.length + 1,
567
- "Method 'localize' must be used as a tag function"
568
- );
569
- let stringToLocalize = stringParts.map((s, i) => i === stringParts.length - 1 ? s : `${s}$${i}`).join("");
570
- let localized = getLocalizedString(stringToLocalize);
571
- args.forEach((arg, index) => {
572
- localized = localized.replace(`$${index}`, arg);
573
- });
574
- return localized;
575
- }
576
-
577
- // src/alert.ts
578
- var template = `
1
+ this.af = this.af || {};
2
+ this.af.common = (function(exports) {
3
+
4
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5
+ //#region ../../node_modules/.pnpm/mitt@3.0.1/node_modules/mitt/dist/mitt.mjs
6
+ function mitt_default(n) {
7
+ return {
8
+ all: n = n || /* @__PURE__ */ new Map(),
9
+ on: function(t, e) {
10
+ var i = n.get(t);
11
+ i ? i.push(e) : n.set(t, [e]);
12
+ },
13
+ off: function(t, e) {
14
+ var i = n.get(t);
15
+ i && (e ? i.splice(i.indexOf(e) >>> 0, 1) : n.set(t, []));
16
+ },
17
+ emit: function(t, e) {
18
+ var i = n.get(t);
19
+ i && i.slice().map(function(n) {
20
+ n(e);
21
+ }), (i = n.get("*")) && i.slice().map(function(n) {
22
+ n(t, e);
23
+ });
24
+ }
25
+ };
26
+ }
27
+
28
+ //#endregion
29
+ //#region src/SessionHandler.ts
30
+ var SessionHandler = class {
31
+ eventHandler = mitt_default();
32
+ authenticated() {
33
+ this.eventHandler.emit("onAuthenticated");
34
+ }
35
+ async expired(callback, type) {
36
+ try {
37
+ let authPromise = new Promise((resolve) => {
38
+ let eventHandler = () => {
39
+ this.eventHandler.off("onAuthenticated", eventHandler);
40
+ callback?.();
41
+ resolve();
42
+ };
43
+ this.eventHandler.on("onAuthenticated", eventHandler);
44
+ });
45
+ let dialog = document.querySelector("dialog.session-expired-dialog");
46
+ if (!dialog) {
47
+ dialog = document.createElement("dialog");
48
+ dialog.className = "session-expired-dialog";
49
+ dialog.style.display = "flex";
50
+ dialog.style.padding = "0";
51
+ dialog.style.left = "50%";
52
+ dialog.style.transform = "translateX(-50%)";
53
+ let link = "/login?ReturnUrl=%2fapi/sessionexpired/remove";
54
+ if (type !== "RequireTwoFactor") await fetch("/logout", { method: "POST" });
55
+ else link = "/login?RequireTwoFactor=1&ReturnUrl=%2fapi/sessionexpired/remove";
56
+ dialog.innerHTML = `<iframe sandbox="allow-same-origin allow-scripts allow-modals allow-top-navigation-by-user-activation allow-forms" src="${link}" style="border:0;width:min(500px,100vw);height:min(700px, 100vh);"></iframe>`;
57
+ document.body.append(dialog);
58
+ dialog.showModal();
59
+ await authPromise;
60
+ dialog.remove();
61
+ } else await authPromise;
62
+ } catch (_) {
63
+ window.location.href = `/login?ReturnUrl=${encodeURIComponent(window.location.pathname)}${encodeURIComponent(window.location.search)}`;
64
+ }
65
+ }
66
+ attachEvent(eventName, handler) {
67
+ return this.eventHandler.on(eventName, handler);
68
+ }
69
+ detachEvent(eventName, handler) {
70
+ return this.eventHandler.off(eventName, handler);
71
+ }
72
+ };
73
+
74
+ //#endregion
75
+ //#region src/UserSession.ts
76
+ var UserSession = class extends SessionHandler {
77
+ amDesignator = "a.m.";
78
+ dayNames = [
79
+ "sunday",
80
+ "monday",
81
+ "tuesday",
82
+ "wednesday",
83
+ "thursday",
84
+ "friday",
85
+ "saturday"
86
+ ];
87
+ dayNamesShort = [
88
+ "sun",
89
+ "mon",
90
+ "tue",
91
+ "wed",
92
+ "thu",
93
+ "fri",
94
+ "sat"
95
+ ];
96
+ decimalSeparator = ".";
97
+ domain = "OB";
98
+ email;
99
+ formats;
100
+ groupSeparator = null;
101
+ integratedSecurity = false;
102
+ isDeveloper = false;
103
+ login = "";
104
+ loginType;
105
+ monthNames = [
106
+ "january",
107
+ "february",
108
+ "march",
109
+ "april",
110
+ "may",
111
+ "june",
112
+ "july",
113
+ "august",
114
+ "september",
115
+ "october",
116
+ "november",
117
+ "december",
118
+ ""
119
+ ];
120
+ monthNamesShort = [
121
+ "jan",
122
+ "feb",
123
+ "mar",
124
+ "apr",
125
+ "may",
126
+ "jun",
127
+ "jul",
128
+ "augt",
129
+ "sep",
130
+ "oct",
131
+ "nov",
132
+ "dec",
133
+ ""
134
+ ];
135
+ name;
136
+ pmDesignator = "p.m.";
137
+ shortDateFormat = "dd.MM.yyyy";
138
+ culture = "en-GB";
139
+ uiculture = "en-GB";
140
+ constructor(userData) {
141
+ super();
142
+ this.formats = {};
143
+ Object.assign(this, userData);
144
+ }
145
+ };
146
+
147
+ //#endregion
148
+ //#region src/log.ts
149
+ const article = window.af?.article?.id ?? window.window?.location.pathname.substring(1).split("/")[0];
150
+ /**
151
+ * Logs an activity to the website activity log
152
+ *
153
+ * @param activity name of the activity we are logging
154
+ * @param parameters A dictionary of parameters used when doing the activity
155
+ * @param timeElapsed Number of milliseconds elapsed while executing
156
+ */
157
+ async function logActivity(activity, parameters = {}, timeElapsed = 0) {
158
+ try {
159
+ let response = await fetch("/api/logging/log-activity", {
160
+ method: "POST",
161
+ body: JSON.stringify({
162
+ article,
163
+ timeElapsed,
164
+ action: activity,
165
+ parameters: {
166
+ ...parameters,
167
+ _session: getSessionData()
168
+ }
169
+ }),
170
+ headers: {
171
+ "Content-Type": "application/json",
172
+ Accept: "application/json"
173
+ }
174
+ });
175
+ if (!response.ok) {
176
+ if (response.headers.get("Content-Type")?.includes("application/json")) {
177
+ let data = await response.json();
178
+ console.error(data.error);
179
+ } else console.error(`${response.status} ${response.statusText}`);
180
+ }
181
+ } catch {}
182
+ }
183
+ /**
184
+ * Records the current time, and returns a function that logs the activity with the
185
+ * time elapsed when it is called.
186
+ *
187
+ * @param activity Name of the activity we are logging
188
+ * @param parameters A dictionary of parameters used when doing the activity
189
+ * @returns A function that should be called when the activity is completed to log it to the website log
190
+ */
191
+ function startActivity(activity, startParameters = {}) {
192
+ let start = performance.now();
193
+ return (endParameters = {}) => logActivity(activity, {
194
+ ...startParameters,
195
+ ...endParameters
196
+ }, performance.now() - start);
197
+ }
198
+ /**
199
+ * Records the time used to execute an operation and returns the value of the operation and the time
200
+ * in milliseconds
201
+ */
202
+ async function time(callback) {
203
+ let start = performance.now();
204
+ return [await callback(), performance.now() - start];
205
+ }
206
+ async function logError(error) {
207
+ try {
208
+ if (!error) return;
209
+ let data = typeof error === "string" ? { error } : typeof error === "object" ? "message" in error ? {
210
+ error: error.message,
211
+ stack: error.stack ?? null
212
+ } : { error: error.toString() } : { error: "Unspecified error" };
213
+ console.error(error);
214
+ let result = await fetch("/data/Logger/LogError", {
215
+ method: "POST",
216
+ body: JSON.stringify(data),
217
+ headers: { "Content-Type": "application/json; charset=utf-8" }
218
+ });
219
+ if (result.ok) return await result.json();
220
+ console.error(Error("Failed to log error"));
221
+ } catch {}
222
+ }
223
+ function getSessionId() {
224
+ return crypto.randomUUID?.();
225
+ }
226
+ let sessionStart = Date.now();
227
+ let sessionId = getSessionId();
228
+ let deviceId = "";
229
+ let browserSessionId = "";
230
+ if ("document" in window) {
231
+ let startSession = () => logActivity("AfSessionInit", {
232
+ "appframe-core": window.af?.common?.version,
233
+ "appframe-data": window.af?.data?.version,
234
+ "app-version": window.af?.article?.version
235
+ });
236
+ document.addEventListener("DOMContentLoaded", () => {
237
+ deviceId = localStorage.getItem("_afDeviceId");
238
+ browserSessionId = sessionStorage.getItem("_afSessionId");
239
+ if (!deviceId) {
240
+ deviceId = getSessionId();
241
+ localStorage.setItem("_afDeviceId", deviceId);
242
+ }
243
+ if (!browserSessionId) {
244
+ browserSessionId = sessionId;
245
+ sessionStorage.setItem("_afSessionId", browserSessionId);
246
+ }
247
+ startSession();
248
+ });
249
+ document.addEventListener("visibilitychange", function logData() {
250
+ if (document.visibilityState === "hidden") navigator.sendBeacon("/api/logging/log-activity", JSON.stringify({
251
+ article,
252
+ action: "AfSessionEnd",
253
+ parameters: { _session: getSessionData() }
254
+ }));
255
+ else startSession();
256
+ });
257
+ }
258
+ function getSessionData() {
259
+ return {
260
+ browserSessionId,
261
+ sessionStart,
262
+ sessionLength: Date.now() - sessionStart,
263
+ sessionId,
264
+ deviceId
265
+ };
266
+ }
267
+
268
+ //#endregion
269
+ //#region src/errorHandler.ts
270
+ window.window?.addEventListener("error", (event) => {
271
+ if (typeof event === "object" && "error" in event) logError(event.error);
272
+ else if (typeof event === "object" && "message" in event) logError(event);
273
+ });
274
+
275
+ //#endregion
276
+ //#region src/localStorage.ts
277
+ function getLocalKey(key) {
278
+ return [
279
+ af?.article?.id || "",
280
+ "common",
281
+ key
282
+ ].join(".");
283
+ }
284
+ var LocalStorage = class {
285
+ isPersisted = () => true;
286
+ getLocalStorageKey(key, global) {
287
+ return global ? ["common", key].join(".") : getLocalKey(key);
288
+ }
289
+ get(key, defaultValue, global) {
290
+ const lsKey = this.getLocalStorageKey(key, global);
291
+ const value = localStorage.getItem(lsKey);
292
+ return value !== null ? JSON.parse(value) : defaultValue;
293
+ }
294
+ set(key, value, global) {
295
+ localStorage.setItem(this.getLocalStorageKey(key, global), JSON.stringify(value));
296
+ }
297
+ remove(key, global) {
298
+ const lsKey = this.getLocalStorageKey(key, global);
299
+ if (localStorage.getItem(lsKey) !== null) {
300
+ localStorage.removeItem(lsKey);
301
+ return true;
302
+ } else return false;
303
+ }
304
+ clear() {
305
+ const baseKey = getLocalKey("");
306
+ for (let key in localStorage) if (key.slice(0, baseKey.length) === baseKey) localStorage.removeItem(key);
307
+ }
308
+ };
309
+ var localStorage_default = new LocalStorage();
310
+
311
+ //#endregion
312
+ //#region src/date.ts
313
+ function toLocalISODate(date) {
314
+ return date ? toLocalISODateTime(date).substring(0, 10) : null;
315
+ }
316
+ function pad(num, digits = 2) {
317
+ return String(num).padStart(digits, "0");
318
+ }
319
+ function toLocalISODateTime(date) {
320
+ return date ? `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}` : null;
321
+ }
322
+ /**
323
+ * Converts a date object to a string compatible with input type datetime-local.
324
+ * Will handle the UTC value of the date as if it was local, to be compatible with
325
+ * data objects.
326
+ *
327
+ * If null or undefined is passed, returns an empty string.
328
+ *
329
+ * @param date
330
+ */
331
+ function toLocalDateTime(date) {
332
+ return date ? date.toISOString().substring(0, 16) : "";
333
+ }
334
+
335
+ //#endregion
336
+ //#region src/downloadBlob.ts
337
+ function downloadBlob(blob, fileName) {
338
+ return new Promise((resolve, reject) => {
339
+ try {
340
+ const url = URL.createObjectURL(blob);
341
+ const parent = document.body;
342
+ const anchor = document.createElement("a");
343
+ anchor.setAttribute("download", fileName);
344
+ anchor.href = url;
345
+ parent.append(anchor);
346
+ anchor.click();
347
+ parent.removeChild(anchor);
348
+ setTimeout(() => {
349
+ URL.revokeObjectURL(url);
350
+ resolve();
351
+ }, 250);
352
+ } catch (ex) {
353
+ reject(ex);
354
+ }
355
+ });
356
+ }
357
+
358
+ //#endregion
359
+ //#region src/invariant.ts
360
+ /**
361
+ * Throws an error if the condition is falsy. The provided message is used as the error message.
362
+ * A function can be provided to lazily generate the message.
363
+ *
364
+ * @param {any} condition
365
+ * @param {string | (() => string)} [message]
366
+ * @returns {void}
367
+ */
368
+ function invariant(condition, message) {
369
+ if (condition) return;
370
+ const provided = typeof message === "function" ? message() : message;
371
+ throw new Error(provided ?? "Invariant failed");
372
+ }
373
+
374
+ //#endregion
375
+ //#region src/downloadRequest.ts
376
+ async function downloadRequest(request, { fileName, signal, onProgress }) {
377
+ let bytesReceived = 0;
378
+ onProgress?.({ status: "requested" });
379
+ try {
380
+ let response = await fetch(request);
381
+ if (!response.ok || !response.body) {
382
+ if (response.headers.get("content-type")?.includes("application/json")) {
383
+ let data = await response.json();
384
+ invariant(!data.error, data.error);
385
+ }
386
+ throw new Error(`${response.status} ${response.statusText}`);
387
+ }
388
+ try {
389
+ const reader = response.body.getReader();
390
+ const stream = new ReadableStream({ start: (controller) => {
391
+ function pump() {
392
+ return reader.read().then((read) => {
393
+ if (read.done) {
394
+ controller.close();
395
+ return;
396
+ }
397
+ bytesReceived += read.value.length;
398
+ onProgress?.({
399
+ bytesReceived,
400
+ status: "downloading"
401
+ });
402
+ controller.enqueue(read.value);
403
+ return pump();
404
+ });
405
+ }
406
+ return pump();
407
+ } });
408
+ response = new Response(stream);
409
+ } catch {}
410
+ const blob = await response.blob();
411
+ onProgress?.({
412
+ bytesReceived,
413
+ status: "downloaded"
414
+ });
415
+ await downloadBlob(blob, fileName);
416
+ onProgress?.({
417
+ bytesReceived,
418
+ status: "completed"
419
+ });
420
+ } catch (err) {
421
+ if (signal?.aborted) onProgress?.({ status: "cancelled" });
422
+ else onProgress?.({
423
+ error: err.message,
424
+ status: "error"
425
+ });
426
+ }
427
+ }
428
+
429
+ //#endregion
430
+ //#region src/parseFunc.ts
431
+ const funcRegex = /^function(?:\s+([a-zA-Z$_][a-zA-Z0-9$_]*))?\s*\(((?:(?:\s*[a-zA-Z$_][a-zA-Z0-9$_]*)(?:\s*,\s*[a-zA-Z$_][a-zA-Z0-9$_]*)*)?)\s*\)\s*\{((?:.|\n|\r)*)\}$/;
432
+ const arrowBlockRegex = /^(?:\(([^)]*)\)|([a-zA-Z$_][a-zA-Z0-9$_]*))\s*=>\s*\{([\s\S]*)\}$/;
433
+ const arrowExpressionRegex = /^(?:\(([^)]*)\)|([a-zA-Z$_][a-zA-Z0-9$_]*))\s*=>\s*([\s\S]+)$/;
434
+ const parseArguments = (args) => args.split(",").map((a) => a.trim()).filter(Boolean);
435
+ function parseFunc(func) {
436
+ const funcString = func.toString();
437
+ const arrowBlockMatch = funcString.match(arrowBlockRegex);
438
+ if (arrowBlockMatch) {
439
+ const args = parseArguments(arrowBlockMatch[1] ?? arrowBlockMatch[2] ?? "");
440
+ return {
441
+ name: func.name,
442
+ args,
443
+ body: arrowBlockMatch[3]
444
+ };
445
+ }
446
+ const arrowExpressionMatch = funcString.match(arrowExpressionRegex);
447
+ if (arrowExpressionMatch) {
448
+ const args = parseArguments(arrowExpressionMatch[1] ?? arrowExpressionMatch[2] ?? "");
449
+ return {
450
+ name: func.name,
451
+ args,
452
+ body: arrowExpressionMatch[3]
453
+ };
454
+ }
455
+ const match = funcString.match(funcRegex);
456
+ invariant(match, "Unable to parse function!");
457
+ return {
458
+ name: func.name ?? match[1],
459
+ args: parseArguments(match[2]),
460
+ body: match[3]
461
+ };
462
+ }
463
+
464
+ //#endregion
465
+ //#region src/Namespace.ts
466
+ function Namespace() {}
467
+ Namespace.prototype = Object.create(null);
468
+
469
+ //#endregion
470
+ //#region src/requireNamespace.ts
471
+ function requireNamespace(root, namespace) {
472
+ if (typeof root === "object") {
473
+ if (typeof namespace === "string") return requireNamespace(root, namespace.split("."));
474
+ else if (Array.isArray(namespace)) {
475
+ let current = root;
476
+ for (let i = 0; i < namespace.length; i++) current = current[namespace[i]] = current[namespace[i]] || new Namespace();
477
+ return current;
478
+ }
479
+ }
480
+ }
481
+
482
+ //#endregion
483
+ //#region src/expose.ts
484
+ /**
485
+ * Expose a value to a potentially deeply nested global variable
486
+ * @param name {string | object} Either a dot-separated path to the global variable, or an object to expose the value on
487
+ * @param value {object | Function | Function[]} The value(s) to expose
488
+ */
489
+ function expose(name, value, options = {}) {
490
+ if (Array.isArray(value)) for (let func of value) {
491
+ const { name: funcName } = parseFunc(func);
492
+ invariant(funcName, "Unable to detect name of function! Name it, or only supply one function and include name in first parameter.");
493
+ expose(name, func);
494
+ }
495
+ else {
496
+ let keyName;
497
+ let namespace;
498
+ if (typeof value === "function") keyName = parseFunc(value).name;
499
+ if (typeof name === "string") {
500
+ let pathParts = name.split(".");
501
+ if (!keyName) {
502
+ keyName = pathParts[pathParts.length - 1];
503
+ pathParts = pathParts.slice(0, pathParts.length - 1);
504
+ }
505
+ namespace = requireNamespace(window, pathParts);
506
+ } else if (keyName && (typeof name === "object" || typeof name === "function")) namespace = name;
507
+ else invariant(false, "Invalid typeof parameter 'name', or unable to parse pValue!");
508
+ if (Object.hasOwn(namespace, keyName) && options?.overwrite !== true) console.warn(`${[name, keyName].join(".")} is already defined!`);
509
+ else namespace[keyName] = value;
510
+ }
511
+ }
512
+
513
+ //#endregion
514
+ //#region src/getLocalizedString.ts
515
+ async function fetchLocalizedString(text) {
516
+ try {
517
+ let response = await fetch(`/api/user/localize/new/${af.article.id}`, {
518
+ body: JSON.stringify({ text }),
519
+ headers: {
520
+ Accept: "application/json; */*",
521
+ "Content-Type": "application/json",
522
+ "X-Requested-With": "XMLHttpRequest"
523
+ },
524
+ method: "POST"
525
+ });
526
+ if (response.ok) return await response.json();
527
+ } catch {}
528
+ return text;
529
+ }
530
+ function getLocalizedString(string, wait) {
531
+ if (typeof string === "string" && string.trim().length === 0) return string;
532
+ if (string === void 0 || string === "" || string === null) return;
533
+ if (window.af?.article?.i18n !== void 0) {
534
+ if (!Object.hasOwn(af.article.i18n, string)) {
535
+ af.article.i18n[string] = string;
536
+ let promise = fetchLocalizedString(string).then((text) => {
537
+ af.article.i18n[string] = text;
538
+ return text;
539
+ });
540
+ if (wait) return promise;
541
+ }
542
+ return af.article.i18n[string];
543
+ } else return string;
544
+ }
545
+
546
+ //#endregion
547
+ //#region src/filter/operators.ts
548
+ /**
549
+ * Operators that take no value at all.
550
+ *
551
+ * `eOperators.ParameterLessChecks` plus the blank checks.
552
+ */
553
+ const PARAMETERLESS_OPERATORS = [
554
+ "isnull",
555
+ "isnotnull",
556
+ "istrue",
557
+ "isfalse",
558
+ "isblank",
559
+ "isnotblank"
560
+ ];
561
+ /** Operators whose value is a two element `[from, to]` array. */
562
+ const PAIR_OPERATORS = [
563
+ "between",
564
+ "notbetween",
565
+ "datebetween",
566
+ "datenotbetween"
567
+ ];
568
+ /** Operators whose value is an array of values. */
569
+ const LIST_OPERATORS = ["inlist", "notinlist"];
570
+ function getOperatorArity(operator) {
571
+ if (PARAMETERLESS_OPERATORS.includes(operator)) return "none";
572
+ if (PAIR_OPERATORS.includes(operator)) return "pair";
573
+ if (LIST_OPERATORS.includes(operator)) return "list";
574
+ return "single";
575
+ }
576
+ /**
577
+ * Operator labels, keyed by operator. Comparison operators have a different
578
+ * label for dates than for numbers, matching the Windows filter editor.
579
+ *
580
+ * @see `appframe/Appframe3.Win/Controls/afFilterEditor/Utils/FilterLineControlUtils.vb`
581
+ */
582
+ const OPERATOR_LABELS = {
583
+ equals: "Equal to",
584
+ notequals: "Not equal to",
585
+ greaterthan: "Greater than",
586
+ greaterthanorequal: "Greater than or equal to",
587
+ lessthan: "Less than",
588
+ lessthanorequal: "Less than or equal to",
589
+ beginswith: "Begins with",
590
+ notbeginswith: "Does not begin with",
591
+ endswith: "Ends with",
592
+ notendswith: "Does not end with",
593
+ contains: "Contains",
594
+ notcontains: "Does not contain",
595
+ like: "Like",
596
+ notlike: "Not like",
597
+ isnull: "Is null",
598
+ isnotnull: "Is not null",
599
+ isblank: "Is empty",
600
+ isnotblank: "Is not empty",
601
+ istrue: "Is true",
602
+ isfalse: "Is false",
603
+ inlist: "In list",
604
+ notinlist: "Not in list",
605
+ between: "Between",
606
+ notbetween: "Not between",
607
+ dateequals: "Equal to",
608
+ notdatequals: "Not equal to",
609
+ dategreaterthan: "After",
610
+ dategreaterthanorequal: "On or after",
611
+ datelessthan: "Before",
612
+ datelessthanorequal: "Up to",
613
+ datebetween: "Between",
614
+ datenotbetween: "Not between"
615
+ };
616
+ /** Comparison operator labels used for date and time fields. */
617
+ const DATE_OPERATOR_LABELS = {
618
+ greaterthan: "After",
619
+ greaterthanorequal: "On or after",
620
+ lessthan: "Before",
621
+ lessthanorequal: "Up to"
622
+ };
623
+ /**
624
+ * Returns the localized label for an operator. Date fields get the
625
+ * "After"/"Before" wording instead of "Greater than"/"Less than".
626
+ */
627
+ function getOperatorLabel(operator, fieldType) {
628
+ let label = (fieldType === "date" || fieldType === "datetime" ? DATE_OPERATOR_LABELS[operator] : void 0) ?? OPERATOR_LABELS[operator];
629
+ return getLocalizedString(label ?? operator);
630
+ }
631
+ const EQUALITY = ["equals", "notequals"];
632
+ const LIST_CHECKS = ["inlist", "notinlist"];
633
+ const RANGE = ["between", "notbetween"];
634
+ const COMPARISONS = [
635
+ "greaterthan",
636
+ "greaterthanorequal",
637
+ "lessthan",
638
+ "lessthanorequal"
639
+ ];
640
+ const STRING_CHECKS = [
641
+ "contains",
642
+ "notcontains",
643
+ "beginswith",
644
+ "notbeginswith",
645
+ "endswith",
646
+ "notendswith",
647
+ "isblank",
648
+ "isnotblank"
649
+ ];
650
+ /**
651
+ * Operators offered per field type, in the order the Windows filter editor
652
+ * presents them.
653
+ */
654
+ const OPERATORS_BY_TYPE = {
655
+ date: [
656
+ ...EQUALITY,
657
+ ...LIST_CHECKS,
658
+ ...RANGE,
659
+ ...COMPARISONS
660
+ ],
661
+ datetime: [
662
+ ...EQUALITY,
663
+ ...LIST_CHECKS,
664
+ ...RANGE,
665
+ ...COMPARISONS
666
+ ],
667
+ number: [
668
+ ...EQUALITY,
669
+ ...LIST_CHECKS,
670
+ ...RANGE,
671
+ ...COMPARISONS
672
+ ],
673
+ boolean: ["istrue", "isfalse"],
674
+ string: [
675
+ ...EQUALITY,
676
+ ...STRING_CHECKS,
677
+ ...LIST_CHECKS,
678
+ ...RANGE,
679
+ ...COMPARISONS
680
+ ],
681
+ uniqueidentifier: [
682
+ ...EQUALITY,
683
+ ...STRING_CHECKS,
684
+ ...LIST_CHECKS,
685
+ ...RANGE,
686
+ ...COMPARISONS
687
+ ]
688
+ };
689
+ /**
690
+ * Default operator per field type.
691
+ *
692
+ * Text defaults to `contains` because a substring search is what people
693
+ * reach for when they type into a filter box without picking an operator —
694
+ * `beginswith` silently misses matches in the middle of the value.
695
+ */
696
+ const DEFAULT_OPERATOR_BY_TYPE = {
697
+ date: "equals",
698
+ datetime: "equals",
699
+ number: "equals",
700
+ boolean: "istrue",
701
+ string: "contains",
702
+ uniqueidentifier: "beginswith"
703
+ };
704
+ /**
705
+ * Returns the operators available for a field. Nullable fields additionally get
706
+ * the null checks. Boolean fields never get null checks, since `istrue` and
707
+ * `isfalse` already cover the parameterless cases.
708
+ */
709
+ function getOperatorsForField(field) {
710
+ let operators = [...OPERATORS_BY_TYPE[field.type] ?? OPERATORS_BY_TYPE.string];
711
+ if (field.nullable && field.type !== "boolean") operators.push("isnull", "isnotnull");
712
+ return operators;
713
+ }
714
+ function getDefaultOperator(field) {
715
+ return DEFAULT_OPERATOR_BY_TYPE[field.type] ?? "equals";
716
+ }
717
+ /**
718
+ * The `valueType` to send for a field/operator combination.
719
+ *
720
+ * Parameterless operators send `"null"`, list and range operators send
721
+ * `"array"`, everything else sends the field's own value type.
722
+ */
723
+ function getValueType(field, operator) {
724
+ if (getOperatorArity(operator) === "none") return "null";
725
+ switch (field.type) {
726
+ case "number": return "number";
727
+ case "boolean": return "boolean";
728
+ case "date":
729
+ case "datetime": return "datetime";
730
+ case "uniqueidentifier": return "uniqueidentifier";
731
+ default: return "string";
732
+ }
733
+ }
734
+ /** Relative date values offered in the date value editor, in menu order. */
735
+ const RELATIVE_DATE_VALUES = [
736
+ "Yesterday",
737
+ "Today",
738
+ "Tomorrow",
739
+ "ThisWeek",
740
+ "ThisMonth",
741
+ "ThisYear",
742
+ "LastWeek",
743
+ "LastMonth",
744
+ "LastYear",
745
+ "NextWeek",
746
+ "NextMonth",
747
+ "NextYear"
748
+ ];
749
+ const DYNAMIC_VALUE_LABELS = {
750
+ CurrentUser: "Current user",
751
+ Yesterday: "Yesterday",
752
+ Today: "Today",
753
+ Tomorrow: "Tomorrow",
754
+ ThisWeek: "This week",
755
+ ThisMonth: "This month",
756
+ ThisYear: "This year",
757
+ LastWeek: "Last week",
758
+ LastMonth: "Last month",
759
+ LastYear: "Last year",
760
+ NextWeek: "Next week",
761
+ NextMonth: "Next month",
762
+ NextYear: "Next year",
763
+ UserYesterday: "Yesterday",
764
+ UserToday: "Today",
765
+ UserTomorrow: "Tomorrow",
766
+ UserThisWeek: "This week",
767
+ UserThisMonth: "This month",
768
+ UserThisYear: "This year",
769
+ UserLastWeek: "Last week",
770
+ UserLastMonth: "Last month",
771
+ UserLastYear: "Last year",
772
+ UserNextWeek: "Next week",
773
+ UserNextMonth: "Next month",
774
+ UserNextYear: "Next year"
775
+ };
776
+ function getDynamicValueLabel(value) {
777
+ return getLocalizedString(DYNAMIC_VALUE_LABELS[value] ?? value);
778
+ }
779
+ /**
780
+ * Returns the dynamic ("special") values that can be used with a field. Date
781
+ * fields get the relative dates; string fields can be compared to the current
782
+ * user name.
783
+ */
784
+ function getDynamicValuesForField(field) {
785
+ if (field.type === "date" || field.type === "datetime") return [...RELATIVE_DATE_VALUES];
786
+ if (field.type === "string") return ["CurrentUser"];
787
+ return [];
788
+ }
789
+ /**
790
+ * Aliases for names `eOperators.ToString()` can produce that are not operators
791
+ * in their own right. `Not` is the bare negation flag (i.e. "not equal to"),
792
+ * `Tweens` shares its numeric value with `NotBetween`, and combined flags are
793
+ * rendered as a comma separated list.
794
+ *
795
+ * @see `FilterElementConverter.FilterExpressionToDictionary`
796
+ */
797
+ const OPERATOR_ALIASES = {
798
+ not: "notequals",
799
+ tweens: "notbetween",
800
+ notdate: "notdatequals",
801
+ notdateequals: "notdatequals"
802
+ };
803
+ /**
804
+ * Normalizes an operator string coming from the server or from another filter
805
+ * producer (`AfGrid` emits PascalCase names) to the canonical lower-case form.
806
+ */
807
+ function normalizeOperator(operator) {
808
+ let normalized = operator.toLowerCase().replace(/[\s,]/g, "");
809
+ return OPERATOR_ALIASES[normalized] ?? normalized;
810
+ }
811
+
812
+ //#endregion
813
+ //#region src/filter/tree.ts
814
+ /**
815
+ * Creates the default empty filter: a single `and` group with no conditions.
816
+ */
817
+ function createEmptyFilter() {
818
+ return createEmptyGroup("and");
819
+ }
820
+ function createEmptyGroup(mode = "and") {
821
+ return {
822
+ type: "group",
823
+ mode,
824
+ items: []
825
+ };
826
+ }
827
+ function isGroup(item) {
828
+ return item.type === "group";
829
+ }
830
+ function isExpression(item) {
831
+ return item.type === "expression";
832
+ }
833
+ /**
834
+ * Normalizes any filter value into a tree the editor can render, without
835
+ * changing its structure. An expression is wrapped in a group; a missing filter
836
+ * becomes the default layout.
837
+ */
838
+ function toFilterTree(filter) {
839
+ if (!filter) return createEmptyFilter();
840
+ if (isExpression(filter)) return {
841
+ type: "group",
842
+ mode: "and",
843
+ items: [filter]
844
+ };
845
+ return filter;
846
+ }
847
+ /**
848
+ * True when the filter contains no expressions. An empty filter must not be
849
+ * saved or applied.
850
+ */
851
+ function isEmptyFilter(filter) {
852
+ return countExpressions(filter) === 0;
853
+ }
854
+ function countExpressions(filter) {
855
+ if (!filter) return 0;
856
+ if (isExpression(filter)) return 1;
857
+ return filter.items.reduce((total, item) => total + countExpressions(item), 0);
858
+ }
859
+ /**
860
+ * Removes incomplete expressions and empty groups from the whole tree. Returns
861
+ * null when nothing is left. Use before applying a filter to a data object so
862
+ * incomplete rows are not sent.
863
+ */
864
+ function pruneFilter(filter) {
865
+ if (!filter) return null;
866
+ if (isExpression(filter)) return isCompleteExpression(filter) ? {
867
+ type: "group",
868
+ mode: "and",
869
+ items: [filter]
870
+ } : null;
871
+ let items = filter.items.map((item) => isGroup(item) ? pruneFilter(item) : isCompleteExpression(item) ? item : null).filter((item) => item !== null);
872
+ if (items.length === 0) return null;
873
+ return {
874
+ ...filter,
875
+ items
876
+ };
877
+ }
878
+ /**
879
+ * True when an expression has everything it needs to be sent to the server.
880
+ */
881
+ function isCompleteExpression(item) {
882
+ if (isGroup(item)) return item.items.some(isCompleteExpression);
883
+ if (!item.column || !item.operator) return false;
884
+ let arity = getOperatorArity(normalizeOperator(item.operator));
885
+ if (arity === "none") return true;
886
+ if (item.value === null || item.value === void 0 || item.value === "") return false;
887
+ if (arity === "pair") return Array.isArray(item.value) && item.value.length === 2 && item.value.every((v) => v !== "" && v != null);
888
+ if (arity === "list") return Array.isArray(item.value) && item.value.length > 0;
889
+ return true;
890
+ }
891
+ /**
892
+ * Creates an expression for a field, using the field's default operator and an
893
+ * empty value of the right shape.
894
+ */
895
+ function createExpression(field, operator) {
896
+ let op = operator ?? getDefaultOperator(field);
897
+ return {
898
+ type: "expression",
899
+ column: field.name,
900
+ operator: op,
901
+ value: createEmptyValue(op),
902
+ valueType: getValueType(field, op)
903
+ };
904
+ }
905
+ function createEmptyValue(operator) {
906
+ switch (getOperatorArity(operator)) {
907
+ case "none": return null;
908
+ case "pair": return ["", ""];
909
+ case "list": return [];
910
+ default: return "";
911
+ }
912
+ }
913
+ /**
914
+ * Returns a copy of the expression with a new operator, adjusting the value to
915
+ * the new operator's arity and the value type accordingly.
916
+ */
917
+ function changeOperator(expression, operator, field) {
918
+ let previousArity = getOperatorArity(normalizeOperator(expression.operator));
919
+ let arity = getOperatorArity(operator);
920
+ let value = expression.value;
921
+ if (arity !== previousArity) value = createEmptyValue(operator);
922
+ let valueType = expression.valueType === "special" && arity === previousArity ? "special" : getValueType(field, operator);
923
+ return {
924
+ ...expression,
925
+ operator,
926
+ value,
927
+ valueType
928
+ };
929
+ }
930
+ /** Returns the node at `path`, or null when the path does not exist. */
931
+ function getNodeAtPath(filter, path) {
932
+ let node = filter;
933
+ for (let index of path) {
934
+ if (!node || !isGroup(node)) return null;
935
+ node = node.items[index];
936
+ }
937
+ return node ?? null;
938
+ }
939
+ /**
940
+ * Returns a copy of the tree with `updater` applied to the node at `path`.
941
+ * Returning null removes the node. An unknown path leaves the tree untouched.
942
+ */
943
+ function updateNodeAtPath(filter, path, updater) {
944
+ if (path.length === 0) return updater(filter) ?? filter;
945
+ if (!isGroup(filter)) return filter;
946
+ let [index, ...rest] = path;
947
+ let child = filter.items[index];
948
+ if (!child) return filter;
949
+ let items = [...filter.items];
950
+ if (rest.length === 0) {
951
+ let updated = updater(child);
952
+ if (updated === null) items.splice(index, 1);
953
+ else items[index] = updated;
954
+ } else items[index] = updateNodeAtPath(child, rest, updater);
955
+ return {
956
+ ...filter,
957
+ items
958
+ };
959
+ }
960
+ /** Returns a copy of the tree with `node` appended to the group at `path`. */
961
+ function insertNodeAtPath(filter, path, node) {
962
+ return updateNodeAtPath(filter, path, (target) => isGroup(target) ? {
963
+ ...target,
964
+ items: [...target.items, node]
965
+ } : target);
966
+ }
967
+ /**
968
+ * Returns a copy of the tree with the node at `path` removed. The root is never
969
+ * removed; it is reset to the default layout instead.
970
+ */
971
+ function removeNodeAtPath(filter, path) {
972
+ if (path.length === 0) return createEmptyFilter();
973
+ return updateNodeAtPath(filter, path, () => null);
974
+ }
975
+ /** Returns a copy of the tree with the mode of the group at `path` changed. */
976
+ function setGroupMode(filter, path, mode) {
977
+ return updateNodeAtPath(filter, path, (node) => isGroup(node) ? {
978
+ ...node,
979
+ mode
980
+ } : node);
981
+ }
982
+ /** Returns a copy of the tree with an empty group appended to the group at `path`. */
983
+ function addGroupAtPath(filter, path = []) {
984
+ let parent = getNodeAtPath(filter, path);
985
+ return insertNodeAtPath(filter, path, createEmptyGroup(parent && isGroup(parent) && parent.mode === "and" ? "or" : "and"));
986
+ }
987
+
988
+ //#endregion
989
+ //#region src/filter/convertFilter.ts
990
+ const CONVERT_URL = "/api/filter/convert";
991
+ /**
992
+ * Converts between a structured filter and a DevExpress filter string.
993
+ *
994
+ * The conversion is done server-side by `api/filter/convert`, because the
995
+ * criteria string grammar is implemented by the licensed DevExpress parser that
996
+ * the Windows client and the report engine use. Doing it in the browser would
997
+ * risk producing strings the server cannot parse back.
998
+ */
999
+ async function convertFilter(request, signal) {
1000
+ let response = await fetch(CONVERT_URL, {
1001
+ method: "POST",
1002
+ headers: { "Content-Type": "application/json" },
1003
+ body: JSON.stringify(request),
1004
+ signal
1005
+ });
1006
+ if (!response.ok) throw new Error(`Failed to convert filter: ${response.status} ${response.statusText}`);
1007
+ let result = await response.json();
1008
+ return {
1009
+ ...result,
1010
+ filterObject: result.filterObject ? toFilterTree(result.filterObject) : null
1011
+ };
1012
+ }
1013
+
1014
+ //#endregion
1015
+ //#region src/filter/describeFilter.ts
1016
+ /**
1017
+ * Builds a human-readable description of a filter, without contacting the
1018
+ * server. Use this for read-only summaries; the authoritative filter string is
1019
+ * produced by `api/filter/convert`, since only the server can generate the
1020
+ * DevExpress criteria syntax.
1021
+ */
1022
+ function describeFilter(filter, options = {}) {
1023
+ if (!filter) return "";
1024
+ return describe(filter, new Map((options.fields ?? []).map((field) => [field.name.toLowerCase(), field])), 0);
1025
+ }
1026
+ function describe(item, fields, depth) {
1027
+ if (isExpression(item)) return describeExpression(item, fields);
1028
+ let parts = item.items.map((child) => describe(child, fields, depth + 1)).filter((part) => part !== "");
1029
+ if (parts.length === 0) return "";
1030
+ if (parts.length === 1) return parts[0];
1031
+ let separator = item.mode === "or" ? " OR " : " AND ";
1032
+ let joined = parts.join(separator);
1033
+ return depth === 0 ? joined : `(${joined})`;
1034
+ }
1035
+ function describeExpression(expression, fields) {
1036
+ if (!expression.column || !expression.operator) return "";
1037
+ let field = fields.get(expression.column.toLowerCase());
1038
+ let caption = field?.caption ?? expression.column;
1039
+ let operator = normalizeOperator(expression.operator);
1040
+ let label = getOperatorLabel(operator, field?.type);
1041
+ let arity = getOperatorArity(operator);
1042
+ if (arity === "none") return `[${caption}] ${label}`;
1043
+ return `[${caption}] ${label} ${formatValue(expression, arity)}`;
1044
+ }
1045
+ function formatValue(expression, arity) {
1046
+ let { value, valueType } = expression;
1047
+ if (valueType === "special" && typeof value === "string") return getDynamicValueLabel(value);
1048
+ if (Array.isArray(value)) {
1049
+ let formatted = value.map((item) => formatScalar(item, valueType));
1050
+ return arity === "pair" ? formatted.join(" - ") : `(${formatted.join(", ")})`;
1051
+ }
1052
+ return formatScalar(value, valueType);
1053
+ }
1054
+ function formatScalar(value, valueType) {
1055
+ if (value === null || value === void 0) return "";
1056
+ if (value instanceof Date) return value.toISOString().slice(0, 10);
1057
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
1058
+ if (valueType === "number" || valueType === "boolean") return String(value);
1059
+ return `'${String(value)}'`;
1060
+ }
1061
+
1062
+ //#endregion
1063
+ //#region src/filter/fields.ts
1064
+ const FIELD_TYPES = [
1065
+ "string",
1066
+ "number",
1067
+ "boolean",
1068
+ "date",
1069
+ "datetime",
1070
+ "uniqueidentifier"
1071
+ ];
1072
+ /** The builder type for a normalized `DataType`. Unknown types are filtered as text. */
1073
+ function toFilterFieldType(dataType) {
1074
+ let normalized = dataType?.trim().toLowerCase();
1075
+ return FIELD_TYPES.find((type) => type === normalized) ?? "string";
1076
+ }
1077
+ function toBoolean$1(value) {
1078
+ return value === true || value === 1;
1079
+ }
1080
+ /** Maps a view field record onto the metadata the builder renders. */
1081
+ function toFieldMetadata(record) {
1082
+ return {
1083
+ name: record.FieldName ?? "",
1084
+ type: toFilterFieldType(record.DataType),
1085
+ nullable: toBoolean$1(record.Nullable),
1086
+ excludeFromFilter: toBoolean$1(record.ExcludeFromFilter),
1087
+ valueListRecordSource: record.ValueListRecordSource || void 0
1088
+ };
1089
+ }
1090
+ /**
1091
+ * Maps and sorts view field records. Fields the view marks as excluded are
1092
+ * dropped rather than hidden, since nothing else can use them.
1093
+ */
1094
+ function toFieldMetadataList(records) {
1095
+ return records.map(toFieldMetadata).filter((field) => field.name !== "" && !field.excludeFromFilter).sort((a, b) => a.name.localeCompare(b.name));
1096
+ }
1097
+
1098
+ //#endregion
1099
+ //#region src/filter/standardLayout.ts
1100
+ /**
1101
+ * The "standard layout" is the simplified shape the Windows filter editor can
1102
+ * render in its flow view: an outer `or` group whose items are `and` groups of
1103
+ * expressions. Anything else falls back to the advanced (DevExpress) editor
1104
+ * there, and to the nested tree editor on the web.
1105
+ *
1106
+ * @see `afFilterEditor.CanRenderFilter`
1107
+ */
1108
+ function isStandardLayout(filter) {
1109
+ if (!filter || isExpression(filter) || filter.mode !== "or") return false;
1110
+ return filter.items.every((item) => isGroup(item) && item.mode === "and" && item.items.every(isExpression));
1111
+ }
1112
+ /**
1113
+ * Coerces an arbitrary filter tree into the standard layout.
1114
+ *
1115
+ * An `or` group's items each become their own `and` group. Anything else is
1116
+ * flattened into a single `and` group. This loses nesting, so only use it when
1117
+ * the consumer cannot handle a nested tree.
1118
+ */
1119
+ function coerceToStandardLayout(filter) {
1120
+ if (!filter) return {
1121
+ type: "group",
1122
+ mode: "or",
1123
+ items: [{
1124
+ type: "group",
1125
+ mode: "and",
1126
+ items: []
1127
+ }]
1128
+ };
1129
+ if (isExpression(filter)) return {
1130
+ type: "group",
1131
+ mode: "or",
1132
+ items: [{
1133
+ type: "group",
1134
+ mode: "and",
1135
+ items: [filter]
1136
+ }]
1137
+ };
1138
+ if (filter.mode === "or") {
1139
+ let groups = filter.items.map((item) => {
1140
+ let expressions = [];
1141
+ collectExpressions(item, expressions);
1142
+ return {
1143
+ type: "group",
1144
+ mode: "and",
1145
+ items: expressions
1146
+ };
1147
+ });
1148
+ return {
1149
+ type: "group",
1150
+ mode: "or",
1151
+ items: groups.length > 0 ? groups : [{
1152
+ type: "group",
1153
+ mode: "and",
1154
+ items: []
1155
+ }]
1156
+ };
1157
+ }
1158
+ let expressions = [];
1159
+ collectExpressions(filter, expressions);
1160
+ return {
1161
+ type: "group",
1162
+ mode: "or",
1163
+ items: [{
1164
+ type: "group",
1165
+ mode: "and",
1166
+ items: expressions
1167
+ }]
1168
+ };
1169
+ }
1170
+ /**
1171
+ * Collects every expression in a (possibly nested) filter, in document order.
1172
+ */
1173
+ function collectExpressions(item, into) {
1174
+ if (isExpression(item)) {
1175
+ into.push(item);
1176
+ return;
1177
+ }
1178
+ for (let child of item.items) collectExpressions(child, into);
1179
+ }
1180
+
1181
+ //#endregion
1182
+ //#region src/filter/savedFilters.ts
1183
+ /**
1184
+ * `sviw_Database_MyFilters` unions in a synthetic "No Filter" row so the Windows
1185
+ * tree can render a "no filter" entry. It is not a real filter and must be
1186
+ * dropped before the list is shown.
1187
+ */
1188
+ const NO_FILTER_ID = -1;
1189
+ /**
1190
+ * Maps a database record onto a `SavedFilter`.
1191
+ *
1192
+ * `CreatedByUser` needs care: the view computes it as the *string* `'true'` or
1193
+ * `'false'` (and `'False'` on the synthetic row), not as a bit.
1194
+ */
1195
+ function toSavedFilter(record) {
1196
+ return {
1197
+ filterId: record.FilterID ?? -1,
1198
+ primKey: record.PrimKey ?? "",
1199
+ name: record.FilterName ?? "",
1200
+ criteria: record.FilterCriteria ?? "",
1201
+ dbObjectId: record.DBObjectID ?? "",
1202
+ accessLevel: toAccessLevel(record.AccessLevel),
1203
+ createdByUser: toBoolean(record.CreatedByUser),
1204
+ createdBy: record.CreatedBy ?? "",
1205
+ domain: record.Domain ?? null,
1206
+ crossDomain: toBoolean(record.CrossDomain),
1207
+ isPersonallyShared: toBoolean(record.IsPersonallyShared),
1208
+ hideCriteria: toBoolean(record.HideFilterCriteria),
1209
+ headerText: record.OptionalHeaderText || null,
1210
+ comment: record.OptionalComment || null,
1211
+ parameters: record.Parameters || null,
1212
+ reportTitle: record.ReportTitle || null,
1213
+ created: toDate(record.Created),
1214
+ updated: toDate(record.Updated)
1215
+ };
1216
+ }
1217
+ function toAccessLevel(value) {
1218
+ if (value === "Manager" || value === "Editor") return value;
1219
+ return "Reader";
1220
+ }
1221
+ function toBoolean(value) {
1222
+ if (typeof value === "string") return value.toLowerCase() === "true";
1223
+ return Boolean(value);
1224
+ }
1225
+ function toDate(value) {
1226
+ if (!value) return null;
1227
+ if (value instanceof Date) return value;
1228
+ let date = new Date(value);
1229
+ return Number.isNaN(date.getTime()) ? null : date;
1230
+ }
1231
+ /** Drops the synthetic "No Filter" row and sorts by name. */
1232
+ function toSavedFilters(records) {
1233
+ return records.filter((record) => (record.FilterID ?? -1) !== -1).map(toSavedFilter).sort((a, b) => a.name.localeCompare(b.name));
1234
+ }
1235
+ /**
1236
+ * Splits filters into the two branches the Windows tree shows: the ones the user
1237
+ * created, and the ones that have been shared with them.
1238
+ */
1239
+ function partitionSavedFilters(filters) {
1240
+ let mine = [];
1241
+ let shared = [];
1242
+ for (let filter of filters) if (filter.createdByUser) mine.push(filter);
1243
+ else shared.push(filter);
1244
+ return {
1245
+ mine,
1246
+ shared
1247
+ };
1248
+ }
1249
+ function findSavedFilter(filters, filterId) {
1250
+ if (filterId == null) return void 0;
1251
+ return filters.find((filter) => filter.filterId === filterId);
1252
+ }
1253
+ /** True when the user may overwrite the filter's criteria. */
1254
+ function canEditSavedFilter(filter) {
1255
+ return filter.accessLevel === "Editor" || filter.accessLevel === "Manager";
1256
+ }
1257
+ /** True when the user may change who the filter is shared with. */
1258
+ function canShareSavedFilter(filter) {
1259
+ return filter.accessLevel === "Manager";
1260
+ }
1261
+ /**
1262
+ * True when the user may rename or delete the filter.
1263
+ *
1264
+ * `sstp_WebSiteCMS_FilterBuilder_RenameFilter` and `…_DeleteFilter` both require
1265
+ * `CreatedBy = SUSER_SNAME()` — the manager-access branch is commented out in
1266
+ * both procedures, deliberately, because the UI only ever offers these for a
1267
+ * user's own filters.
1268
+ */
1269
+ function canRenameSavedFilter(filter) {
1270
+ return filter.createdByUser;
1271
+ }
1272
+ const canDeleteSavedFilter = canRenameSavedFilter;
1273
+ /**
1274
+ * True when the user may toggle the cross-domain flag.
1275
+ *
1276
+ * `sstp_Database_Filters_SetCrossDomain` also filters on
1277
+ * `CreatedBy = SUSER_SNAME()`.
1278
+ */
1279
+ const canSetCrossDomain = canRenameSavedFilter;
1280
+
1281
+ //#endregion
1282
+ //#region src/getUserImage.ts
1283
+ const sizeMap = {
1284
+ xs: 64,
1285
+ sm: 128,
1286
+ md: 256,
1287
+ lg: 512,
1288
+ xl: void 0
1289
+ };
1290
+ function getUserImage(primKeyOrOptions, login, hash, size = "xs") {
1291
+ if (primKeyOrOptions && typeof primKeyOrOptions === "object") return getUserImage(primKeyOrOptions.primKey, primKeyOrOptions.login, primKeyOrOptions.hash, primKeyOrOptions.size);
1292
+ if (!primKeyOrOptions || !hash) return "";
1293
+ let sizePx = sizeMap[size];
1294
+ return `/api/data/blob/EmployeesLookup/${primKeyOrOptions}/Image/${encodeURIComponent(login ?? "")}${login ? "." : ""}${encodeURIComponent(hash)}.jpg${sizePx ? `?width=${sizePx}` : ""}`;
1295
+ }
1296
+
1297
+ //#endregion
1298
+ //#region src/localize.ts
1299
+ /**
1300
+ * Localization function for tagged templates. Replaces the arguments
1301
+ * with $n, where n is the index, before asking Appframe to translate
1302
+ * the string.
1303
+ *
1304
+ * For example, if you call localize`Page ${2} or ${5}`, the string
1305
+ * "Page $0 of $1" will be sent to Appframe, and for norwegian,
1306
+ * "Side 2 av 5" will be returned.
1307
+ *
1308
+ * @param stringParts
1309
+ * @param args
1310
+ * @returns Translated string
1311
+ */
1312
+ function localize(stringParts, ...args) {
1313
+ invariant(Array.isArray(stringParts) && stringParts.length === args.length + 1, "Method 'localize' must be used as a tag function");
1314
+ let stringToLocalize = stringParts.map((s, i) => i === stringParts.length - 1 ? s : `${s}$${i}`).join("");
1315
+ let localized = getLocalizedString(stringToLocalize);
1316
+ args.forEach((arg, index) => {
1317
+ localized = localized.replace(`$${index}`, arg);
1318
+ });
1319
+ return localized;
1320
+ }
1321
+
1322
+ //#endregion
1323
+ //#region src/report/recordSource.ts
1324
+ const XML_ENTITIES = {
1325
+ amp: "&",
1326
+ lt: "<",
1327
+ gt: ">",
1328
+ quot: "\"",
1329
+ apos: "'"
1330
+ };
1331
+ /** Resolves the XML entities the .NET serializer emits. */
1332
+ function decodeXml(value) {
1333
+ return value.replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (match, entity) => {
1334
+ if (entity.startsWith("#x") || entity.startsWith("#X")) return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));
1335
+ if (entity.startsWith("#")) return String.fromCodePoint(Number.parseInt(entity.slice(1), 10));
1336
+ return XML_ENTITIES[entity.toLowerCase()] ?? match;
1337
+ });
1338
+ }
1339
+ /** Escapes a value for use as XML text or as an attribute value. */
1340
+ function encodeXml(value) {
1341
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1342
+ }
1343
+ /**
1344
+ * The text content of the first `<name>` element, or `null` when the element is
1345
+ * missing or self-closing (`<FilterString />`, which the serializer writes for
1346
+ * an empty value).
1347
+ */
1348
+ function readElement(xml, name) {
1349
+ let match = new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)</${name}>`).exec(xml);
1350
+ if (!match) return null;
1351
+ let value = decodeXml(match[1]).trim();
1352
+ return value === "" ? null : value;
1353
+ }
1354
+ /** The text content of every `<name>` element, in document order. */
1355
+ function readElements(xml, name) {
1356
+ return [...xml.matchAll(new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)</${name}>`, "g"))].map((match) => decodeXml(match[1]).trim());
1357
+ }
1358
+ /**
1359
+ * The CLR types the designer writes on a select column. Anything else — and a
1360
+ * column with no `DataType` at all, which is what it writes for strings — is
1361
+ * treated as text.
1362
+ */
1363
+ const COLUMN_TYPES = {
1364
+ Byte: "number",
1365
+ Decimal: "number",
1366
+ Double: "number",
1367
+ Int16: "number",
1368
+ Int32: "number",
1369
+ Int64: "number",
1370
+ Single: "number",
1371
+ Boolean: "boolean",
1372
+ DateTime: "date"
1373
+ };
1374
+ /** The columns of a `<SelectColumns>` block, in document order. */
1375
+ function readSelectColumns(xml) {
1376
+ let block = /<SelectColumns>([\s\S]*?)<\/SelectColumns>/.exec(xml)?.[1] ?? "";
1377
+ let columns = [];
1378
+ for (let match of block.matchAll(/<afSelectColumn>([\s\S]*?)<\/afSelectColumn>/g)) {
1379
+ let name = readElement(match[1], "Name");
1380
+ if (!name) continue;
1381
+ columns.push({
1382
+ name,
1383
+ type: COLUMN_TYPES[readElement(match[1], "DataType") ?? ""] ?? "string"
1384
+ });
1385
+ }
1386
+ return columns;
1387
+ }
1388
+ /**
1389
+ * Reads the parts of an `afRecordSource` a web client can act on: the view, the
1390
+ * selected columns and the design-time filter.
1391
+ *
1392
+ * Returns `null` for anything that is not a record source, so a missing or
1393
+ * empty `RecordSource` column simply means "no lookup".
1394
+ */
1395
+ function parseRecordSource(xml) {
1396
+ if (!xml || !xml.includes("<afRecordSource")) return null;
1397
+ let viewName = readElement(xml, "ViewName");
1398
+ if (!viewName) return null;
1399
+ let maxRecords = readElement(xml, "MaxRecords");
1400
+ return {
1401
+ viewName,
1402
+ columns: readSelectColumns(xml),
1403
+ whereClause: readElement(xml, "WhereClause"),
1404
+ filterString: readElement(xml, "FilterString"),
1405
+ maxRecords: maxRecords === null || maxRecords === "0" ? null : Number(maxRecords)
1406
+ };
1407
+ }
1408
+
1409
+ //#endregion
1410
+ //#region src/report/parameters.ts
1411
+ /**
1412
+ * Report parameters: mapping the metadata records onto something renderable,
1413
+ * and the XML the parameter values are stored as on a saved filter.
1414
+ */
1415
+ const PARAMETER_TYPES = [
1416
+ "String",
1417
+ "Integer",
1418
+ "Double",
1419
+ "Date",
1420
+ "Boolean"
1421
+ ];
1422
+ /**
1423
+ * A default value naming a stored procedure, e.g. `astp_Reports_CurrentPeriod`.
1424
+ *
1425
+ * The Windows launcher executes the procedure and uses the first column of the
1426
+ * first row. The web client cannot execute an arbitrary procedure, so these are
1427
+ * resolved through the report endpoint instead.
1428
+ */
1429
+ const PROCEDURE_DEFAULT = /^[a-z]stp_/i;
1430
+ /** True when a `DefaultValue` names a stored procedure rather than a literal. */
1431
+ function isProcedureDefault(defaultValue) {
1432
+ return typeof defaultValue === "string" && PROCEDURE_DEFAULT.test(defaultValue.trim());
1433
+ }
1434
+ /** The choices of a parameter, one per line of its `Items` column. */
1435
+ function parseParameterItems(items) {
1436
+ if (!items) return [];
1437
+ return items.split(/\r\n|\r|\n/).map((item) => item.trim()).filter((item) => item !== "");
1438
+ }
1439
+ function toParameterType(dataType) {
1440
+ return PARAMETER_TYPES.find((type) => type.toLowerCase() === dataType?.trim().toLowerCase()) ?? "String";
1441
+ }
1442
+ /**
1443
+ * The editor a parameter should use. A lookup or a fixed item list wins over the
1444
+ * data type, which is what the Windows launcher does as well.
1445
+ */
1446
+ function toParameterEditor(type, hasLookup, hasItems) {
1447
+ if (hasLookup) return "lookup";
1448
+ if (hasItems) return "select";
1449
+ switch (type) {
1450
+ case "Integer":
1451
+ case "Double": return "number";
1452
+ case "Date": return "date";
1453
+ case "Boolean": return "boolean";
1454
+ default: return "text";
1455
+ }
1456
+ }
1457
+ /** Maps a `sviw_WinClient_ReportsParameters` record onto a `ReportParameter`. */
1458
+ function toReportParameter(record) {
1459
+ let name = record.Name ?? "";
1460
+ let type = toParameterType(record.DataType);
1461
+ let items = parseParameterItems(record.Items);
1462
+ let recordSource = parseRecordSource(record.RecordSource);
1463
+ let valueMember = record.ValueMember ?? null;
1464
+ if (recordSource && !valueMember) valueMember = recordSource.columns[0]?.name ?? null;
1465
+ let displayMember = recordSource?.columns.find((column) => column.name !== valueMember)?.name ?? null;
1466
+ let hasLookup = Boolean(recordSource && valueMember);
1467
+ return {
1468
+ name,
1469
+ label: record.Label?.trim() || name,
1470
+ description: record.Description?.trim() || null,
1471
+ type,
1472
+ editor: toParameterEditor(type, hasLookup, items.length > 0),
1473
+ defaultValue: record.DefaultValue ?? null,
1474
+ items,
1475
+ recordSource: hasLookup ? recordSource : null,
1476
+ valueMember: hasLookup ? valueMember : null,
1477
+ displayMember: hasLookup ? displayMember : null,
1478
+ sortOrder: record.SortOrder ?? 0,
1479
+ lookupWidth: record.LookupWidth ?? null,
1480
+ lookupHeight: record.LookupHeight ?? null
1481
+ };
1482
+ }
1483
+ /** Maps and sorts a report's parameter records. */
1484
+ function toReportParameters(records) {
1485
+ return records.filter((record) => record.Name).map(toReportParameter).sort((a, b) => a.sortOrder - b.sortOrder || a.label.localeCompare(b.label));
1486
+ }
1487
+ /** Converts a raw value to the type a parameter expects. */
1488
+ function coerceParameterValue(parameter, value) {
1489
+ if (value === null || value === void 0 || value === "") return parameter.type === "Boolean" ? false : null;
1490
+ switch (parameter.type) {
1491
+ case "Boolean": return typeof value === "boolean" ? value : /^(true|1|ja|yes)$/i.test(String(value));
1492
+ case "Integer": {
1493
+ let parsed = Number.parseInt(String(value), 10);
1494
+ return Number.isNaN(parsed) ? null : parsed;
1495
+ }
1496
+ case "Double": {
1497
+ let parsed = Number(String(value).replace(",", "."));
1498
+ return Number.isNaN(parsed) ? null : parsed;
1499
+ }
1500
+ default: return String(value);
1501
+ }
1502
+ }
1503
+ /**
1504
+ * The initial values for a set of parameters.
1505
+ *
1506
+ * Defaults naming a stored procedure are left unset: they have to be resolved
1507
+ * server-side, and the caller fills them in once they are.
1508
+ */
1509
+ function getDefaultParameterValues(parameters) {
1510
+ let values = {};
1511
+ for (let parameter of parameters) values[parameter.name] = isProcedureDefault(parameter.defaultValue) ? coerceParameterValue(parameter, null) : coerceParameterValue(parameter, parameter.defaultValue);
1512
+ return values;
1513
+ }
1514
+ function toXmlValue(parameter, value) {
1515
+ if (value === null || value === void 0) return "";
1516
+ if (typeof value === "boolean") return value ? "True" : "False";
1517
+ return String(value);
1518
+ }
1519
+ /**
1520
+ * Serializes parameter values the way the Windows filter builder does, so that
1521
+ * a filter saved on the web is readable in the Windows client and the other way
1522
+ * around.
1523
+ *
1524
+ * ```xml
1525
+ * <Parameters Version="1">
1526
+ * <Parameter Name="Period" Type="Integer">202601</Parameter>
1527
+ * </Parameters>
1528
+ * ```
1529
+ */
1530
+ function serializeParameters(parameters, values) {
1531
+ return `<Parameters Version="1">\n${parameters.map((parameter) => {
1532
+ let value = toXmlValue(parameter, values[parameter.name] ?? null);
1533
+ return ` <Parameter Name="${encodeXml(parameter.name)}" Type="${parameter.type}">${encodeXml(value)}</Parameter>`;
1534
+ }).join("\n")}\n</Parameters>`;
1535
+ }
1536
+ /**
1537
+ * Reads the values back out of the XML stored on a saved filter. Values are
1538
+ * returned as strings and coerced against the report's own parameters by
1539
+ * `restoreParameterValues`, since the XML may name parameters the report no
1540
+ * longer has.
1541
+ */
1542
+ function parseParameters(xml) {
1543
+ if (!xml) return {};
1544
+ let values = {};
1545
+ for (let match of xml.matchAll(/<Parameter\s+([^>]*?)\/?>(?:([\s\S]*?)<\/Parameter>)?/g)) {
1546
+ let name = /Name\s*=\s*"([^"]*)"/.exec(match[1])?.[1];
1547
+ if (!name) continue;
1548
+ values[name] = readElement(match[0], "Parameter") ?? "";
1549
+ }
1550
+ return values;
1551
+ }
1552
+ /**
1553
+ * Applies the values stored on a saved filter to a report's parameters, keeping
1554
+ * the defaults for anything the filter does not mention.
1555
+ */
1556
+ function restoreParameterValues(parameters, xml) {
1557
+ let stored = parseParameters(xml);
1558
+ let values = getDefaultParameterValues(parameters);
1559
+ for (let parameter of parameters) if (parameter.name in stored) values[parameter.name] = coerceParameterValue(parameter, stored[parameter.name]);
1560
+ return values;
1561
+ }
1562
+
1563
+ //#endregion
1564
+ //#region src/report/parameterDefaults.ts
1565
+ /**
1566
+ * Resolving report parameter defaults that name a stored procedure.
1567
+ *
1568
+ * A `DefaultValue` matching `^[a-z]stp_` names a procedure that produces the
1569
+ * default rather than being the default itself. Executing it is a server
1570
+ * concern, and the framework already exposes it through the `WebsiteCMS`
1571
+ * `api/reporting/filters` route.
1572
+ */
1573
+ /**
1574
+ * Runs the stored procedure a parameter's default names and returns the value
1575
+ * it produces — the first column of the first row, the way the Windows launcher
1576
+ * reads it.
1577
+ *
1578
+ * Returns `null` when the parameter has no procedure default or the procedure
1579
+ * produced no rows.
1580
+ */
1581
+ async function fetchParameterDefault(reportId, parameter, signal) {
1582
+ if (!parameter.defaultValue || !isProcedureDefault(parameter.defaultValue)) return null;
1583
+ let response = await fetch(`/api/reporting/filters/${encodeURIComponent(reportId)}/GetParameterDefaultValue`, {
1584
+ body: JSON.stringify({ parameterName: parameter.name }),
1585
+ credentials: "same-origin",
1586
+ headers: {
1587
+ "Content-Type": "application/json",
1588
+ "X-Requested-With": "XMLHttpRequest"
1589
+ },
1590
+ method: "POST",
1591
+ signal
1592
+ });
1593
+ if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);
1594
+ return firstValue(await response.json());
1595
+ }
1596
+ /**
1597
+ * Resolves every procedure default of a report in parallel and merges the
1598
+ * results over the literal defaults.
1599
+ *
1600
+ * A parameter whose procedure fails is left at its literal default rather than
1601
+ * failing the whole form — the user can still type a value.
1602
+ */
1603
+ async function resolveParameterDefaults(reportId, parameters, literalDefaults, signal) {
1604
+ let dynamic = parameters.filter((parameter) => isProcedureDefault(parameter.defaultValue ?? ""));
1605
+ if (dynamic.length === 0) return literalDefaults;
1606
+ let resolved = await Promise.all(dynamic.map(async (parameter) => {
1607
+ try {
1608
+ return [parameter.name, await fetchParameterDefault(reportId, parameter, signal)];
1609
+ } catch {
1610
+ return [parameter.name, null];
1611
+ }
1612
+ }));
1613
+ let values = { ...literalDefaults };
1614
+ for (let [name, value] of resolved) if (value !== null) values[name] = value;
1615
+ return values;
1616
+ }
1617
+ /** The first column of the first row of whichever result set came back. */
1618
+ function firstValue(result) {
1619
+ let row = (Array.isArray(result) ? result : Object.values(result).find((value) => Array.isArray(value)))?.[0];
1620
+ if (row === void 0 || row === null) return null;
1621
+ if (Array.isArray(row)) return row[0] ?? null;
1622
+ if (typeof row === "object") return Object.values(row)[0] ?? null;
1623
+ return row;
1624
+ }
1625
+
1626
+ //#endregion
1627
+ //#region src/report/render.ts
1628
+ /**
1629
+ * Rendering a report through the framework's report route.
1630
+ *
1631
+ * The route is a CMS code module owned by the Appframe framework
1632
+ * (`WebsiteCMS.Reports`), registered on
1633
+ * `api/report/{ReportID}/{FileName}.{Extension}`. Everything here builds
1634
+ * requests for it — there is no report endpoint of our own.
1635
+ */
1636
+ /**
1637
+ * The file extension each format is requested with. The route only accepts
1638
+ * `(pdf|csv|xlsx?|html|xbm|mht|rtf|txt)`, which is why `TEXT` is `txt` and
1639
+ * `IMAGE` is `xbm` rather than the format name.
1640
+ */
1641
+ const REPORT_EXTENSIONS = {
1642
+ CSV: "csv",
1643
+ HTML: "html",
1644
+ IMAGE: "xbm",
1645
+ MHT: "mht",
1646
+ PDF: "pdf",
1647
+ RTF: "rtf",
1648
+ TEXT: "txt",
1649
+ XLS: "xls",
1650
+ XLSX: "xlsx"
1651
+ };
1652
+ /** The media type each format is served as, for previewing a rendered report. */
1653
+ const REPORT_MEDIA_TYPES = {
1654
+ CSV: "text/csv",
1655
+ HTML: "text/html",
1656
+ IMAGE: "image/x-xbitmap",
1657
+ MHT: "message/rfc822",
1658
+ PDF: "application/pdf",
1659
+ RTF: "text/enriched",
1660
+ TEXT: "text/plain",
1661
+ XLS: "application/vnd.ms-excel",
1662
+ XLSX: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
1663
+ };
1664
+ /** The extension a format is requested with. */
1665
+ function getReportExtension(format) {
1666
+ return REPORT_EXTENSIONS[format];
1667
+ }
1668
+ /** The media type a format is served as. */
1669
+ function getReportMediaType(format) {
1670
+ return REPORT_MEDIA_TYPES[format];
1671
+ }
1672
+ /**
1673
+ * Characters that must not reach the file name, because it is a path segment of
1674
+ * the route: separators, the extension delimiter, the query and fragment
1675
+ * delimiters, and control characters.
1676
+ */
1677
+ const UNSAFE_FILE_NAME_CHARACTERS = /[\\/:*?"<>|.#&+%\u0000-\u001f]/g;
1678
+ /**
1679
+ * The name a rendered report is downloaded as, including its extension.
1680
+ *
1681
+ * The file name is part of the route rather than a query parameter, so anything
1682
+ * that would change the path is replaced.
1683
+ */
1684
+ function getReportFileName(options) {
1685
+ let safe = (options.fileName ?? options.reportId).trim().replace(UNSAFE_FILE_NAME_CHARACTERS, "-").replace(/-{2,}/g, "-").replace(/^-|-$/g, "").trim();
1686
+ return `${safe === "" ? options.reportId : safe}.${getReportExtension(options.format)}`;
1687
+ }
1688
+ /**
1689
+ * The route is always on the same origin, but a `Request` needs an absolute
1690
+ * URL, so the path is resolved against the document when there is one.
1691
+ */
1692
+ function toRequestUrl(path) {
1693
+ let base = window.location?.href;
1694
+ return base ? new URL(path, base).toString() : path;
1695
+ }
1696
+ /**
1697
+ * The request that renders a report.
1698
+ *
1699
+ * A report without parameters is a plain `GET`, so it can be opened directly in
1700
+ * a new tab. As soon as there are parameters or a header the options go in a
1701
+ * JSON body, which the route only reads from a `POST`.
1702
+ *
1703
+ * `filter` is always sent alongside `parameters`: the route reads the filter out
1704
+ * of the body *guarded by the presence of `parameters`*, and reads it with an
1705
+ * indexer that throws when the key is missing.
1706
+ */
1707
+ function getReportRequest(options) {
1708
+ let { domain, filter, headerText, hideFilterString, parameters, reportId, signal, timezone } = options;
1709
+ let fileName = getReportFileName(options);
1710
+ let url = `/api/report/${encodeURIComponent(reportId)}/${encodeURIComponent(fileName)}`;
1711
+ let query = new URLSearchParams();
1712
+ let entries = toParameterEntries(parameters);
1713
+ let needsBody = entries.length > 0 || Boolean(headerText) || hideFilterString === true;
1714
+ if (domain) query.set("Domain", domain);
1715
+ query.set("timezone", String(timezone ?? -(/* @__PURE__ */ new Date()).getTimezoneOffset() / 60));
1716
+ if (!needsBody) {
1717
+ if (filter) query.set("Filter", filter);
1718
+ return new Request(toRequestUrl(`${url}?${query}`), {
1719
+ credentials: "same-origin",
1720
+ signal
1721
+ });
1722
+ }
1723
+ let body = {
1724
+ filter: filter ?? "",
1725
+ parameters: entries
1726
+ };
1727
+ if (headerText) body.optionalheader = headerText;
1728
+ if (hideFilterString === true) body.showfiltercriteria = "true";
1729
+ return new Request(toRequestUrl(`${url}?${query}`), {
1730
+ body: JSON.stringify(body),
1731
+ credentials: "same-origin",
1732
+ headers: {
1733
+ "Content-Type": "application/json",
1734
+ "X-Requested-With": "XMLHttpRequest"
1735
+ },
1736
+ method: "POST",
1737
+ signal
1738
+ });
1739
+ }
1740
+ /**
1741
+ * Renders a report and resolves with the rendered file.
1742
+ *
1743
+ * The route answers with a JSON body carrying an `error` when rendering fails,
1744
+ * rather than with a failing status, so a JSON response is turned into an error
1745
+ * here.
1746
+ */
1747
+ async function renderReport(options) {
1748
+ let response = await fetch(getReportRequest(options));
1749
+ if ((response.headers.get("content-type") ?? "").includes("application/json")) {
1750
+ let data = await response.json();
1751
+ throw new Error(data.error ?? "Failed to render report");
1752
+ }
1753
+ if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);
1754
+ return response.blob();
1755
+ }
1756
+ /** Renders a report and saves it, reporting progress as it downloads. */
1757
+ function downloadReport(options) {
1758
+ return downloadRequest(getReportRequest(options), {
1759
+ fileName: getReportFileName(options),
1760
+ onProgress: options.onProgress,
1761
+ signal: options.signal
1762
+ });
1763
+ }
1764
+ /**
1765
+ * Renders a report and opens it in a new tab.
1766
+ *
1767
+ * The blob is rendered first rather than pointing a tab at the route, so a
1768
+ * failure surfaces as an error here instead of as a tab showing JSON, and so
1769
+ * reports with parameters — which have to be posted — can be previewed too.
1770
+ */
1771
+ async function openReport(options) {
1772
+ let blob = await renderReport(options);
1773
+ let url = URL.createObjectURL(blob.type ? blob : new Blob([blob], { type: getReportMediaType(options.format) }));
1774
+ if (!window.open(url, "_blank", "noopener")) {
1775
+ URL.revokeObjectURL(url);
1776
+ throw new Error("The report could not be opened. Allow pop-ups for this site and try again.");
1777
+ }
1778
+ window.setTimeout(() => URL.revokeObjectURL(url), 6e4);
1779
+ }
1780
+ /**
1781
+ * Renders a report and opens the browser's print dialog for it.
1782
+ *
1783
+ * The report is loaded into an offscreen iframe rather than a new tab, so the
1784
+ * print dialog opens over the launcher and the user is not left with a stray
1785
+ * tab afterwards. Browsers that will not print an embedded document fall back
1786
+ * to opening it, which leaves the user one keystroke from printing.
1787
+ */
1788
+ async function printReport(options) {
1789
+ let document_ = window.document;
1790
+ if (!document_?.body) return openReport(options);
1791
+ let blob = await renderReport(options);
1792
+ let url = URL.createObjectURL(blob.type ? blob : new Blob([blob], { type: getReportMediaType(options.format) }));
1793
+ let frame = document_.createElement("iframe");
1794
+ frame.setAttribute("aria-hidden", "true");
1795
+ frame.style.cssText = "position:fixed;inset-block-start:0;inset-inline-start:0;inline-size:1px;block-size:1px;border:0;visibility:hidden";
1796
+ let cleanUp = () => {
1797
+ frame.remove();
1798
+ URL.revokeObjectURL(url);
1799
+ };
1800
+ try {
1801
+ await new Promise((resolve, reject) => {
1802
+ frame.addEventListener("load", () => resolve(), { once: true });
1803
+ frame.addEventListener("error", () => reject(/* @__PURE__ */ new Error("The report could not be loaded for printing")), { once: true });
1804
+ frame.src = url;
1805
+ document_.body.append(frame);
1806
+ });
1807
+ frame.contentWindow?.focus();
1808
+ frame.contentWindow?.print();
1809
+ } catch {
1810
+ cleanUp();
1811
+ return openReport(options);
1812
+ }
1813
+ window.setTimeout(cleanUp, 6e4);
1814
+ }
1815
+ /**
1816
+ * Parameters in the shape the route expects — `{ name, value }` objects.
1817
+ *
1818
+ * Empty values are dropped: the route skips them anyway, and a report falls back
1819
+ * to its own default when a parameter is not sent.
1820
+ */
1821
+ function toParameterEntries(parameters) {
1822
+ if (!parameters) return [];
1823
+ return Object.entries(parameters).filter(([, value]) => value !== null && value !== void 0 && value !== "").map(([name, value]) => ({
1824
+ name,
1825
+ value: typeof value === "boolean" ? String(value) : value
1826
+ }));
1827
+ }
1828
+
1829
+ //#endregion
1830
+ //#region src/report/report.ts
1831
+ /**
1832
+ * Mapping a `sviw_WinClient_MyReports` record onto the report model, including
1833
+ * which output formats the report offers.
1834
+ */
1835
+ function isSet(value) {
1836
+ return value === true || value === 1;
1837
+ }
1838
+ /**
1839
+ * The formats a report may be rendered to, in the order the launcher offers
1840
+ * them.
1841
+ *
1842
+ * `FormatCSV` covers the whole spreadsheet family: the Windows launcher enables
1843
+ * "save as XLS" and "save as XLSX" from the same flag, because they all come out
1844
+ * of the same DevExpress export.
1845
+ */
1846
+ function getReportFormats(record) {
1847
+ let formats = [];
1848
+ if (isSet(record.FormatPDF)) formats.push("PDF");
1849
+ if (isSet(record.FormatCSV)) formats.push("XLSX", "XLS", "CSV");
1850
+ if (isSet(record.FormatHTML)) formats.push("HTML");
1851
+ if (isSet(record.FormatRTF)) formats.push("RTF");
1852
+ if (isSet(record.FormatMHT)) formats.push("MHT");
1853
+ if (isSet(record.FormatTEXT)) formats.push("TEXT");
1854
+ if (isSet(record.FormatIMAGE)) formats.push("IMAGE");
1855
+ return formats;
1856
+ }
1857
+ /** Maps a report record onto the model the launcher renders. */
1858
+ function toReport(record) {
1859
+ let recordSource = parseRecordSource(record.RecordSource);
1860
+ return {
1861
+ reportId: record.ReportID ?? "",
1862
+ shortId: record.ShortID ?? null,
1863
+ title: record.Title?.trim() || null,
1864
+ description: record.Description?.trim() || null,
1865
+ viewName: recordSource?.viewName ?? null,
1866
+ initialFilter: recordSource?.filterString ?? null,
1867
+ hasTitle: isSet(record.HasTitle),
1868
+ hasHeader: isSet(record.HasHeader),
1869
+ formats: getReportFormats(record),
1870
+ timeout: record.Timeout ?? null
1871
+ };
1872
+ }
1873
+
1874
+ //#endregion
1875
+ //#region src/alert.ts
1876
+ const template = `
579
1877
  <dialog class="alert-dialog">
580
1878
  <form method="dialog">
581
1879
  <article></article>
@@ -585,133 +1883,227 @@ var af;
585
1883
  </form>
586
1884
  </dialog>
587
1885
  `;
588
- if (window.document && !document.querySelector("#AlertDialogTemplate")) {
589
- let $template = document.createElement("template");
590
- $template.id = "AlertDialogTemplate";
591
- $template.innerHTML = template;
592
- document.body.append($template);
593
- }
594
- function waitForDialog(dialog, cancelValue = "No") {
595
- return new Promise((resolve) => {
596
- let controller = new AbortController();
597
- dialog.addEventListener(
598
- "close",
599
- () => {
600
- resolve(dialog.returnValue);
601
- controller.abort();
602
- },
603
- { signal: controller.signal }
604
- );
605
- dialog.addEventListener(
606
- "cancel",
607
- () => {
608
- resolve(cancelValue);
609
- controller.abort();
610
- },
611
- { signal: controller.signal }
612
- );
613
- });
614
- }
615
- var alertDialogPromiseMap = /* @__PURE__ */ new Map();
616
- async function openAlertDialog({ buttons, content, className, id, title }) {
617
- if (id && alertDialogPromiseMap.has(id)) {
618
- return await alertDialogPromiseMap.get(id);
619
- }
620
- let $template = document.querySelector("#AlertDialogTemplate");
621
- if (!$template) throw Error("No alert dialog template found");
622
- let $dialog = $template.content.firstElementChild?.cloneNode(true);
623
- let $content = $dialog?.querySelector("article");
624
- let $menu = $dialog?.querySelector("footer menu");
625
- if (!$dialog || !$content || !$menu) throw Error("Invalid alert dialog template");
626
- if (className) {
627
- for (const className_ of className.split(/\s+/)) {
628
- $dialog?.classList.add(className_);
629
- }
630
- }
631
- if (title) {
632
- let $header = document.createElement("header");
633
- $header.append(title);
634
- $content.parentNode?.insertBefore($header, $content);
635
- }
636
- $content.appendChild(typeof content === "string" ? document.createTextNode(content) : content);
637
- for (let { label, value, primary } of buttons) {
638
- let listItem = document.createElement("li");
639
- let buttonElem = document.createElement("button");
640
- buttonElem.value = value;
641
- if (primary) {
642
- buttonElem.classList.add("primary");
643
- }
644
- buttonElem.textContent = label;
645
- listItem.appendChild(buttonElem);
646
- $menu.appendChild(buttonElem);
647
- }
648
- document.body.appendChild($dialog);
649
- $dialog.showModal();
650
- let dialogPromise = waitForDialog($dialog).then((returnValue) => {
651
- if (id && alertDialogPromiseMap.has(id)) {
652
- alertDialogPromiseMap.delete(id);
653
- }
654
- if ($dialog) document.body.removeChild($dialog);
655
- return returnValue;
656
- });
657
- if (id) {
658
- alertDialogPromiseMap.set(id, dialogPromise);
659
- }
660
- return await dialogPromise;
661
- }
662
- var ConfirmButtons = /* @__PURE__ */ ((ConfirmButtons2) => {
663
- ConfirmButtons2[ConfirmButtons2["YesNo"] = 0] = "YesNo";
664
- ConfirmButtons2[ConfirmButtons2["OkCancel"] = 1] = "OkCancel";
665
- return ConfirmButtons2;
666
- })(ConfirmButtons || {});
667
- async function confirm(prompt, options = {}) {
668
- let { buttons: optionButtons = 0 /* YesNo */, title } = options;
669
- let buttons = optionButtons === 1 /* OkCancel */ ? [
670
- { label: getLocalizedString("OK"), value: "yes", primary: true },
671
- { label: getLocalizedString("Cancel"), value: "no" }
672
- ] : [
673
- { label: getLocalizedString("Yes"), value: "yes", primary: true },
674
- { label: getLocalizedString("No"), value: "no" }
675
- ];
676
- let result = await openAlertDialog({ content: prompt, buttons, className: "alert-dialog-confirm", title });
677
- return result === "yes";
678
- }
679
- async function alert(prompt, options = {}) {
680
- await openAlertDialog({
681
- content: prompt,
682
- className: "alert-dialog-alert",
683
- buttons: [{ label: getLocalizedString("OK"), value: "ok", primary: true }],
684
- ...options
685
- });
686
- }
687
-
688
- // src/settings.ts
689
- function getKey(article2) {
690
- const articleKey = article2 ?? window.af?.article?.id ?? window.window?.location.pathname.substring(1).split("/")[0];
691
- return `${articleKey}.${window.af?.userSession.login ?? "anonymous"}`;
692
- }
693
- function getSettings(setting, article2) {
694
- if (!window.af?.userSession) return null;
695
- const key = getKey(article2);
696
- const settings = JSON.parse(localStorage.getItem(key) || "{}");
697
- if (setting) {
698
- return settings[setting] || null;
699
- }
700
- return settings;
701
- }
702
- function saveSettings(setting, value, article2) {
703
- if (!window.af?.userSession) return;
704
- const key = getKey(article2);
705
- let userSettings = JSON.parse(localStorage.getItem(key) || "{}");
706
- if (typeof value !== "undefined") {
707
- userSettings[setting] = value;
708
- } else {
709
- userSettings = setting;
710
- }
711
- localStorage.setItem(key, JSON.stringify(userSettings));
712
- }
713
-
714
- // src/index.ts
715
- var version = "2.11.10";
716
- return __toCommonJS(index_exports);
717
- })();
1886
+ function addDialogTemplate() {
1887
+ if (document.querySelector("#AlertDialogTemplate")) return;
1888
+ let $template = document.createElement("template");
1889
+ $template.id = "AlertDialogTemplate";
1890
+ $template.innerHTML = template;
1891
+ document.body.append($template);
1892
+ }
1893
+ if (window.document) {
1894
+ if (document.body) addDialogTemplate();
1895
+ else document.addEventListener("DOMContentLoaded", addDialogTemplate, { once: true });
1896
+ }
1897
+ function waitForDialog(dialog, cancelValue = "No") {
1898
+ return new Promise((resolve) => {
1899
+ let controller = new AbortController();
1900
+ dialog.addEventListener("close", () => {
1901
+ resolve(dialog.returnValue);
1902
+ controller.abort();
1903
+ }, { signal: controller.signal });
1904
+ dialog.addEventListener("cancel", () => {
1905
+ resolve(cancelValue);
1906
+ controller.abort();
1907
+ }, { signal: controller.signal });
1908
+ });
1909
+ }
1910
+ const alertDialogPromiseMap = /* @__PURE__ */ new Map();
1911
+ async function openAlertDialog({ buttons, content, className, id, title }) {
1912
+ if (id && alertDialogPromiseMap.has(id)) return await alertDialogPromiseMap.get(id);
1913
+ let $template = document.querySelector("#AlertDialogTemplate");
1914
+ if (!$template) throw Error("No alert dialog template found");
1915
+ let $dialog = $template.content.firstElementChild?.cloneNode(true);
1916
+ let $content = $dialog?.querySelector("article");
1917
+ let $menu = $dialog?.querySelector("footer menu");
1918
+ if (!$dialog || !$content || !$menu) throw Error("Invalid alert dialog template");
1919
+ if (className) for (const className_ of className.split(/\s+/)) $dialog?.classList.add(className_);
1920
+ if (title) {
1921
+ let $header = document.createElement("header");
1922
+ $header.append(title);
1923
+ $content.parentNode?.insertBefore($header, $content);
1924
+ }
1925
+ $content.appendChild(typeof content === "string" ? document.createTextNode(content) : content);
1926
+ for (let { label, value, primary } of buttons) {
1927
+ let listItem = document.createElement("li");
1928
+ let buttonElem = document.createElement("button");
1929
+ buttonElem.value = value;
1930
+ if (primary) buttonElem.classList.add("primary");
1931
+ buttonElem.textContent = label;
1932
+ listItem.appendChild(buttonElem);
1933
+ $menu.appendChild(buttonElem);
1934
+ }
1935
+ document.body.appendChild($dialog);
1936
+ $dialog.showModal();
1937
+ let dialogPromise = waitForDialog($dialog).then((returnValue) => {
1938
+ if (id && alertDialogPromiseMap.has(id)) alertDialogPromiseMap.delete(id);
1939
+ if ($dialog) document.body.removeChild($dialog);
1940
+ return returnValue;
1941
+ });
1942
+ if (id) alertDialogPromiseMap.set(id, dialogPromise);
1943
+ return await dialogPromise;
1944
+ }
1945
+ let ConfirmButtons = /* @__PURE__ */ function(ConfirmButtons) {
1946
+ ConfirmButtons[ConfirmButtons["YesNo"] = 0] = "YesNo";
1947
+ ConfirmButtons[ConfirmButtons["OkCancel"] = 1] = "OkCancel";
1948
+ return ConfirmButtons;
1949
+ }({});
1950
+ async function confirm(prompt, options = {}) {
1951
+ let { buttons: optionButtons = 0, title } = options;
1952
+ return await openAlertDialog({
1953
+ content: prompt,
1954
+ buttons: optionButtons === 1 ? [{
1955
+ label: getLocalizedString("OK"),
1956
+ value: "yes",
1957
+ primary: true
1958
+ }, {
1959
+ label: getLocalizedString("Cancel"),
1960
+ value: "no"
1961
+ }] : [{
1962
+ label: getLocalizedString("Yes"),
1963
+ value: "yes",
1964
+ primary: true
1965
+ }, {
1966
+ label: getLocalizedString("No"),
1967
+ value: "no"
1968
+ }],
1969
+ className: "alert-dialog-confirm",
1970
+ title
1971
+ }) === "yes";
1972
+ }
1973
+ async function alert(prompt, options = {}) {
1974
+ await openAlertDialog({
1975
+ content: prompt,
1976
+ className: "alert-dialog-alert",
1977
+ buttons: [{
1978
+ label: getLocalizedString("OK"),
1979
+ value: "ok",
1980
+ primary: true
1981
+ }],
1982
+ ...options
1983
+ });
1984
+ }
1985
+
1986
+ //#endregion
1987
+ //#region src/settings.ts
1988
+ function getKey(article) {
1989
+ return `${article ?? window.af?.article?.id ?? window.window?.location.pathname.substring(1).split("/")[0]}.${window.af?.userSession.login ?? "anonymous"}`;
1990
+ }
1991
+ function getSettings(setting, article) {
1992
+ if (!window.af?.userSession) return null;
1993
+ const key = getKey(article);
1994
+ const settings = JSON.parse(localStorage.getItem(key) || "{}");
1995
+ if (setting) return settings[setting] || null;
1996
+ return settings;
1997
+ }
1998
+ function saveSettings(setting, value, article) {
1999
+ if (!window.af?.userSession) return;
2000
+ const key = getKey(article);
2001
+ let userSettings = JSON.parse(localStorage.getItem(key) || "{}");
2002
+ if (typeof value !== "undefined") userSettings[setting] = value;
2003
+ else userSettings = setting;
2004
+ localStorage.setItem(key, JSON.stringify(userSettings));
2005
+ }
2006
+
2007
+ //#endregion
2008
+ //#region src/index.ts
2009
+ const version = "2.12.0";
2010
+
2011
+ //#endregion
2012
+ exports.ConfirmButtons = ConfirmButtons;
2013
+ exports.NO_FILTER_ID = NO_FILTER_ID;
2014
+ exports.RELATIVE_DATE_VALUES = RELATIVE_DATE_VALUES;
2015
+ exports.SessionHandler = SessionHandler;
2016
+ exports.UserSession = UserSession;
2017
+ exports.addGroupAtPath = addGroupAtPath;
2018
+ exports.alert = alert;
2019
+ exports.canDeleteSavedFilter = canDeleteSavedFilter;
2020
+ exports.canEditSavedFilter = canEditSavedFilter;
2021
+ exports.canRenameSavedFilter = canRenameSavedFilter;
2022
+ exports.canSetCrossDomain = canSetCrossDomain;
2023
+ exports.canShareSavedFilter = canShareSavedFilter;
2024
+ exports.changeOperator = changeOperator;
2025
+ exports.coerceParameterValue = coerceParameterValue;
2026
+ exports.coerceToStandardLayout = coerceToStandardLayout;
2027
+ exports.confirm = confirm;
2028
+ exports.convertFilter = convertFilter;
2029
+ exports.countExpressions = countExpressions;
2030
+ exports.createEmptyFilter = createEmptyFilter;
2031
+ exports.createEmptyGroup = createEmptyGroup;
2032
+ exports.createExpression = createExpression;
2033
+ exports.decodeXml = decodeXml;
2034
+ exports.describeFilter = describeFilter;
2035
+ exports.downloadBlob = downloadBlob;
2036
+ exports.downloadReport = downloadReport;
2037
+ exports.downloadRequest = downloadRequest;
2038
+ exports.encodeXml = encodeXml;
2039
+ exports.expose = expose;
2040
+ exports.fetchParameterDefault = fetchParameterDefault;
2041
+ exports.findSavedFilter = findSavedFilter;
2042
+ exports.getDefaultOperator = getDefaultOperator;
2043
+ exports.getDefaultParameterValues = getDefaultParameterValues;
2044
+ exports.getDynamicValueLabel = getDynamicValueLabel;
2045
+ exports.getDynamicValuesForField = getDynamicValuesForField;
2046
+ exports.getLocalizedString = getLocalizedString;
2047
+ exports.getNodeAtPath = getNodeAtPath;
2048
+ exports.getOperatorArity = getOperatorArity;
2049
+ exports.getOperatorLabel = getOperatorLabel;
2050
+ exports.getOperatorsForField = getOperatorsForField;
2051
+ exports.getReportExtension = getReportExtension;
2052
+ exports.getReportFileName = getReportFileName;
2053
+ exports.getReportFormats = getReportFormats;
2054
+ exports.getReportMediaType = getReportMediaType;
2055
+ exports.getReportRequest = getReportRequest;
2056
+ exports.getSessionData = getSessionData;
2057
+ exports.getSettings = getSettings;
2058
+ exports.getUserImage = getUserImage;
2059
+ exports.getValueType = getValueType;
2060
+ exports.insertNodeAtPath = insertNodeAtPath;
2061
+ exports.invariant = invariant;
2062
+ exports.isCompleteExpression = isCompleteExpression;
2063
+ exports.isEmptyFilter = isEmptyFilter;
2064
+ exports.isExpression = isExpression;
2065
+ exports.isGroup = isGroup;
2066
+ exports.isProcedureDefault = isProcedureDefault;
2067
+ exports.isStandardLayout = isStandardLayout;
2068
+ exports.localStorage = localStorage_default;
2069
+ exports.localize = localize;
2070
+ exports.logActivity = logActivity;
2071
+ exports.logError = logError;
2072
+ exports.mitt = mitt_default;
2073
+ exports.normalizeOperator = normalizeOperator;
2074
+ exports.openAlertDialog = openAlertDialog;
2075
+ exports.openReport = openReport;
2076
+ exports.parseParameterItems = parseParameterItems;
2077
+ exports.parseParameters = parseParameters;
2078
+ exports.parseRecordSource = parseRecordSource;
2079
+ exports.partitionSavedFilters = partitionSavedFilters;
2080
+ exports.printReport = printReport;
2081
+ exports.pruneFilter = pruneFilter;
2082
+ exports.readElement = readElement;
2083
+ exports.readElements = readElements;
2084
+ exports.removeNodeAtPath = removeNodeAtPath;
2085
+ exports.renderReport = renderReport;
2086
+ exports.resolveParameterDefaults = resolveParameterDefaults;
2087
+ exports.restoreParameterValues = restoreParameterValues;
2088
+ exports.saveSettings = saveSettings;
2089
+ exports.serializeParameters = serializeParameters;
2090
+ exports.setGroupMode = setGroupMode;
2091
+ exports.startActivity = startActivity;
2092
+ exports.time = time;
2093
+ exports.toFieldMetadata = toFieldMetadata;
2094
+ exports.toFieldMetadataList = toFieldMetadataList;
2095
+ exports.toFilterFieldType = toFilterFieldType;
2096
+ exports.toFilterTree = toFilterTree;
2097
+ exports.toLocalDateTime = toLocalDateTime;
2098
+ exports.toLocalISODate = toLocalISODate;
2099
+ exports.toLocalISODateTime = toLocalISODateTime;
2100
+ exports.toReport = toReport;
2101
+ exports.toReportParameter = toReportParameter;
2102
+ exports.toReportParameters = toReportParameters;
2103
+ exports.toSavedFilter = toSavedFilter;
2104
+ exports.toSavedFilters = toSavedFilters;
2105
+ exports.updateNodeAtPath = updateNodeAtPath;
2106
+ exports.version = version;
2107
+ exports.waitForDialog = waitForDialog;
2108
+ return exports;
2109
+ })({});