@olenbetong/appframe-core 2.11.10 → 2.12.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 +1982 -626
  2. package/dist/esm/af.common.legacy.js +1936 -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 +2140 -708
  8. package/dist/iife/af.common.legacy.js +2094 -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 +229 -0
  28. package/es/filter/operators.test.d.ts +1 -0
  29. package/es/filter/operators.test.js +106 -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 +3 -1
  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 +136 -0
  76. package/src/filter/operators.ts +252 -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,1873 @@
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
+ /** Default operator per field type. */
690
+ const DEFAULT_OPERATOR_BY_TYPE = {
691
+ date: "equals",
692
+ datetime: "equals",
693
+ number: "equals",
694
+ boolean: "istrue",
695
+ string: "beginswith",
696
+ uniqueidentifier: "beginswith"
697
+ };
698
+ /**
699
+ * Returns the operators available for a field. Nullable fields additionally get
700
+ * the null checks. Boolean fields never get null checks, since `istrue` and
701
+ * `isfalse` already cover the parameterless cases.
702
+ */
703
+ function getOperatorsForField(field) {
704
+ let operators = [...OPERATORS_BY_TYPE[field.type] ?? OPERATORS_BY_TYPE.string];
705
+ if (field.nullable && field.type !== "boolean") operators.push("isnull", "isnotnull");
706
+ return operators;
707
+ }
708
+ function getDefaultOperator(field) {
709
+ return DEFAULT_OPERATOR_BY_TYPE[field.type] ?? "equals";
710
+ }
711
+ /**
712
+ * The `valueType` to send for a field/operator combination.
713
+ *
714
+ * Parameterless operators send `"null"`, list and range operators send
715
+ * `"array"`, everything else sends the field's own value type.
716
+ */
717
+ function getValueType(field, operator) {
718
+ if (getOperatorArity(operator) === "none") return "null";
719
+ switch (field.type) {
720
+ case "number": return "number";
721
+ case "boolean": return "boolean";
722
+ case "date":
723
+ case "datetime": return "datetime";
724
+ case "uniqueidentifier": return "uniqueidentifier";
725
+ default: return "string";
726
+ }
727
+ }
728
+ /** Relative date values offered in the date value editor, in menu order. */
729
+ const RELATIVE_DATE_VALUES = [
730
+ "Yesterday",
731
+ "Today",
732
+ "Tomorrow",
733
+ "ThisWeek",
734
+ "ThisMonth",
735
+ "ThisYear",
736
+ "LastWeek",
737
+ "LastMonth",
738
+ "LastYear",
739
+ "NextWeek",
740
+ "NextMonth",
741
+ "NextYear"
742
+ ];
743
+ const DYNAMIC_VALUE_LABELS = {
744
+ CurrentUser: "Current user",
745
+ Yesterday: "Yesterday",
746
+ Today: "Today",
747
+ Tomorrow: "Tomorrow",
748
+ ThisWeek: "This week",
749
+ ThisMonth: "This month",
750
+ ThisYear: "This year",
751
+ LastWeek: "Last week",
752
+ LastMonth: "Last month",
753
+ LastYear: "Last year",
754
+ NextWeek: "Next week",
755
+ NextMonth: "Next month",
756
+ NextYear: "Next year",
757
+ UserYesterday: "Yesterday",
758
+ UserToday: "Today",
759
+ UserTomorrow: "Tomorrow",
760
+ UserThisWeek: "This week",
761
+ UserThisMonth: "This month",
762
+ UserThisYear: "This year",
763
+ UserLastWeek: "Last week",
764
+ UserLastMonth: "Last month",
765
+ UserLastYear: "Last year",
766
+ UserNextWeek: "Next week",
767
+ UserNextMonth: "Next month",
768
+ UserNextYear: "Next year"
769
+ };
770
+ function getDynamicValueLabel(value) {
771
+ return getLocalizedString(DYNAMIC_VALUE_LABELS[value] ?? value);
772
+ }
773
+ /**
774
+ * Returns the dynamic ("special") values that can be used with a field. Date
775
+ * fields get the relative dates; string fields can be compared to the current
776
+ * user name.
777
+ */
778
+ function getDynamicValuesForField(field) {
779
+ if (field.type === "date" || field.type === "datetime") return [...RELATIVE_DATE_VALUES];
780
+ if (field.type === "string") return ["CurrentUser"];
781
+ return [];
782
+ }
783
+ /**
784
+ * Aliases for names `eOperators.ToString()` can produce that are not operators
785
+ * in their own right. `Not` is the bare negation flag (i.e. "not equal to"),
786
+ * `Tweens` shares its numeric value with `NotBetween`, and combined flags are
787
+ * rendered as a comma separated list.
788
+ *
789
+ * @see `FilterElementConverter.FilterExpressionToDictionary`
790
+ */
791
+ const OPERATOR_ALIASES = {
792
+ not: "notequals",
793
+ tweens: "notbetween",
794
+ notdate: "notdatequals",
795
+ notdateequals: "notdatequals"
796
+ };
797
+ /**
798
+ * Normalizes an operator string coming from the server or from another filter
799
+ * producer (`AfGrid` emits PascalCase names) to the canonical lower-case form.
800
+ */
801
+ function normalizeOperator(operator) {
802
+ let normalized = operator.toLowerCase().replace(/[\s,]/g, "");
803
+ return OPERATOR_ALIASES[normalized] ?? normalized;
804
+ }
805
+
806
+ //#endregion
807
+ //#region src/filter/tree.ts
808
+ /**
809
+ * Creates the default empty filter: a single `and` group with no conditions.
810
+ */
811
+ function createEmptyFilter() {
812
+ return createEmptyGroup("and");
813
+ }
814
+ function createEmptyGroup(mode = "and") {
815
+ return {
816
+ type: "group",
817
+ mode,
818
+ items: []
819
+ };
820
+ }
821
+ function isGroup(item) {
822
+ return item.type === "group";
823
+ }
824
+ function isExpression(item) {
825
+ return item.type === "expression";
826
+ }
827
+ /**
828
+ * Normalizes any filter value into a tree the editor can render, without
829
+ * changing its structure. An expression is wrapped in a group; a missing filter
830
+ * becomes the default layout.
831
+ */
832
+ function toFilterTree(filter) {
833
+ if (!filter) return createEmptyFilter();
834
+ if (isExpression(filter)) return {
835
+ type: "group",
836
+ mode: "and",
837
+ items: [filter]
838
+ };
839
+ return filter;
840
+ }
841
+ /**
842
+ * True when the filter contains no expressions. An empty filter must not be
843
+ * saved or applied.
844
+ */
845
+ function isEmptyFilter(filter) {
846
+ return countExpressions(filter) === 0;
847
+ }
848
+ function countExpressions(filter) {
849
+ if (!filter) return 0;
850
+ if (isExpression(filter)) return 1;
851
+ return filter.items.reduce((total, item) => total + countExpressions(item), 0);
852
+ }
853
+ /**
854
+ * Removes incomplete expressions and empty groups from the whole tree. Returns
855
+ * null when nothing is left. Use before applying a filter to a data object so
856
+ * incomplete rows are not sent.
857
+ */
858
+ function pruneFilter(filter) {
859
+ if (!filter) return null;
860
+ if (isExpression(filter)) return isCompleteExpression(filter) ? {
861
+ type: "group",
862
+ mode: "and",
863
+ items: [filter]
864
+ } : null;
865
+ let items = filter.items.map((item) => isGroup(item) ? pruneFilter(item) : isCompleteExpression(item) ? item : null).filter((item) => item !== null);
866
+ if (items.length === 0) return null;
867
+ return {
868
+ ...filter,
869
+ items
870
+ };
871
+ }
872
+ /**
873
+ * True when an expression has everything it needs to be sent to the server.
874
+ */
875
+ function isCompleteExpression(item) {
876
+ if (isGroup(item)) return item.items.some(isCompleteExpression);
877
+ if (!item.column || !item.operator) return false;
878
+ let arity = getOperatorArity(normalizeOperator(item.operator));
879
+ if (arity === "none") return true;
880
+ if (item.value === null || item.value === void 0 || item.value === "") return false;
881
+ if (arity === "pair") return Array.isArray(item.value) && item.value.length === 2 && item.value.every((v) => v !== "" && v != null);
882
+ if (arity === "list") return Array.isArray(item.value) && item.value.length > 0;
883
+ return true;
884
+ }
885
+ /**
886
+ * Creates an expression for a field, using the field's default operator and an
887
+ * empty value of the right shape.
888
+ */
889
+ function createExpression(field, operator) {
890
+ let op = operator ?? getDefaultOperator(field);
891
+ return {
892
+ type: "expression",
893
+ column: field.name,
894
+ operator: op,
895
+ value: createEmptyValue(op),
896
+ valueType: getValueType(field, op)
897
+ };
898
+ }
899
+ function createEmptyValue(operator) {
900
+ switch (getOperatorArity(operator)) {
901
+ case "none": return null;
902
+ case "pair": return ["", ""];
903
+ case "list": return [];
904
+ default: return "";
905
+ }
906
+ }
907
+ /**
908
+ * Returns a copy of the expression with a new operator, adjusting the value to
909
+ * the new operator's arity and the value type accordingly.
910
+ */
911
+ function changeOperator(expression, operator, field) {
912
+ let previousArity = getOperatorArity(normalizeOperator(expression.operator));
913
+ let arity = getOperatorArity(operator);
914
+ let value = expression.value;
915
+ if (arity !== previousArity) value = createEmptyValue(operator);
916
+ let valueType = expression.valueType === "special" && arity === previousArity ? "special" : getValueType(field, operator);
917
+ return {
918
+ ...expression,
919
+ operator,
920
+ value,
921
+ valueType
922
+ };
923
+ }
924
+ /** Returns the node at `path`, or null when the path does not exist. */
925
+ function getNodeAtPath(filter, path) {
926
+ let node = filter;
927
+ for (let index of path) {
928
+ if (!node || !isGroup(node)) return null;
929
+ node = node.items[index];
930
+ }
931
+ return node ?? null;
932
+ }
933
+ /**
934
+ * Returns a copy of the tree with `updater` applied to the node at `path`.
935
+ * Returning null removes the node. An unknown path leaves the tree untouched.
936
+ */
937
+ function updateNodeAtPath(filter, path, updater) {
938
+ if (path.length === 0) return updater(filter) ?? filter;
939
+ if (!isGroup(filter)) return filter;
940
+ let [index, ...rest] = path;
941
+ let child = filter.items[index];
942
+ if (!child) return filter;
943
+ let items = [...filter.items];
944
+ if (rest.length === 0) {
945
+ let updated = updater(child);
946
+ if (updated === null) items.splice(index, 1);
947
+ else items[index] = updated;
948
+ } else items[index] = updateNodeAtPath(child, rest, updater);
949
+ return {
950
+ ...filter,
951
+ items
952
+ };
953
+ }
954
+ /** Returns a copy of the tree with `node` appended to the group at `path`. */
955
+ function insertNodeAtPath(filter, path, node) {
956
+ return updateNodeAtPath(filter, path, (target) => isGroup(target) ? {
957
+ ...target,
958
+ items: [...target.items, node]
959
+ } : target);
960
+ }
961
+ /**
962
+ * Returns a copy of the tree with the node at `path` removed. The root is never
963
+ * removed; it is reset to the default layout instead.
964
+ */
965
+ function removeNodeAtPath(filter, path) {
966
+ if (path.length === 0) return createEmptyFilter();
967
+ return updateNodeAtPath(filter, path, () => null);
968
+ }
969
+ /** Returns a copy of the tree with the mode of the group at `path` changed. */
970
+ function setGroupMode(filter, path, mode) {
971
+ return updateNodeAtPath(filter, path, (node) => isGroup(node) ? {
972
+ ...node,
973
+ mode
974
+ } : node);
975
+ }
976
+ /** Returns a copy of the tree with an empty group appended to the group at `path`. */
977
+ function addGroupAtPath(filter, path = []) {
978
+ let parent = getNodeAtPath(filter, path);
979
+ return insertNodeAtPath(filter, path, createEmptyGroup(parent && isGroup(parent) && parent.mode === "and" ? "or" : "and"));
980
+ }
981
+
982
+ //#endregion
983
+ //#region src/filter/convertFilter.ts
984
+ const CONVERT_URL = "/api/filter/convert";
985
+ /**
986
+ * Converts between a structured filter and a DevExpress filter string.
987
+ *
988
+ * The conversion is done server-side by `api/filter/convert`, because the
989
+ * criteria string grammar is implemented by the licensed DevExpress parser that
990
+ * the Windows client and the report engine use. Doing it in the browser would
991
+ * risk producing strings the server cannot parse back.
992
+ */
993
+ async function convertFilter(request, signal) {
994
+ let response = await fetch(CONVERT_URL, {
995
+ method: "POST",
996
+ headers: { "Content-Type": "application/json" },
997
+ body: JSON.stringify(request),
998
+ signal
999
+ });
1000
+ if (!response.ok) throw new Error(`Failed to convert filter: ${response.status} ${response.statusText}`);
1001
+ let result = await response.json();
1002
+ return {
1003
+ ...result,
1004
+ filterObject: result.filterObject ? toFilterTree(result.filterObject) : null
1005
+ };
1006
+ }
1007
+
1008
+ //#endregion
1009
+ //#region src/filter/describeFilter.ts
1010
+ /**
1011
+ * Builds a human-readable description of a filter, without contacting the
1012
+ * server. Use this for read-only summaries; the authoritative filter string is
1013
+ * produced by `api/filter/convert`, since only the server can generate the
1014
+ * DevExpress criteria syntax.
1015
+ */
1016
+ function describeFilter(filter, options = {}) {
1017
+ if (!filter) return "";
1018
+ return describe(filter, new Map((options.fields ?? []).map((field) => [field.name.toLowerCase(), field])), 0);
1019
+ }
1020
+ function describe(item, fields, depth) {
1021
+ if (isExpression(item)) return describeExpression(item, fields);
1022
+ let parts = item.items.map((child) => describe(child, fields, depth + 1)).filter((part) => part !== "");
1023
+ if (parts.length === 0) return "";
1024
+ if (parts.length === 1) return parts[0];
1025
+ let separator = item.mode === "or" ? " OR " : " AND ";
1026
+ let joined = parts.join(separator);
1027
+ return depth === 0 ? joined : `(${joined})`;
1028
+ }
1029
+ function describeExpression(expression, fields) {
1030
+ if (!expression.column || !expression.operator) return "";
1031
+ let field = fields.get(expression.column.toLowerCase());
1032
+ let caption = field?.caption ?? expression.column;
1033
+ let operator = normalizeOperator(expression.operator);
1034
+ let label = getOperatorLabel(operator, field?.type);
1035
+ let arity = getOperatorArity(operator);
1036
+ if (arity === "none") return `[${caption}] ${label}`;
1037
+ return `[${caption}] ${label} ${formatValue(expression, arity)}`;
1038
+ }
1039
+ function formatValue(expression, arity) {
1040
+ let { value, valueType } = expression;
1041
+ if (valueType === "special" && typeof value === "string") return getDynamicValueLabel(value);
1042
+ if (Array.isArray(value)) {
1043
+ let formatted = value.map((item) => formatScalar(item, valueType));
1044
+ return arity === "pair" ? formatted.join(" - ") : `(${formatted.join(", ")})`;
1045
+ }
1046
+ return formatScalar(value, valueType);
1047
+ }
1048
+ function formatScalar(value, valueType) {
1049
+ if (value === null || value === void 0) return "";
1050
+ if (value instanceof Date) return value.toISOString().slice(0, 10);
1051
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
1052
+ if (valueType === "number" || valueType === "boolean") return String(value);
1053
+ return `'${String(value)}'`;
1054
+ }
1055
+
1056
+ //#endregion
1057
+ //#region src/filter/fields.ts
1058
+ const FIELD_TYPES = [
1059
+ "string",
1060
+ "number",
1061
+ "boolean",
1062
+ "date",
1063
+ "datetime",
1064
+ "uniqueidentifier"
1065
+ ];
1066
+ /** The builder type for a normalized `DataType`. Unknown types are filtered as text. */
1067
+ function toFilterFieldType(dataType) {
1068
+ let normalized = dataType?.trim().toLowerCase();
1069
+ return FIELD_TYPES.find((type) => type === normalized) ?? "string";
1070
+ }
1071
+ function toBoolean$1(value) {
1072
+ return value === true || value === 1;
1073
+ }
1074
+ /** Maps a view field record onto the metadata the builder renders. */
1075
+ function toFieldMetadata(record) {
1076
+ return {
1077
+ name: record.FieldName ?? "",
1078
+ type: toFilterFieldType(record.DataType),
1079
+ nullable: toBoolean$1(record.Nullable),
1080
+ excludeFromFilter: toBoolean$1(record.ExcludeFromFilter),
1081
+ valueListRecordSource: record.ValueListRecordSource || void 0
1082
+ };
1083
+ }
1084
+ /**
1085
+ * Maps and sorts view field records. Fields the view marks as excluded are
1086
+ * dropped rather than hidden, since nothing else can use them.
1087
+ */
1088
+ function toFieldMetadataList(records) {
1089
+ return records.map(toFieldMetadata).filter((field) => field.name !== "" && !field.excludeFromFilter).sort((a, b) => a.name.localeCompare(b.name));
1090
+ }
1091
+
1092
+ //#endregion
1093
+ //#region src/filter/standardLayout.ts
1094
+ /**
1095
+ * The "standard layout" is the simplified shape the Windows filter editor can
1096
+ * render in its flow view: an outer `or` group whose items are `and` groups of
1097
+ * expressions. Anything else falls back to the advanced (DevExpress) editor
1098
+ * there, and to the nested tree editor on the web.
1099
+ *
1100
+ * @see `afFilterEditor.CanRenderFilter`
1101
+ */
1102
+ function isStandardLayout(filter) {
1103
+ if (!filter || isExpression(filter) || filter.mode !== "or") return false;
1104
+ return filter.items.every((item) => isGroup(item) && item.mode === "and" && item.items.every(isExpression));
1105
+ }
1106
+ /**
1107
+ * Coerces an arbitrary filter tree into the standard layout.
1108
+ *
1109
+ * An `or` group's items each become their own `and` group. Anything else is
1110
+ * flattened into a single `and` group. This loses nesting, so only use it when
1111
+ * the consumer cannot handle a nested tree.
1112
+ */
1113
+ function coerceToStandardLayout(filter) {
1114
+ if (!filter) return {
1115
+ type: "group",
1116
+ mode: "or",
1117
+ items: [{
1118
+ type: "group",
1119
+ mode: "and",
1120
+ items: []
1121
+ }]
1122
+ };
1123
+ if (isExpression(filter)) return {
1124
+ type: "group",
1125
+ mode: "or",
1126
+ items: [{
1127
+ type: "group",
1128
+ mode: "and",
1129
+ items: [filter]
1130
+ }]
1131
+ };
1132
+ if (filter.mode === "or") {
1133
+ let groups = filter.items.map((item) => {
1134
+ let expressions = [];
1135
+ collectExpressions(item, expressions);
1136
+ return {
1137
+ type: "group",
1138
+ mode: "and",
1139
+ items: expressions
1140
+ };
1141
+ });
1142
+ return {
1143
+ type: "group",
1144
+ mode: "or",
1145
+ items: groups.length > 0 ? groups : [{
1146
+ type: "group",
1147
+ mode: "and",
1148
+ items: []
1149
+ }]
1150
+ };
1151
+ }
1152
+ let expressions = [];
1153
+ collectExpressions(filter, expressions);
1154
+ return {
1155
+ type: "group",
1156
+ mode: "or",
1157
+ items: [{
1158
+ type: "group",
1159
+ mode: "and",
1160
+ items: expressions
1161
+ }]
1162
+ };
1163
+ }
1164
+ /**
1165
+ * Collects every expression in a (possibly nested) filter, in document order.
1166
+ */
1167
+ function collectExpressions(item, into) {
1168
+ if (isExpression(item)) {
1169
+ into.push(item);
1170
+ return;
1171
+ }
1172
+ for (let child of item.items) collectExpressions(child, into);
1173
+ }
1174
+
1175
+ //#endregion
1176
+ //#region src/filter/savedFilters.ts
1177
+ /**
1178
+ * `sviw_Database_MyFilters` unions in a synthetic "No Filter" row so the Windows
1179
+ * tree can render a "no filter" entry. It is not a real filter and must be
1180
+ * dropped before the list is shown.
1181
+ */
1182
+ const NO_FILTER_ID = -1;
1183
+ /**
1184
+ * Maps a database record onto a `SavedFilter`.
1185
+ *
1186
+ * `CreatedByUser` needs care: the view computes it as the *string* `'true'` or
1187
+ * `'false'` (and `'False'` on the synthetic row), not as a bit.
1188
+ */
1189
+ function toSavedFilter(record) {
1190
+ return {
1191
+ filterId: record.FilterID ?? -1,
1192
+ primKey: record.PrimKey ?? "",
1193
+ name: record.FilterName ?? "",
1194
+ criteria: record.FilterCriteria ?? "",
1195
+ dbObjectId: record.DBObjectID ?? "",
1196
+ accessLevel: toAccessLevel(record.AccessLevel),
1197
+ createdByUser: toBoolean(record.CreatedByUser),
1198
+ createdBy: record.CreatedBy ?? "",
1199
+ domain: record.Domain ?? null,
1200
+ crossDomain: toBoolean(record.CrossDomain),
1201
+ isPersonallyShared: toBoolean(record.IsPersonallyShared),
1202
+ hideCriteria: toBoolean(record.HideFilterCriteria),
1203
+ headerText: record.OptionalHeaderText || null,
1204
+ comment: record.OptionalComment || null,
1205
+ parameters: record.Parameters || null,
1206
+ reportTitle: record.ReportTitle || null,
1207
+ created: toDate(record.Created),
1208
+ updated: toDate(record.Updated)
1209
+ };
1210
+ }
1211
+ function toAccessLevel(value) {
1212
+ if (value === "Manager" || value === "Editor") return value;
1213
+ return "Reader";
1214
+ }
1215
+ function toBoolean(value) {
1216
+ if (typeof value === "string") return value.toLowerCase() === "true";
1217
+ return Boolean(value);
1218
+ }
1219
+ function toDate(value) {
1220
+ if (!value) return null;
1221
+ if (value instanceof Date) return value;
1222
+ let date = new Date(value);
1223
+ return Number.isNaN(date.getTime()) ? null : date;
1224
+ }
1225
+ /** Drops the synthetic "No Filter" row and sorts by name. */
1226
+ function toSavedFilters(records) {
1227
+ return records.filter((record) => (record.FilterID ?? -1) !== -1).map(toSavedFilter).sort((a, b) => a.name.localeCompare(b.name));
1228
+ }
1229
+ /**
1230
+ * Splits filters into the two branches the Windows tree shows: the ones the user
1231
+ * created, and the ones that have been shared with them.
1232
+ */
1233
+ function partitionSavedFilters(filters) {
1234
+ let mine = [];
1235
+ let shared = [];
1236
+ for (let filter of filters) if (filter.createdByUser) mine.push(filter);
1237
+ else shared.push(filter);
1238
+ return {
1239
+ mine,
1240
+ shared
1241
+ };
1242
+ }
1243
+ function findSavedFilter(filters, filterId) {
1244
+ if (filterId == null) return void 0;
1245
+ return filters.find((filter) => filter.filterId === filterId);
1246
+ }
1247
+ /** True when the user may overwrite the filter's criteria. */
1248
+ function canEditSavedFilter(filter) {
1249
+ return filter.accessLevel === "Editor" || filter.accessLevel === "Manager";
1250
+ }
1251
+ /** True when the user may change who the filter is shared with. */
1252
+ function canShareSavedFilter(filter) {
1253
+ return filter.accessLevel === "Manager";
1254
+ }
1255
+ /**
1256
+ * True when the user may rename or delete the filter.
1257
+ *
1258
+ * `sstp_WebSiteCMS_FilterBuilder_RenameFilter` and `…_DeleteFilter` both require
1259
+ * `CreatedBy = SUSER_SNAME()` — the manager-access branch is commented out in
1260
+ * both procedures, deliberately, because the UI only ever offers these for a
1261
+ * user's own filters.
1262
+ */
1263
+ function canRenameSavedFilter(filter) {
1264
+ return filter.createdByUser;
1265
+ }
1266
+ const canDeleteSavedFilter = canRenameSavedFilter;
1267
+ /**
1268
+ * True when the user may toggle the cross-domain flag.
1269
+ *
1270
+ * `sstp_Database_Filters_SetCrossDomain` also filters on
1271
+ * `CreatedBy = SUSER_SNAME()`.
1272
+ */
1273
+ const canSetCrossDomain = canRenameSavedFilter;
1274
+
1275
+ //#endregion
1276
+ //#region src/getUserImage.ts
1277
+ const sizeMap = {
1278
+ xs: 64,
1279
+ sm: 128,
1280
+ md: 256,
1281
+ lg: 512,
1282
+ xl: void 0
1283
+ };
1284
+ function getUserImage(primKeyOrOptions, login, hash, size = "xs") {
1285
+ if (primKeyOrOptions && typeof primKeyOrOptions === "object") return getUserImage(primKeyOrOptions.primKey, primKeyOrOptions.login, primKeyOrOptions.hash, primKeyOrOptions.size);
1286
+ if (!primKeyOrOptions || !hash) return "";
1287
+ let sizePx = sizeMap[size];
1288
+ return `/api/data/blob/EmployeesLookup/${primKeyOrOptions}/Image/${encodeURIComponent(login ?? "")}${login ? "." : ""}${encodeURIComponent(hash)}.jpg${sizePx ? `?width=${sizePx}` : ""}`;
1289
+ }
1290
+
1291
+ //#endregion
1292
+ //#region src/localize.ts
1293
+ /**
1294
+ * Localization function for tagged templates. Replaces the arguments
1295
+ * with $n, where n is the index, before asking Appframe to translate
1296
+ * the string.
1297
+ *
1298
+ * For example, if you call localize`Page ${2} or ${5}`, the string
1299
+ * "Page $0 of $1" will be sent to Appframe, and for norwegian,
1300
+ * "Side 2 av 5" will be returned.
1301
+ *
1302
+ * @param stringParts
1303
+ * @param args
1304
+ * @returns Translated string
1305
+ */
1306
+ function localize(stringParts, ...args) {
1307
+ invariant(Array.isArray(stringParts) && stringParts.length === args.length + 1, "Method 'localize' must be used as a tag function");
1308
+ let stringToLocalize = stringParts.map((s, i) => i === stringParts.length - 1 ? s : `${s}$${i}`).join("");
1309
+ let localized = getLocalizedString(stringToLocalize);
1310
+ args.forEach((arg, index) => {
1311
+ localized = localized.replace(`$${index}`, arg);
1312
+ });
1313
+ return localized;
1314
+ }
1315
+
1316
+ //#endregion
1317
+ //#region src/report/recordSource.ts
1318
+ const XML_ENTITIES = {
1319
+ amp: "&",
1320
+ lt: "<",
1321
+ gt: ">",
1322
+ quot: "\"",
1323
+ apos: "'"
1324
+ };
1325
+ /** Resolves the XML entities the .NET serializer emits. */
1326
+ function decodeXml(value) {
1327
+ return value.replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (match, entity) => {
1328
+ if (entity.startsWith("#x") || entity.startsWith("#X")) return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));
1329
+ if (entity.startsWith("#")) return String.fromCodePoint(Number.parseInt(entity.slice(1), 10));
1330
+ return XML_ENTITIES[entity.toLowerCase()] ?? match;
1331
+ });
1332
+ }
1333
+ /** Escapes a value for use as XML text or as an attribute value. */
1334
+ function encodeXml(value) {
1335
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1336
+ }
1337
+ /**
1338
+ * The text content of the first `<name>` element, or `null` when the element is
1339
+ * missing or self-closing (`<FilterString />`, which the serializer writes for
1340
+ * an empty value).
1341
+ */
1342
+ function readElement(xml, name) {
1343
+ let match = new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)</${name}>`).exec(xml);
1344
+ if (!match) return null;
1345
+ let value = decodeXml(match[1]).trim();
1346
+ return value === "" ? null : value;
1347
+ }
1348
+ /** The text content of every `<name>` element, in document order. */
1349
+ function readElements(xml, name) {
1350
+ return [...xml.matchAll(new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)</${name}>`, "g"))].map((match) => decodeXml(match[1]).trim());
1351
+ }
1352
+ /**
1353
+ * The CLR types the designer writes on a select column. Anything else — and a
1354
+ * column with no `DataType` at all, which is what it writes for strings — is
1355
+ * treated as text.
1356
+ */
1357
+ const COLUMN_TYPES = {
1358
+ Byte: "number",
1359
+ Decimal: "number",
1360
+ Double: "number",
1361
+ Int16: "number",
1362
+ Int32: "number",
1363
+ Int64: "number",
1364
+ Single: "number",
1365
+ Boolean: "boolean",
1366
+ DateTime: "date"
1367
+ };
1368
+ /** The columns of a `<SelectColumns>` block, in document order. */
1369
+ function readSelectColumns(xml) {
1370
+ let block = /<SelectColumns>([\s\S]*?)<\/SelectColumns>/.exec(xml)?.[1] ?? "";
1371
+ let columns = [];
1372
+ for (let match of block.matchAll(/<afSelectColumn>([\s\S]*?)<\/afSelectColumn>/g)) {
1373
+ let name = readElement(match[1], "Name");
1374
+ if (!name) continue;
1375
+ columns.push({
1376
+ name,
1377
+ type: COLUMN_TYPES[readElement(match[1], "DataType") ?? ""] ?? "string"
1378
+ });
1379
+ }
1380
+ return columns;
1381
+ }
1382
+ /**
1383
+ * Reads the parts of an `afRecordSource` a web client can act on: the view, the
1384
+ * selected columns and the design-time filter.
1385
+ *
1386
+ * Returns `null` for anything that is not a record source, so a missing or
1387
+ * empty `RecordSource` column simply means "no lookup".
1388
+ */
1389
+ function parseRecordSource(xml) {
1390
+ if (!xml || !xml.includes("<afRecordSource")) return null;
1391
+ let viewName = readElement(xml, "ViewName");
1392
+ if (!viewName) return null;
1393
+ let maxRecords = readElement(xml, "MaxRecords");
1394
+ return {
1395
+ viewName,
1396
+ columns: readSelectColumns(xml),
1397
+ whereClause: readElement(xml, "WhereClause"),
1398
+ filterString: readElement(xml, "FilterString"),
1399
+ maxRecords: maxRecords === null || maxRecords === "0" ? null : Number(maxRecords)
1400
+ };
1401
+ }
1402
+
1403
+ //#endregion
1404
+ //#region src/report/parameters.ts
1405
+ /**
1406
+ * Report parameters: mapping the metadata records onto something renderable,
1407
+ * and the XML the parameter values are stored as on a saved filter.
1408
+ */
1409
+ const PARAMETER_TYPES = [
1410
+ "String",
1411
+ "Integer",
1412
+ "Double",
1413
+ "Date",
1414
+ "Boolean"
1415
+ ];
1416
+ /**
1417
+ * A default value naming a stored procedure, e.g. `astp_Reports_CurrentPeriod`.
1418
+ *
1419
+ * The Windows launcher executes the procedure and uses the first column of the
1420
+ * first row. The web client cannot execute an arbitrary procedure, so these are
1421
+ * resolved through the report endpoint instead.
1422
+ */
1423
+ const PROCEDURE_DEFAULT = /^[a-z]stp_/i;
1424
+ /** True when a `DefaultValue` names a stored procedure rather than a literal. */
1425
+ function isProcedureDefault(defaultValue) {
1426
+ return typeof defaultValue === "string" && PROCEDURE_DEFAULT.test(defaultValue.trim());
1427
+ }
1428
+ /** The choices of a parameter, one per line of its `Items` column. */
1429
+ function parseParameterItems(items) {
1430
+ if (!items) return [];
1431
+ return items.split(/\r\n|\r|\n/).map((item) => item.trim()).filter((item) => item !== "");
1432
+ }
1433
+ function toParameterType(dataType) {
1434
+ return PARAMETER_TYPES.find((type) => type.toLowerCase() === dataType?.trim().toLowerCase()) ?? "String";
1435
+ }
1436
+ /**
1437
+ * The editor a parameter should use. A lookup or a fixed item list wins over the
1438
+ * data type, which is what the Windows launcher does as well.
1439
+ */
1440
+ function toParameterEditor(type, hasLookup, hasItems) {
1441
+ if (hasLookup) return "lookup";
1442
+ if (hasItems) return "select";
1443
+ switch (type) {
1444
+ case "Integer":
1445
+ case "Double": return "number";
1446
+ case "Date": return "date";
1447
+ case "Boolean": return "boolean";
1448
+ default: return "text";
1449
+ }
1450
+ }
1451
+ /** Maps a `sviw_WinClient_ReportsParameters` record onto a `ReportParameter`. */
1452
+ function toReportParameter(record) {
1453
+ let name = record.Name ?? "";
1454
+ let type = toParameterType(record.DataType);
1455
+ let items = parseParameterItems(record.Items);
1456
+ let recordSource = parseRecordSource(record.RecordSource);
1457
+ let valueMember = record.ValueMember ?? null;
1458
+ if (recordSource && !valueMember) valueMember = recordSource.columns[0]?.name ?? null;
1459
+ let displayMember = recordSource?.columns.find((column) => column.name !== valueMember)?.name ?? null;
1460
+ let hasLookup = Boolean(recordSource && valueMember);
1461
+ return {
1462
+ name,
1463
+ label: record.Label?.trim() || name,
1464
+ description: record.Description?.trim() || null,
1465
+ type,
1466
+ editor: toParameterEditor(type, hasLookup, items.length > 0),
1467
+ defaultValue: record.DefaultValue ?? null,
1468
+ items,
1469
+ recordSource: hasLookup ? recordSource : null,
1470
+ valueMember: hasLookup ? valueMember : null,
1471
+ displayMember: hasLookup ? displayMember : null,
1472
+ sortOrder: record.SortOrder ?? 0,
1473
+ lookupWidth: record.LookupWidth ?? null,
1474
+ lookupHeight: record.LookupHeight ?? null
1475
+ };
1476
+ }
1477
+ /** Maps and sorts a report's parameter records. */
1478
+ function toReportParameters(records) {
1479
+ return records.filter((record) => record.Name).map(toReportParameter).sort((a, b) => a.sortOrder - b.sortOrder || a.label.localeCompare(b.label));
1480
+ }
1481
+ /** Converts a raw value to the type a parameter expects. */
1482
+ function coerceParameterValue(parameter, value) {
1483
+ if (value === null || value === void 0 || value === "") return parameter.type === "Boolean" ? false : null;
1484
+ switch (parameter.type) {
1485
+ case "Boolean": return typeof value === "boolean" ? value : /^(true|1|ja|yes)$/i.test(String(value));
1486
+ case "Integer": {
1487
+ let parsed = Number.parseInt(String(value), 10);
1488
+ return Number.isNaN(parsed) ? null : parsed;
1489
+ }
1490
+ case "Double": {
1491
+ let parsed = Number(String(value).replace(",", "."));
1492
+ return Number.isNaN(parsed) ? null : parsed;
1493
+ }
1494
+ default: return String(value);
1495
+ }
1496
+ }
1497
+ /**
1498
+ * The initial values for a set of parameters.
1499
+ *
1500
+ * Defaults naming a stored procedure are left unset: they have to be resolved
1501
+ * server-side, and the caller fills them in once they are.
1502
+ */
1503
+ function getDefaultParameterValues(parameters) {
1504
+ let values = {};
1505
+ for (let parameter of parameters) values[parameter.name] = isProcedureDefault(parameter.defaultValue) ? coerceParameterValue(parameter, null) : coerceParameterValue(parameter, parameter.defaultValue);
1506
+ return values;
1507
+ }
1508
+ function toXmlValue(parameter, value) {
1509
+ if (value === null || value === void 0) return "";
1510
+ if (typeof value === "boolean") return value ? "True" : "False";
1511
+ return String(value);
1512
+ }
1513
+ /**
1514
+ * Serializes parameter values the way the Windows filter builder does, so that
1515
+ * a filter saved on the web is readable in the Windows client and the other way
1516
+ * around.
1517
+ *
1518
+ * ```xml
1519
+ * <Parameters Version="1">
1520
+ * <Parameter Name="Period" Type="Integer">202601</Parameter>
1521
+ * </Parameters>
1522
+ * ```
1523
+ */
1524
+ function serializeParameters(parameters, values) {
1525
+ return `<Parameters Version="1">\n${parameters.map((parameter) => {
1526
+ let value = toXmlValue(parameter, values[parameter.name] ?? null);
1527
+ return ` <Parameter Name="${encodeXml(parameter.name)}" Type="${parameter.type}">${encodeXml(value)}</Parameter>`;
1528
+ }).join("\n")}\n</Parameters>`;
1529
+ }
1530
+ /**
1531
+ * Reads the values back out of the XML stored on a saved filter. Values are
1532
+ * returned as strings and coerced against the report's own parameters by
1533
+ * `restoreParameterValues`, since the XML may name parameters the report no
1534
+ * longer has.
1535
+ */
1536
+ function parseParameters(xml) {
1537
+ if (!xml) return {};
1538
+ let values = {};
1539
+ for (let match of xml.matchAll(/<Parameter\s+([^>]*?)\/?>(?:([\s\S]*?)<\/Parameter>)?/g)) {
1540
+ let name = /Name\s*=\s*"([^"]*)"/.exec(match[1])?.[1];
1541
+ if (!name) continue;
1542
+ values[name] = readElement(match[0], "Parameter") ?? "";
1543
+ }
1544
+ return values;
1545
+ }
1546
+ /**
1547
+ * Applies the values stored on a saved filter to a report's parameters, keeping
1548
+ * the defaults for anything the filter does not mention.
1549
+ */
1550
+ function restoreParameterValues(parameters, xml) {
1551
+ let stored = parseParameters(xml);
1552
+ let values = getDefaultParameterValues(parameters);
1553
+ for (let parameter of parameters) if (parameter.name in stored) values[parameter.name] = coerceParameterValue(parameter, stored[parameter.name]);
1554
+ return values;
1555
+ }
1556
+
1557
+ //#endregion
1558
+ //#region src/report/parameterDefaults.ts
1559
+ /**
1560
+ * Resolving report parameter defaults that name a stored procedure.
1561
+ *
1562
+ * A `DefaultValue` matching `^[a-z]stp_` names a procedure that produces the
1563
+ * default rather than being the default itself. Executing it is a server
1564
+ * concern, and the framework already exposes it through the `WebsiteCMS`
1565
+ * `api/reporting/filters` route.
1566
+ */
1567
+ /**
1568
+ * Runs the stored procedure a parameter's default names and returns the value
1569
+ * it produces — the first column of the first row, the way the Windows launcher
1570
+ * reads it.
1571
+ *
1572
+ * Returns `null` when the parameter has no procedure default or the procedure
1573
+ * produced no rows.
1574
+ */
1575
+ async function fetchParameterDefault(reportId, parameter, signal) {
1576
+ if (!parameter.defaultValue || !isProcedureDefault(parameter.defaultValue)) return null;
1577
+ let response = await fetch(`/api/reporting/filters/${encodeURIComponent(reportId)}/GetParameterDefaultValue`, {
1578
+ body: JSON.stringify({ parameterName: parameter.name }),
1579
+ credentials: "same-origin",
1580
+ headers: {
1581
+ "Content-Type": "application/json",
1582
+ "X-Requested-With": "XMLHttpRequest"
1583
+ },
1584
+ method: "POST",
1585
+ signal
1586
+ });
1587
+ if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);
1588
+ return firstValue(await response.json());
1589
+ }
1590
+ /**
1591
+ * Resolves every procedure default of a report in parallel and merges the
1592
+ * results over the literal defaults.
1593
+ *
1594
+ * A parameter whose procedure fails is left at its literal default rather than
1595
+ * failing the whole form — the user can still type a value.
1596
+ */
1597
+ async function resolveParameterDefaults(reportId, parameters, literalDefaults, signal) {
1598
+ let dynamic = parameters.filter((parameter) => isProcedureDefault(parameter.defaultValue ?? ""));
1599
+ if (dynamic.length === 0) return literalDefaults;
1600
+ let resolved = await Promise.all(dynamic.map(async (parameter) => {
1601
+ try {
1602
+ return [parameter.name, await fetchParameterDefault(reportId, parameter, signal)];
1603
+ } catch {
1604
+ return [parameter.name, null];
1605
+ }
1606
+ }));
1607
+ let values = { ...literalDefaults };
1608
+ for (let [name, value] of resolved) if (value !== null) values[name] = value;
1609
+ return values;
1610
+ }
1611
+ /** The first column of the first row of whichever result set came back. */
1612
+ function firstValue(result) {
1613
+ let row = (Array.isArray(result) ? result : Object.values(result).find((value) => Array.isArray(value)))?.[0];
1614
+ if (row === void 0 || row === null) return null;
1615
+ if (Array.isArray(row)) return row[0] ?? null;
1616
+ if (typeof row === "object") return Object.values(row)[0] ?? null;
1617
+ return row;
1618
+ }
1619
+
1620
+ //#endregion
1621
+ //#region src/report/render.ts
1622
+ /**
1623
+ * Rendering a report through the framework's report route.
1624
+ *
1625
+ * The route is a CMS code module owned by the Appframe framework
1626
+ * (`WebsiteCMS.Reports`), registered on
1627
+ * `api/report/{ReportID}/{FileName}.{Extension}`. Everything here builds
1628
+ * requests for it — there is no report endpoint of our own.
1629
+ */
1630
+ /**
1631
+ * The file extension each format is requested with. The route only accepts
1632
+ * `(pdf|csv|xlsx?|html|xbm|mht|rtf|txt)`, which is why `TEXT` is `txt` and
1633
+ * `IMAGE` is `xbm` rather than the format name.
1634
+ */
1635
+ const REPORT_EXTENSIONS = {
1636
+ CSV: "csv",
1637
+ HTML: "html",
1638
+ IMAGE: "xbm",
1639
+ MHT: "mht",
1640
+ PDF: "pdf",
1641
+ RTF: "rtf",
1642
+ TEXT: "txt",
1643
+ XLS: "xls",
1644
+ XLSX: "xlsx"
1645
+ };
1646
+ /** The media type each format is served as, for previewing a rendered report. */
1647
+ const REPORT_MEDIA_TYPES = {
1648
+ CSV: "text/csv",
1649
+ HTML: "text/html",
1650
+ IMAGE: "image/x-xbitmap",
1651
+ MHT: "message/rfc822",
1652
+ PDF: "application/pdf",
1653
+ RTF: "text/enriched",
1654
+ TEXT: "text/plain",
1655
+ XLS: "application/vnd.ms-excel",
1656
+ XLSX: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
1657
+ };
1658
+ /** The extension a format is requested with. */
1659
+ function getReportExtension(format) {
1660
+ return REPORT_EXTENSIONS[format];
1661
+ }
1662
+ /** The media type a format is served as. */
1663
+ function getReportMediaType(format) {
1664
+ return REPORT_MEDIA_TYPES[format];
1665
+ }
1666
+ /**
1667
+ * Characters that must not reach the file name, because it is a path segment of
1668
+ * the route: separators, the extension delimiter, the query and fragment
1669
+ * delimiters, and control characters.
1670
+ */
1671
+ const UNSAFE_FILE_NAME_CHARACTERS = /[\\/:*?"<>|.#&+%\u0000-\u001f]/g;
1672
+ /**
1673
+ * The name a rendered report is downloaded as, including its extension.
1674
+ *
1675
+ * The file name is part of the route rather than a query parameter, so anything
1676
+ * that would change the path is replaced.
1677
+ */
1678
+ function getReportFileName(options) {
1679
+ let safe = (options.fileName ?? options.reportId).trim().replace(UNSAFE_FILE_NAME_CHARACTERS, "-").replace(/-{2,}/g, "-").replace(/^-|-$/g, "").trim();
1680
+ return `${safe === "" ? options.reportId : safe}.${getReportExtension(options.format)}`;
1681
+ }
1682
+ /**
1683
+ * The route is always on the same origin, but a `Request` needs an absolute
1684
+ * URL, so the path is resolved against the document when there is one.
1685
+ */
1686
+ function toRequestUrl(path) {
1687
+ let base = window.location?.href;
1688
+ return base ? new URL(path, base).toString() : path;
1689
+ }
1690
+ /**
1691
+ * The request that renders a report.
1692
+ *
1693
+ * A report without parameters is a plain `GET`, so it can be opened directly in
1694
+ * a new tab. As soon as there are parameters or a header the options go in a
1695
+ * JSON body, which the route only reads from a `POST`.
1696
+ *
1697
+ * `filter` is always sent alongside `parameters`: the route reads the filter out
1698
+ * of the body *guarded by the presence of `parameters`*, and reads it with an
1699
+ * indexer that throws when the key is missing.
1700
+ */
1701
+ function getReportRequest(options) {
1702
+ let { domain, filter, headerText, hideFilterString, parameters, reportId, signal, timezone } = options;
1703
+ let fileName = getReportFileName(options);
1704
+ let url = `/api/report/${encodeURIComponent(reportId)}/${encodeURIComponent(fileName)}`;
1705
+ let query = new URLSearchParams();
1706
+ let entries = toParameterEntries(parameters);
1707
+ let needsBody = entries.length > 0 || Boolean(headerText) || hideFilterString === true;
1708
+ if (domain) query.set("Domain", domain);
1709
+ query.set("timezone", String(timezone ?? -(/* @__PURE__ */ new Date()).getTimezoneOffset() / 60));
1710
+ if (!needsBody) {
1711
+ if (filter) query.set("Filter", filter);
1712
+ return new Request(toRequestUrl(`${url}?${query}`), {
1713
+ credentials: "same-origin",
1714
+ signal
1715
+ });
1716
+ }
1717
+ let body = {
1718
+ filter: filter ?? "",
1719
+ parameters: entries
1720
+ };
1721
+ if (headerText) body.optionalheader = headerText;
1722
+ if (hideFilterString === true) body.showfiltercriteria = "true";
1723
+ return new Request(toRequestUrl(`${url}?${query}`), {
1724
+ body: JSON.stringify(body),
1725
+ credentials: "same-origin",
1726
+ headers: {
1727
+ "Content-Type": "application/json",
1728
+ "X-Requested-With": "XMLHttpRequest"
1729
+ },
1730
+ method: "POST",
1731
+ signal
1732
+ });
1733
+ }
1734
+ /**
1735
+ * Renders a report and resolves with the rendered file.
1736
+ *
1737
+ * The route answers with a JSON body carrying an `error` when rendering fails,
1738
+ * rather than with a failing status, so a JSON response is turned into an error
1739
+ * here.
1740
+ */
1741
+ async function renderReport(options) {
1742
+ let response = await fetch(getReportRequest(options));
1743
+ if ((response.headers.get("content-type") ?? "").includes("application/json")) {
1744
+ let data = await response.json();
1745
+ throw new Error(data.error ?? "Failed to render report");
1746
+ }
1747
+ if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);
1748
+ return response.blob();
1749
+ }
1750
+ /** Renders a report and saves it, reporting progress as it downloads. */
1751
+ function downloadReport(options) {
1752
+ return downloadRequest(getReportRequest(options), {
1753
+ fileName: getReportFileName(options),
1754
+ onProgress: options.onProgress,
1755
+ signal: options.signal
1756
+ });
1757
+ }
1758
+ /**
1759
+ * Renders a report and opens it in a new tab.
1760
+ *
1761
+ * The blob is rendered first rather than pointing a tab at the route, so a
1762
+ * failure surfaces as an error here instead of as a tab showing JSON, and so
1763
+ * reports with parameters — which have to be posted — can be previewed too.
1764
+ */
1765
+ async function openReport(options) {
1766
+ let blob = await renderReport(options);
1767
+ let url = URL.createObjectURL(blob.type ? blob : new Blob([blob], { type: getReportMediaType(options.format) }));
1768
+ if (!window.open(url, "_blank", "noopener")) {
1769
+ URL.revokeObjectURL(url);
1770
+ throw new Error("The report could not be opened. Allow pop-ups for this site and try again.");
1771
+ }
1772
+ window.setTimeout(() => URL.revokeObjectURL(url), 6e4);
1773
+ }
1774
+ /**
1775
+ * Renders a report and opens the browser's print dialog for it.
1776
+ *
1777
+ * The report is loaded into an offscreen iframe rather than a new tab, so the
1778
+ * print dialog opens over the launcher and the user is not left with a stray
1779
+ * tab afterwards. Browsers that will not print an embedded document fall back
1780
+ * to opening it, which leaves the user one keystroke from printing.
1781
+ */
1782
+ async function printReport(options) {
1783
+ let document_ = window.document;
1784
+ if (!document_?.body) return openReport(options);
1785
+ let blob = await renderReport(options);
1786
+ let url = URL.createObjectURL(blob.type ? blob : new Blob([blob], { type: getReportMediaType(options.format) }));
1787
+ let frame = document_.createElement("iframe");
1788
+ frame.setAttribute("aria-hidden", "true");
1789
+ frame.style.cssText = "position:fixed;inset-block-start:0;inset-inline-start:0;inline-size:1px;block-size:1px;border:0;visibility:hidden";
1790
+ let cleanUp = () => {
1791
+ frame.remove();
1792
+ URL.revokeObjectURL(url);
1793
+ };
1794
+ try {
1795
+ await new Promise((resolve, reject) => {
1796
+ frame.addEventListener("load", () => resolve(), { once: true });
1797
+ frame.addEventListener("error", () => reject(/* @__PURE__ */ new Error("The report could not be loaded for printing")), { once: true });
1798
+ frame.src = url;
1799
+ document_.body.append(frame);
1800
+ });
1801
+ frame.contentWindow?.focus();
1802
+ frame.contentWindow?.print();
1803
+ } catch {
1804
+ cleanUp();
1805
+ return openReport(options);
1806
+ }
1807
+ window.setTimeout(cleanUp, 6e4);
1808
+ }
1809
+ /**
1810
+ * Parameters in the shape the route expects — `{ name, value }` objects.
1811
+ *
1812
+ * Empty values are dropped: the route skips them anyway, and a report falls back
1813
+ * to its own default when a parameter is not sent.
1814
+ */
1815
+ function toParameterEntries(parameters) {
1816
+ if (!parameters) return [];
1817
+ return Object.entries(parameters).filter(([, value]) => value !== null && value !== void 0 && value !== "").map(([name, value]) => ({
1818
+ name,
1819
+ value: typeof value === "boolean" ? String(value) : value
1820
+ }));
1821
+ }
1822
+
1823
+ //#endregion
1824
+ //#region src/report/report.ts
1825
+ /**
1826
+ * Mapping a `sviw_WinClient_MyReports` record onto the report model, including
1827
+ * which output formats the report offers.
1828
+ */
1829
+ function isSet(value) {
1830
+ return value === true || value === 1;
1831
+ }
1832
+ /**
1833
+ * The formats a report may be rendered to, in the order the launcher offers
1834
+ * them.
1835
+ *
1836
+ * `FormatCSV` covers the whole spreadsheet family: the Windows launcher enables
1837
+ * "save as XLS" and "save as XLSX" from the same flag, because they all come out
1838
+ * of the same DevExpress export.
1839
+ */
1840
+ function getReportFormats(record) {
1841
+ let formats = [];
1842
+ if (isSet(record.FormatPDF)) formats.push("PDF");
1843
+ if (isSet(record.FormatCSV)) formats.push("XLSX", "XLS", "CSV");
1844
+ if (isSet(record.FormatHTML)) formats.push("HTML");
1845
+ if (isSet(record.FormatRTF)) formats.push("RTF");
1846
+ if (isSet(record.FormatMHT)) formats.push("MHT");
1847
+ if (isSet(record.FormatTEXT)) formats.push("TEXT");
1848
+ if (isSet(record.FormatIMAGE)) formats.push("IMAGE");
1849
+ return formats;
1850
+ }
1851
+ /** Maps a report record onto the model the launcher renders. */
1852
+ function toReport(record) {
1853
+ let recordSource = parseRecordSource(record.RecordSource);
1854
+ return {
1855
+ reportId: record.ReportID ?? "",
1856
+ shortId: record.ShortID ?? null,
1857
+ title: record.Title?.trim() || null,
1858
+ description: record.Description?.trim() || null,
1859
+ viewName: recordSource?.viewName ?? null,
1860
+ initialFilter: recordSource?.filterString ?? null,
1861
+ hasTitle: isSet(record.HasTitle),
1862
+ hasHeader: isSet(record.HasHeader),
1863
+ formats: getReportFormats(record),
1864
+ timeout: record.Timeout ?? null
1865
+ };
1866
+ }
1867
+
1868
+ //#endregion
1869
+ //#region src/alert.ts
1870
+ const template = `
579
1871
  <dialog class="alert-dialog">
580
1872
  <form method="dialog">
581
1873
  <article></article>
@@ -585,133 +1877,227 @@ var af;
585
1877
  </form>
586
1878
  </dialog>
587
1879
  `;
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
- })();
1880
+ function addDialogTemplate() {
1881
+ if (document.querySelector("#AlertDialogTemplate")) return;
1882
+ let $template = document.createElement("template");
1883
+ $template.id = "AlertDialogTemplate";
1884
+ $template.innerHTML = template;
1885
+ document.body.append($template);
1886
+ }
1887
+ if (window.document) {
1888
+ if (document.body) addDialogTemplate();
1889
+ else document.addEventListener("DOMContentLoaded", addDialogTemplate, { once: true });
1890
+ }
1891
+ function waitForDialog(dialog, cancelValue = "No") {
1892
+ return new Promise((resolve) => {
1893
+ let controller = new AbortController();
1894
+ dialog.addEventListener("close", () => {
1895
+ resolve(dialog.returnValue);
1896
+ controller.abort();
1897
+ }, { signal: controller.signal });
1898
+ dialog.addEventListener("cancel", () => {
1899
+ resolve(cancelValue);
1900
+ controller.abort();
1901
+ }, { signal: controller.signal });
1902
+ });
1903
+ }
1904
+ const alertDialogPromiseMap = /* @__PURE__ */ new Map();
1905
+ async function openAlertDialog({ buttons, content, className, id, title }) {
1906
+ if (id && alertDialogPromiseMap.has(id)) return await alertDialogPromiseMap.get(id);
1907
+ let $template = document.querySelector("#AlertDialogTemplate");
1908
+ if (!$template) throw Error("No alert dialog template found");
1909
+ let $dialog = $template.content.firstElementChild?.cloneNode(true);
1910
+ let $content = $dialog?.querySelector("article");
1911
+ let $menu = $dialog?.querySelector("footer menu");
1912
+ if (!$dialog || !$content || !$menu) throw Error("Invalid alert dialog template");
1913
+ if (className) for (const className_ of className.split(/\s+/)) $dialog?.classList.add(className_);
1914
+ if (title) {
1915
+ let $header = document.createElement("header");
1916
+ $header.append(title);
1917
+ $content.parentNode?.insertBefore($header, $content);
1918
+ }
1919
+ $content.appendChild(typeof content === "string" ? document.createTextNode(content) : content);
1920
+ for (let { label, value, primary } of buttons) {
1921
+ let listItem = document.createElement("li");
1922
+ let buttonElem = document.createElement("button");
1923
+ buttonElem.value = value;
1924
+ if (primary) buttonElem.classList.add("primary");
1925
+ buttonElem.textContent = label;
1926
+ listItem.appendChild(buttonElem);
1927
+ $menu.appendChild(buttonElem);
1928
+ }
1929
+ document.body.appendChild($dialog);
1930
+ $dialog.showModal();
1931
+ let dialogPromise = waitForDialog($dialog).then((returnValue) => {
1932
+ if (id && alertDialogPromiseMap.has(id)) alertDialogPromiseMap.delete(id);
1933
+ if ($dialog) document.body.removeChild($dialog);
1934
+ return returnValue;
1935
+ });
1936
+ if (id) alertDialogPromiseMap.set(id, dialogPromise);
1937
+ return await dialogPromise;
1938
+ }
1939
+ let ConfirmButtons = /* @__PURE__ */ function(ConfirmButtons) {
1940
+ ConfirmButtons[ConfirmButtons["YesNo"] = 0] = "YesNo";
1941
+ ConfirmButtons[ConfirmButtons["OkCancel"] = 1] = "OkCancel";
1942
+ return ConfirmButtons;
1943
+ }({});
1944
+ async function confirm(prompt, options = {}) {
1945
+ let { buttons: optionButtons = 0, title } = options;
1946
+ return await openAlertDialog({
1947
+ content: prompt,
1948
+ buttons: optionButtons === 1 ? [{
1949
+ label: getLocalizedString("OK"),
1950
+ value: "yes",
1951
+ primary: true
1952
+ }, {
1953
+ label: getLocalizedString("Cancel"),
1954
+ value: "no"
1955
+ }] : [{
1956
+ label: getLocalizedString("Yes"),
1957
+ value: "yes",
1958
+ primary: true
1959
+ }, {
1960
+ label: getLocalizedString("No"),
1961
+ value: "no"
1962
+ }],
1963
+ className: "alert-dialog-confirm",
1964
+ title
1965
+ }) === "yes";
1966
+ }
1967
+ async function alert(prompt, options = {}) {
1968
+ await openAlertDialog({
1969
+ content: prompt,
1970
+ className: "alert-dialog-alert",
1971
+ buttons: [{
1972
+ label: getLocalizedString("OK"),
1973
+ value: "ok",
1974
+ primary: true
1975
+ }],
1976
+ ...options
1977
+ });
1978
+ }
1979
+
1980
+ //#endregion
1981
+ //#region src/settings.ts
1982
+ function getKey(article) {
1983
+ return `${article ?? window.af?.article?.id ?? window.window?.location.pathname.substring(1).split("/")[0]}.${window.af?.userSession.login ?? "anonymous"}`;
1984
+ }
1985
+ function getSettings(setting, article) {
1986
+ if (!window.af?.userSession) return null;
1987
+ const key = getKey(article);
1988
+ const settings = JSON.parse(localStorage.getItem(key) || "{}");
1989
+ if (setting) return settings[setting] || null;
1990
+ return settings;
1991
+ }
1992
+ function saveSettings(setting, value, article) {
1993
+ if (!window.af?.userSession) return;
1994
+ const key = getKey(article);
1995
+ let userSettings = JSON.parse(localStorage.getItem(key) || "{}");
1996
+ if (typeof value !== "undefined") userSettings[setting] = value;
1997
+ else userSettings = setting;
1998
+ localStorage.setItem(key, JSON.stringify(userSettings));
1999
+ }
2000
+
2001
+ //#endregion
2002
+ //#region src/index.ts
2003
+ const version = "2.11.10";
2004
+
2005
+ //#endregion
2006
+ exports.ConfirmButtons = ConfirmButtons;
2007
+ exports.NO_FILTER_ID = NO_FILTER_ID;
2008
+ exports.RELATIVE_DATE_VALUES = RELATIVE_DATE_VALUES;
2009
+ exports.SessionHandler = SessionHandler;
2010
+ exports.UserSession = UserSession;
2011
+ exports.addGroupAtPath = addGroupAtPath;
2012
+ exports.alert = alert;
2013
+ exports.canDeleteSavedFilter = canDeleteSavedFilter;
2014
+ exports.canEditSavedFilter = canEditSavedFilter;
2015
+ exports.canRenameSavedFilter = canRenameSavedFilter;
2016
+ exports.canSetCrossDomain = canSetCrossDomain;
2017
+ exports.canShareSavedFilter = canShareSavedFilter;
2018
+ exports.changeOperator = changeOperator;
2019
+ exports.coerceParameterValue = coerceParameterValue;
2020
+ exports.coerceToStandardLayout = coerceToStandardLayout;
2021
+ exports.confirm = confirm;
2022
+ exports.convertFilter = convertFilter;
2023
+ exports.countExpressions = countExpressions;
2024
+ exports.createEmptyFilter = createEmptyFilter;
2025
+ exports.createEmptyGroup = createEmptyGroup;
2026
+ exports.createExpression = createExpression;
2027
+ exports.decodeXml = decodeXml;
2028
+ exports.describeFilter = describeFilter;
2029
+ exports.downloadBlob = downloadBlob;
2030
+ exports.downloadReport = downloadReport;
2031
+ exports.downloadRequest = downloadRequest;
2032
+ exports.encodeXml = encodeXml;
2033
+ exports.expose = expose;
2034
+ exports.fetchParameterDefault = fetchParameterDefault;
2035
+ exports.findSavedFilter = findSavedFilter;
2036
+ exports.getDefaultOperator = getDefaultOperator;
2037
+ exports.getDefaultParameterValues = getDefaultParameterValues;
2038
+ exports.getDynamicValueLabel = getDynamicValueLabel;
2039
+ exports.getDynamicValuesForField = getDynamicValuesForField;
2040
+ exports.getLocalizedString = getLocalizedString;
2041
+ exports.getNodeAtPath = getNodeAtPath;
2042
+ exports.getOperatorArity = getOperatorArity;
2043
+ exports.getOperatorLabel = getOperatorLabel;
2044
+ exports.getOperatorsForField = getOperatorsForField;
2045
+ exports.getReportExtension = getReportExtension;
2046
+ exports.getReportFileName = getReportFileName;
2047
+ exports.getReportFormats = getReportFormats;
2048
+ exports.getReportMediaType = getReportMediaType;
2049
+ exports.getReportRequest = getReportRequest;
2050
+ exports.getSessionData = getSessionData;
2051
+ exports.getSettings = getSettings;
2052
+ exports.getUserImage = getUserImage;
2053
+ exports.getValueType = getValueType;
2054
+ exports.insertNodeAtPath = insertNodeAtPath;
2055
+ exports.invariant = invariant;
2056
+ exports.isCompleteExpression = isCompleteExpression;
2057
+ exports.isEmptyFilter = isEmptyFilter;
2058
+ exports.isExpression = isExpression;
2059
+ exports.isGroup = isGroup;
2060
+ exports.isProcedureDefault = isProcedureDefault;
2061
+ exports.isStandardLayout = isStandardLayout;
2062
+ exports.localStorage = localStorage_default;
2063
+ exports.localize = localize;
2064
+ exports.logActivity = logActivity;
2065
+ exports.logError = logError;
2066
+ exports.mitt = mitt_default;
2067
+ exports.normalizeOperator = normalizeOperator;
2068
+ exports.openAlertDialog = openAlertDialog;
2069
+ exports.openReport = openReport;
2070
+ exports.parseParameterItems = parseParameterItems;
2071
+ exports.parseParameters = parseParameters;
2072
+ exports.parseRecordSource = parseRecordSource;
2073
+ exports.partitionSavedFilters = partitionSavedFilters;
2074
+ exports.printReport = printReport;
2075
+ exports.pruneFilter = pruneFilter;
2076
+ exports.readElement = readElement;
2077
+ exports.readElements = readElements;
2078
+ exports.removeNodeAtPath = removeNodeAtPath;
2079
+ exports.renderReport = renderReport;
2080
+ exports.resolveParameterDefaults = resolveParameterDefaults;
2081
+ exports.restoreParameterValues = restoreParameterValues;
2082
+ exports.saveSettings = saveSettings;
2083
+ exports.serializeParameters = serializeParameters;
2084
+ exports.setGroupMode = setGroupMode;
2085
+ exports.startActivity = startActivity;
2086
+ exports.time = time;
2087
+ exports.toFieldMetadata = toFieldMetadata;
2088
+ exports.toFieldMetadataList = toFieldMetadataList;
2089
+ exports.toFilterFieldType = toFilterFieldType;
2090
+ exports.toFilterTree = toFilterTree;
2091
+ exports.toLocalDateTime = toLocalDateTime;
2092
+ exports.toLocalISODate = toLocalISODate;
2093
+ exports.toLocalISODateTime = toLocalISODateTime;
2094
+ exports.toReport = toReport;
2095
+ exports.toReportParameter = toReportParameter;
2096
+ exports.toReportParameters = toReportParameters;
2097
+ exports.toSavedFilter = toSavedFilter;
2098
+ exports.toSavedFilters = toSavedFilters;
2099
+ exports.updateNodeAtPath = updateNodeAtPath;
2100
+ exports.version = version;
2101
+ exports.waitForDialog = waitForDialog;
2102
+ return exports;
2103
+ })({});