keepup-admin 0.1.0__py3-none-any.whl

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.

Potentially problematic release.


This version of keepup-admin might be problematic. Click here for more details.

Files changed (86) hide show
  1. keepup/THIRD-PARTY.md +44 -0
  2. keepup/__init__.py +41 -0
  3. keepup/api_versions.py +100 -0
  4. keepup/audit.py +499 -0
  5. keepup/auth/__init__.py +7 -0
  6. keepup/auth/config.py +128 -0
  7. keepup/auth/dependencies.py +485 -0
  8. keepup/auth/dto/__init__.py +0 -0
  9. keepup/auth/dto/token.py +31 -0
  10. keepup/auth/factory.py +28 -0
  11. keepup/auth/login_throttle.py +151 -0
  12. keepup/auth/oidc.py +245 -0
  13. keepup/auth/oidc_policy.py +111 -0
  14. keepup/auth/oidc_routes.py +288 -0
  15. keepup/auth/panel_session.py +220 -0
  16. keepup/auth/permissions.py +59 -0
  17. keepup/auth/providers/__init__.py +0 -0
  18. keepup/auth/providers/base.py +168 -0
  19. keepup/auth/providers/local.py +180 -0
  20. keepup/auth/routes.py +660 -0
  21. keepup/auth/seed_accounts.py +322 -0
  22. keepup/auth/session_lifetime.py +104 -0
  23. keepup/auth/signing_key.py +138 -0
  24. keepup/auth/websocket.py +86 -0
  25. keepup/cluster.py +634 -0
  26. keepup/db.py +663 -0
  27. keepup/events.py +764 -0
  28. keepup/factory.py +484 -0
  29. keepup/instance.py +46 -0
  30. keepup/integrations.py +260 -0
  31. keepup/locks.py +412 -0
  32. keepup/logging_setup.py +690 -0
  33. keepup/metrics.py +818 -0
  34. keepup/metrics_retention.py +376 -0
  35. keepup/modules.py +572 -0
  36. keepup/notification_bus.py +355 -0
  37. keepup/plugins/__init__.py +9 -0
  38. keepup/plugins/admin.py +246 -0
  39. keepup/plugins/base.py +234 -0
  40. keepup/plugins/enablement.py +184 -0
  41. keepup/plugins/registry.py +171 -0
  42. keepup/plugins/route_mask.py +338 -0
  43. keepup/plugins/routes.py +376 -0
  44. keepup/roles.py +17 -0
  45. keepup/scheduler.py +93 -0
  46. keepup/schema.py +295 -0
  47. keepup/sections.json +104 -0
  48. keepup/settings.py +184 -0
  49. keepup/static/css/aos.css +1 -0
  50. keepup/static/css/main_nebula.css +232 -0
  51. keepup/static/css/main_new.css +852 -0
  52. keepup/static/css/tailwind.css +1 -0
  53. keepup/static/index_nebula.html +293 -0
  54. keepup/static/index_new.html +286 -0
  55. keepup/static/js/aos.js +1 -0
  56. keepup/static/js/feather-icons.js +13 -0
  57. keepup/static/js/main_new.js +1861 -0
  58. keepup/static/js/tailwind.js +83 -0
  59. keepup/static/modules/css/background_tasks.css +233 -0
  60. keepup/static/modules/css/cluster.css +16 -0
  61. keepup/static/modules/css/event_manager.css +386 -0
  62. keepup/static/modules/css/integration_logs.css +33 -0
  63. keepup/static/modules/css/metrics.css +115 -0
  64. keepup/static/modules/css/modules.css +189 -0
  65. keepup/static/modules/css/themes.css +563 -0
  66. keepup/static/modules/css/users.css +278 -0
  67. keepup/static/modules/js/background_tasks.js +657 -0
  68. keepup/static/modules/js/chart.js +14 -0
  69. keepup/static/modules/js/chartjs-adapter-date-fns.bundle.min.js +7 -0
  70. keepup/static/modules/js/cluster.js +363 -0
  71. keepup/static/modules/js/event_manager.js +979 -0
  72. keepup/static/modules/js/integration_logs.js +767 -0
  73. keepup/static/modules/js/metrics.js +908 -0
  74. keepup/static/modules/js/modules.js +1086 -0
  75. keepup/static/modules/js/themes.js +653 -0
  76. keepup/static/modules/js/users.js +784 -0
  77. keepup/tables.py +302 -0
  78. keepup/themes.py +496 -0
  79. keepup/web.py +182 -0
  80. keepup_admin-0.1.0.dist-info/METADATA +117 -0
  81. keepup_admin-0.1.0.dist-info/RECORD +86 -0
  82. keepup_admin-0.1.0.dist-info/WHEEL +5 -0
  83. keepup_admin-0.1.0.dist-info/licenses/LICENSE +202 -0
  84. keepup_admin-0.1.0.dist-info/licenses/NOTICE +22 -0
  85. keepup_admin-0.1.0.dist-info/licenses/THIRD-PARTY.md +44 -0
  86. keepup_admin-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1861 @@
1
+
2
+ let currentUser = null;
3
+
4
+ // endregion
5
+
6
+ /* ==========================================================================
7
+ Panel session.
8
+
9
+ The session is an httpOnly cookie the page cannot read. What the page keeps
10
+ under 'authToken' is the marker below, so sections that check for a token and
11
+ send `Bearer ${token}` keep working: the server reads `Bearer cookie` as no
12
+ header and uses the cookie. A change made by cookie must carry the CSRF value,
13
+ which the wrapper below adds to every same-origin request that is not a read.
14
+ ========================================================================== */
15
+ const SESSION_MARKER = 'cookie';
16
+ const CSRF_COOKIE = 'ss_csrf';
17
+ const CSRF_HEADER = 'X-CSRF-Token';
18
+ const CSRF_SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'];
19
+
20
+ function readCookie(name) {
21
+ const prefix = name + '=';
22
+ const found = (document.cookie || '').split(';')
23
+ .map(part => part.trim())
24
+ .find(part => part.startsWith(prefix));
25
+ return found ? decodeURIComponent(found.slice(prefix.length)) : null;
26
+ }
27
+
28
+ function isSameOriginUrl(url) {
29
+ try {
30
+ return new URL(url, window.location.href).origin === window.location.origin;
31
+ } catch (error) {
32
+ return false;
33
+ }
34
+ }
35
+
36
+ function installCsrfFetch(target) {
37
+ const originalFetch = target.fetch;
38
+ if (!originalFetch || originalFetch.csrfAware) {
39
+ return;
40
+ }
41
+ const wrapped = function (input, init) {
42
+ const request = typeof Request !== 'undefined' && input instanceof Request ? input : null;
43
+ const method = String((init && init.method) || (request && request.method) || 'GET').toUpperCase();
44
+ const url = request ? request.url : String(input);
45
+ const csrf = readCookie(CSRF_COOKIE);
46
+ if (csrf && !CSRF_SAFE_METHODS.includes(method) && isSameOriginUrl(url)) {
47
+ const headers = new Headers((init && init.headers) || (request && request.headers) || undefined);
48
+ if (!headers.has(CSRF_HEADER)) {
49
+ headers.set(CSRF_HEADER, csrf);
50
+ }
51
+ init = Object.assign({}, init || {}, { headers });
52
+ }
53
+ return originalFetch.call(target, input, init);
54
+ };
55
+ wrapped.csrfAware = true;
56
+ target.fetch = wrapped;
57
+ }
58
+
59
+ installCsrfFetch(window);
60
+
61
+ const ROLE_ADMIN = 'ADMIN';
62
+ const ROLE_CLIENT = 'CLIENT';
63
+
64
+
65
+ /* ==========================================================================
66
+ Adaptive layout.
67
+
68
+ The narrow/wide boundary is a design token, --layout-breakpoint, so a theme
69
+ can move it. A media query cannot read a custom property and there is no CSS
70
+ build step here to expand one, so the value is read once and the resulting
71
+ state is published as the .is-narrow class on <html>; every adaptive rule in
72
+ main_new.css matches on that class. The theme's head script sets the class
73
+ before the first paint -- this module only takes over and keeps it in step.
74
+ ========================================================================== */
75
+ const LAYOUT_NARROW_CLASS = 'is-narrow';
76
+ const LAYOUT_BREAKPOINT_FALLBACK = 768;
77
+ const LAYOUT_CHANGED_EVENT = 'app:layout:changed';
78
+
79
+ let layoutMediaQuery = null;
80
+
81
+ function readLayoutBreakpoint() {
82
+ const declared = getComputedStyle(document.documentElement)
83
+ .getPropertyValue('--layout-breakpoint');
84
+ const value = parseFloat(declared);
85
+ return Number.isFinite(value) && value > 0 ? value : LAYOUT_BREAKPOINT_FALLBACK;
86
+ }
87
+
88
+ function isNarrowLayout() {
89
+ return document.documentElement.classList.contains(LAYOUT_NARROW_CLASS);
90
+ }
91
+
92
+ function applyLayoutState(narrow) {
93
+ const changed = narrow !== isNarrowLayout();
94
+ document.documentElement.classList.toggle(LAYOUT_NARROW_CLASS, narrow);
95
+ if (!changed) return;
96
+ AppEventTarget.dispatchEvent(new CustomEvent(LAYOUT_CHANGED_EVENT, {
97
+ detail: { narrow }
98
+ }));
99
+ }
100
+
101
+ function initLayoutBreakpoint() {
102
+ // 0.02px below the token: matchMedia ranges are inclusive, so a plain
103
+ // max-width equal to the breakpoint would make both layouts true at exactly
104
+ // that width, and the md: utilities Tailwind builds from the same value
105
+ // start at the breakpoint itself.
106
+ layoutMediaQuery = window.matchMedia(`(max-width: ${readLayoutBreakpoint() - 0.02}px)`);
107
+ applyLayoutState(layoutMediaQuery.matches);
108
+ layoutMediaQuery.addEventListener('change', event => applyLayoutState(event.matches));
109
+ }
110
+
111
+ /* --------------------------------------------------------------------------
112
+ Navigation drawer. Below the breakpoint the sidebar floats over the content
113
+ instead of sitting beside it, so it needs a way out that a permanent column
114
+ never did: the backdrop, Esc, and picking a section all close it. Without
115
+ the last one the user lands on the section they chose behind a menu that is
116
+ still covering it.
117
+ -------------------------------------------------------------------------- */
118
+ const NAV_OPEN_CLASS = 'nav-open';
119
+ const NAV_LOCKED_CLASS = 'nav-locked';
120
+
121
+ function isNavOpen() {
122
+ return document.documentElement.classList.contains(NAV_OPEN_CLASS);
123
+ }
124
+
125
+ function setNavOpen(open) {
126
+ document.documentElement.classList.toggle(NAV_OPEN_CLASS, open);
127
+ document.body.classList.toggle(NAV_LOCKED_CLASS, open);
128
+ const toggle = document.getElementById('sidebarToggle');
129
+ if (toggle) {
130
+ toggle.setAttribute('aria-expanded', String(open));
131
+ }
132
+ }
133
+
134
+ function openNav() {
135
+ setNavOpen(true);
136
+ }
137
+
138
+ function closeNav() {
139
+ if (isNavOpen()) setNavOpen(false);
140
+ }
141
+
142
+ function toggleNav() {
143
+ setNavOpen(!isNavOpen());
144
+ }
145
+
146
+ function initNavDrawer() {
147
+ const toggle = document.getElementById('sidebarToggle');
148
+ if (toggle) {
149
+ toggle.addEventListener('click', toggleNav);
150
+ }
151
+
152
+ const backdrop = document.getElementById('nav-backdrop');
153
+ if (backdrop) {
154
+ backdrop.addEventListener('click', closeNav);
155
+ }
156
+
157
+ document.addEventListener('keydown', event => {
158
+ if (event.key === 'Escape') closeNav();
159
+ });
160
+
161
+ // Crossing the breakpoint either way leaves the drawer closed: open is a
162
+ // state of the narrow layout only, and carrying it into the wide one would
163
+ // leave the backdrop covering a page that has its sidebar back.
164
+ AppEventTarget.addEventListener(LAYOUT_CHANGED_EVENT, closeNav);
165
+ }
166
+
167
+ /* --------------------------------------------------------------------------
168
+ Responsive tables.
169
+
170
+ A section opts in by putting `responsive-table` on the table and nothing
171
+ else: no media query of its own, no card markup, no per-section JS. What the
172
+ helper does depends on how many columns the table has, because the two ways
173
+ out of a narrow screen suit different tables. Up to --table-card-columns the
174
+ row folds into a card, and each cell is labelled with its column heading --
175
+ read from <thead>, so renaming a column renames the label instead of leaving
176
+ a stale one hand-written in the row template. Wider than that, folding
177
+ produces a card nobody can scan, so the table keeps its shape and scrolls
178
+ inside its own container with the first column pinned.
179
+
180
+ Sections rebuild their tables through innerHTML, and often, so this cannot be
181
+ a one-off call at init: initResponsiveTables watches the module container and
182
+ re-runs. Work is skipped where it has already been done, so a re-run over an
183
+ unchanged table costs a query and nothing else.
184
+ -------------------------------------------------------------------------- */
185
+ const TABLE_HELPER_CLASS = 'responsive-table';
186
+ const TABLE_CARD_COLUMNS_FALLBACK = 6;
187
+ const TABLE_ENHANCE_DELAY_MS = 50;
188
+
189
+ let tableEnhanceTimer = null;
190
+
191
+ function readTableCardColumns() {
192
+ const declared = getComputedStyle(document.documentElement)
193
+ .getPropertyValue('--table-card-columns');
194
+ const value = parseInt(declared, 10);
195
+ return Number.isFinite(value) && value > 0 ? value : TABLE_CARD_COLUMNS_FALLBACK;
196
+ }
197
+
198
+ function wrapForHorizontalScroll(table) {
199
+ const parent = table.parentElement;
200
+ if (!parent || parent.classList.contains('table-scroll')) return;
201
+ // Several sections already wrapped their table in an overflow-x container
202
+ // of their own. Adopt it rather than nesting a second scrolling box inside
203
+ // it, which would leave two scrollbars for one table.
204
+ if (parent.classList.contains('overflow-x-auto')) {
205
+ parent.classList.add('table-scroll');
206
+ return;
207
+ }
208
+ const wrapper = document.createElement('div');
209
+ wrapper.className = 'table-scroll';
210
+ parent.insertBefore(wrapper, table);
211
+ wrapper.appendChild(table);
212
+ }
213
+
214
+ function labelCardCells(table, headers) {
215
+ table.querySelectorAll('tbody tr').forEach(row => {
216
+ const cells = row.children;
217
+ // A row that does not line up with the headings is not a data row --
218
+ // an empty-state or a spanning summary row. Labelling it by position
219
+ // would put the wrong heading in front of its text.
220
+ if (cells.length !== headers.length) return;
221
+ Array.from(cells).forEach((cell, index) => {
222
+ if (cell.dataset.label === undefined && headers[index]) {
223
+ cell.dataset.label = headers[index];
224
+ }
225
+ });
226
+ });
227
+ }
228
+
229
+ function enhanceTable(table) {
230
+ const headers = Array.from(table.querySelectorAll('thead th'))
231
+ .map(th => th.textContent.trim());
232
+ if (!headers.length) return;
233
+
234
+ if (headers.length > readTableCardColumns()) {
235
+ table.dataset.responsiveMode = 'scroll';
236
+ wrapForHorizontalScroll(table);
237
+ return;
238
+ }
239
+
240
+ table.dataset.responsiveMode = 'cards';
241
+ labelCardCells(table, headers);
242
+ }
243
+
244
+ function enhanceTables(root) {
245
+ const scope = (root && root.querySelectorAll) ? root : document;
246
+ if (scope.matches && scope.matches(`table.${TABLE_HELPER_CLASS}`)) {
247
+ enhanceTable(scope);
248
+ return;
249
+ }
250
+ scope.querySelectorAll(`table.${TABLE_HELPER_CLASS}`).forEach(enhanceTable);
251
+ }
252
+
253
+ function scheduleTableEnhance() {
254
+ if (tableEnhanceTimer) return;
255
+ tableEnhanceTimer = setTimeout(() => {
256
+ tableEnhanceTimer = null;
257
+ enhanceTables(document);
258
+ }, TABLE_ENHANCE_DELAY_MS);
259
+ }
260
+
261
+ function initResponsiveTables() {
262
+ enhanceTables(document);
263
+
264
+ const container = document.getElementById('modules-container');
265
+ if (!container) return;
266
+
267
+ // childList only: the helper's own writes are attributes, so it does not
268
+ // wake itself. Wrapping a wide table is a child change and costs exactly
269
+ // one extra pass, which then finds the wrapper already there.
270
+ new MutationObserver(scheduleTableEnhance)
271
+ .observe(container, { childList: true, subtree: true });
272
+ }
273
+
274
+ // The one surface sections are meant to use. Everything else about the layout
275
+ // is CSS matching on .is-narrow.
276
+ window.AdminLayout = {
277
+ NARROW_CLASS: LAYOUT_NARROW_CLASS,
278
+ LAYOUT_CHANGED: LAYOUT_CHANGED_EVENT,
279
+ isNarrow: isNarrowLayout,
280
+ breakpoint: readLayoutBreakpoint,
281
+ openNav,
282
+ closeNav,
283
+ toggleNav,
284
+ enhanceTables
285
+ };
286
+
287
+
288
+
289
+
290
+ function toggleSidebar() {
291
+ // In the narrow layout the panel is a drawer, so the chevron closes it
292
+ // rather than collapsing it. Collapsing there would both do nothing visible
293
+ // and overwrite the wide layout's saved state from a screen that has no
294
+ // wide layout.
295
+ if (isNarrowLayout()) {
296
+ closeNav();
297
+ return;
298
+ }
299
+
300
+ const sidebar = document.getElementById('sidebar');
301
+
302
+ sidebar.classList.toggle('sidebar-collapsed');
303
+ const isCollapsed = sidebar.classList.contains('sidebar-collapsed');
304
+ localStorage.setItem('sidebarCollapsed', isCollapsed);
305
+ }
306
+
307
+ // Restore menu state on page load
308
+ document.addEventListener('DOMContentLoaded', function() {
309
+ initLayoutBreakpoint();
310
+ applyThemeBranding();
311
+ const sidebar = document.getElementById('sidebar');
312
+ const isCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
313
+
314
+ if (isCollapsed) {
315
+ sidebar.classList.add('sidebar-collapsed');
316
+ }
317
+ // Add a handler for the menu toggle button
318
+ const toggleButton = document.getElementById('toggleSidebar');
319
+ if (toggleButton) {
320
+ toggleButton.addEventListener('click', toggleSidebar);
321
+ }
322
+
323
+ if (typeof feather !== 'undefined') {
324
+ feather.replace();
325
+ }
326
+ });
327
+
328
+ async function applyThemeBranding() {
329
+ // The markup already carries the name baked in at build time by
330
+ // replace_placeholder.sh. A theme without branding leaves it alone, and so
331
+ // does a failed request -- the corner is never left empty.
332
+ let brand;
333
+ try {
334
+ const response = await fetch('/api/theme/brand');
335
+ if (!response.ok) return;
336
+ brand = await response.json();
337
+ } catch (error) {
338
+ console.warn('Failed to fetch theme brand:', error);
339
+ return;
340
+ }
341
+ if (!brand || (!brand.brand_name && !brand.logo_url)) return;
342
+
343
+ const name = brand.brand_name || document.title;
344
+ if (brand.brand_name) {
345
+ document.title = brand.brand_name;
346
+ }
347
+
348
+ document.querySelectorAll('.logo-text').forEach(element => {
349
+ if (brand.logo_url) {
350
+ const logo = document.createElement('img');
351
+ logo.src = brand.logo_url;
352
+ logo.alt = name;
353
+ logo.className = 'logo-image';
354
+ element.replaceChildren(logo);
355
+ } else {
356
+ element.textContent = brand.brand_name;
357
+ }
358
+ });
359
+ }
360
+
361
+ function refreshEntireUI() {
362
+ if (window.goodsModule) {
363
+ window.goodsModule.refreshEntireUI();
364
+ }
365
+ updateUIAfterAuth();
366
+ feather.replace();
367
+ }
368
+
369
+ function handleNavigation(e) {
370
+ e.preventDefault();
371
+
372
+ if (!checkAuth()) return;
373
+
374
+ document.querySelectorAll('.nav-item').forEach(navItem => {
375
+ navItem.classList.remove('active');
376
+ });
377
+ this.classList.add('active');
378
+
379
+ const targetId = this.dataset.target;
380
+
381
+ showSection(targetId);
382
+ const sectionName = this.querySelector('span').textContent;
383
+ document.getElementById('current-section-title').textContent = sectionName;
384
+
385
+ // IMPORTANT: use appSections to get the route
386
+ const routePath = appSections.getRoutePath(targetId);
387
+ if (routePath) {
388
+ appRouter.navigate(routePath);
389
+ }
390
+
391
+ const sectionInfo = appSections.getSection(targetId);
392
+ if (sectionInfo && sectionInfo.handler) {
393
+ sectionInfo.handler();
394
+ }
395
+
396
+ closeNav();
397
+ }
398
+
399
+ // Central routing system
400
+ const appRouter = {
401
+ routes: new Map(),
402
+ currentRoute: null,
403
+ isNavigating: false, // Flag to prevent recursion
404
+
405
+ registerRoute(path, handler) {
406
+ console.log(`Registering route: ${path}`);
407
+ this.routes.set(path, handler);
408
+ },
409
+
410
+ unregisterRoute(path) {
411
+ this.routes.delete(path);
412
+ },
413
+
414
+ handleUrlChange() {
415
+ if (this.isNavigating) return;
416
+
417
+ const currentPath = window.location.pathname;
418
+ console.log('Router: URL changed to', currentPath);
419
+ console.log('Available routes:', Array.from(this.routes.keys()));
420
+
421
+ if (this.routes.has(currentPath)) {
422
+ const handler = this.routes.get(currentPath);
423
+ console.log('Router: Found exact match, calling handler');
424
+ this.isNavigating = true;
425
+ try {
426
+ handler();
427
+ this.currentRoute = currentPath;
428
+ } finally {
429
+ setTimeout(() => {
430
+ this.isNavigating = false;
431
+ }, 100);
432
+ }
433
+ return;
434
+ }
435
+
436
+ let matched = false;
437
+ for (const [route, handler] of this.routes) {
438
+ if (currentPath.startsWith(route)) {
439
+ console.log('Router: Found partial match', route);
440
+ this.isNavigating = true;
441
+ try {
442
+ handler();
443
+ this.currentRoute = currentPath;
444
+ matched = true;
445
+ } finally {
446
+ setTimeout(() => {
447
+ this.isNavigating = false;
448
+ }, 100);
449
+ }
450
+ break;
451
+ }
452
+ }
453
+
454
+ if (!matched) {
455
+ console.log('Router: No route found for', currentPath, 'redirecting to /selfcare');
456
+ if (currentPath.includes('/modules/')) {
457
+ console.log('Router: Module route not yet registered, waiting...');
458
+ setTimeout(() => {
459
+ this.handleUrlChange();
460
+ }, 1000);
461
+ } else {
462
+ this.navigate('/selfcare');
463
+ }
464
+ }
465
+ },
466
+
467
+ navigate(path) {
468
+ if (this.isNavigating) {
469
+ console.log('Router: Navigation already in progress, skipping');
470
+ return;
471
+ }
472
+
473
+ if (window.location.pathname === path) {
474
+ console.log('Router: Already on target path, skipping');
475
+ return;
476
+ }
477
+
478
+ this.isNavigating = true;
479
+ try {
480
+ window.history.pushState({}, '', path);
481
+ this.handleUrlChange();
482
+ } finally {
483
+ setTimeout(() => {
484
+ this.isNavigating = false;
485
+ }, 100);
486
+ }
487
+ },
488
+
489
+ getCurrentRoute() {
490
+ return this.currentRoute;
491
+ },
492
+
493
+ getRoutes() {
494
+ return Array.from(this.routes.keys());
495
+ }
496
+ };
497
+
498
+ // Make it globally accessible for modules
499
+ window.appRouter = appRouter;
500
+
501
+ function setupRouter() {
502
+ appRouter.registerRoute('/selfcare/modules/goods', () => {
503
+ console.log('Router: Handling goods route');
504
+ showGoodsSection();
505
+ });
506
+
507
+ appRouter.registerRoute('/selfcare', () => {
508
+ console.log('Router: Handling main selfcare route');
509
+ const defaultSection = document.querySelector('.nav-item');
510
+ if (defaultSection) {
511
+ defaultSection.click();
512
+ }
513
+ });
514
+
515
+ appRouter.registerRoute('/', () => {
516
+ appRouter.navigate('/selfcare');
517
+ });
518
+
519
+ appRouter.registerRoute('/selfcare/modules/', () => {
520
+ // This route will be overridden by modules
521
+ });
522
+
523
+ window.addEventListener('popstate', function(event) {
524
+ appRouter.handleUrlChange();
525
+ });
526
+
527
+ document.addEventListener('click', function(e) {
528
+ const link = e.target.closest('a');
529
+ if (link && link.href) {
530
+ const url = new URL(link.href);
531
+ const path = url.pathname;
532
+
533
+ if (path.startsWith('/selfcare') || path === '/') {
534
+ e.preventDefault();
535
+ appRouter.navigate(path);
536
+ }
537
+ }
538
+ });
539
+ }
540
+
541
+ function initializeApp() {
542
+ const contentSections = document.querySelectorAll('.content-section');
543
+ contentSections.forEach(section => {
544
+ section.classList.remove('active');
545
+ });
546
+
547
+ // loadFilterState();
548
+
549
+ initNavDrawer();
550
+ initResponsiveTables();
551
+
552
+ feather.replace();
553
+
554
+ if (typeof AOS !== 'undefined') {
555
+ AOS.init();
556
+ }
557
+
558
+ setupRouter();
559
+ registerAppSections();
560
+ setupNavigation();
561
+ setupAuthForms();
562
+
563
+ // A token left from before the cookie is traded for one and forgotten; with
564
+ // no token at all the cookie may still hold a session, so it is asked too.
565
+ adoptSession().then(async isValid => {
566
+ if (isValid && !(await ensureAgreements())) {
567
+ return;
568
+ }
569
+ if (isValid) {
570
+ loadModules().then(() => {
571
+ updateVersionPanelVisibility();
572
+ appRouter.handleUrlChange();
573
+
574
+ setTimeout(() => {
575
+ const activeSection = document.querySelector('.content-section.active');
576
+ if (!activeSection) {
577
+ const defaultNav = document.querySelector('.nav-item');
578
+ if (defaultNav) {
579
+ defaultNav.click();
580
+ }
581
+ }
582
+ }, 200);
583
+ });
584
+ } else {
585
+ showAuthModal();
586
+ }
587
+ });
588
+ }
589
+
590
+ /* ==========================================================================
591
+ Platform documents.
592
+
593
+ The panel does not open until the person has accepted the current version of
594
+ every document required of them; the server refuses the sections' requests
595
+ meanwhile (403 agreements_required). Texts and versions come from the server,
596
+ and what is sent back is exactly the versions that were shown.
597
+ ========================================================================== */
598
+ function pendingDocuments(overview) {
599
+ const pending = new Set((overview && overview.pending) || []);
600
+ return ((overview && overview.documents) || []).filter(doc => pending.has(doc.id));
601
+ }
602
+
603
+ function agreementAcceptance(documents) {
604
+ return { documents: (documents || []).map(doc => ({ id: doc.id, version: doc.version })) };
605
+ }
606
+ // end of platform documents helpers
607
+
608
+ async function documentsPending() {
609
+ // The framework does not ship documents and declares no routes for them:
610
+ // those belong to whichever application actually has the documents. What
611
+ // the framework does say is whether this person has anything to accept;
612
+ // without that check the shell used to call /api/agreements for everyone,
613
+ // and in an application with no documents that was a refusal on every
614
+ // sign-in.
615
+ try {
616
+ const response = await fetch('/api/auth/me');
617
+ if (!response.ok) {
618
+ return false;
619
+ }
620
+ return Boolean((await response.json()).documents_pending);
621
+ } catch (error) {
622
+ console.warn('Could not tell whether documents are pending:', error);
623
+ return false;
624
+ }
625
+ }
626
+
627
+ async function ensureAgreements() {
628
+ if (!(await documentsPending())) {
629
+ return true;
630
+ }
631
+ let overview;
632
+ try {
633
+ const response = await fetch('/api/agreements');
634
+ if (!response.ok) {
635
+ return true;
636
+ }
637
+ overview = await response.json();
638
+ } catch (error) {
639
+ console.warn('Could not read the platform documents:', error);
640
+ return true;
641
+ }
642
+ const documents = pendingDocuments(overview);
643
+ if (!documents.length) {
644
+ return true;
645
+ }
646
+ return showAgreementsDialog(documents);
647
+ }
648
+
649
+ function showAgreementsDialog(documents) {
650
+ return new Promise(resolve => {
651
+ const overlay = document.createElement('div');
652
+ overlay.className = 'fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-60';
653
+ overlay.setAttribute('role', 'dialog');
654
+ overlay.setAttribute('aria-modal', 'true');
655
+
656
+ const panel = document.createElement('div');
657
+ panel.className = 'bg-white text-gray-900 rounded-lg shadow-xl w-full max-w-3xl flex flex-col';
658
+ panel.style.maxHeight = '90vh';
659
+
660
+ const header = document.createElement('div');
661
+ header.className = 'p-4 border-b';
662
+ const title = document.createElement('h2');
663
+ title.className = 'text-lg font-semibold';
664
+ title.textContent = 'Before you continue';
665
+ const lead = document.createElement('p');
666
+ lead.className = 'text-sm text-gray-600 mt-1';
667
+ lead.textContent = 'Please read and accept the documents below. You accept these versions; '
668
+ + 'a new version will be shown to you again.';
669
+ header.append(title, lead);
670
+
671
+ const body = document.createElement('div');
672
+ body.className = 'p-4 overflow-y-auto';
673
+ documents.forEach(doc => {
674
+ const heading = document.createElement('h3');
675
+ heading.className = 'font-semibold mt-2';
676
+ heading.textContent = doc.title + ' (version ' + doc.version + ')';
677
+ const text = document.createElement('pre');
678
+ text.className = 'whitespace-pre-wrap text-sm bg-gray-50 border rounded p-3 mt-2 mb-4';
679
+ text.style.fontFamily = 'inherit';
680
+ text.textContent = doc.text || '';
681
+ body.append(heading, text);
682
+ });
683
+
684
+ const footer = document.createElement('div');
685
+ footer.className = 'p-4 border-t flex flex-col gap-3';
686
+ const agree = document.createElement('label');
687
+ agree.className = 'flex items-start gap-2 text-sm';
688
+ const box = document.createElement('input');
689
+ box.type = 'checkbox';
690
+ box.className = 'mt-1';
691
+ const agreeText = document.createElement('span');
692
+ agreeText.textContent = 'I have read and accept ' + documents.map(doc => doc.title).join(', ') + '.';
693
+ agree.append(box, agreeText);
694
+ const error = document.createElement('p');
695
+ error.className = 'text-sm text-red-600';
696
+ error.hidden = true;
697
+ const buttons = document.createElement('div');
698
+ buttons.className = 'flex flex-col md:flex-row gap-2 md:justify-end';
699
+ const leave = document.createElement('button');
700
+ leave.type = 'button';
701
+ leave.className = 'px-4 py-2 rounded border';
702
+ leave.textContent = 'Sign out';
703
+ const accept = document.createElement('button');
704
+ accept.type = 'button';
705
+ accept.className = 'px-4 py-2 rounded bg-blue-600 text-white disabled:opacity-50';
706
+ accept.textContent = 'Accept and continue';
707
+ accept.disabled = true;
708
+ box.addEventListener('change', () => { accept.disabled = !box.checked; });
709
+ buttons.append(leave, accept);
710
+ footer.append(agree, error, buttons);
711
+
712
+ panel.append(header, body, footer);
713
+ overlay.appendChild(panel);
714
+ document.body.appendChild(overlay);
715
+
716
+ leave.addEventListener('click', async () => {
717
+ overlay.remove();
718
+ await logout();
719
+ resolve(false);
720
+ });
721
+ accept.addEventListener('click', async () => {
722
+ accept.disabled = true;
723
+ error.hidden = true;
724
+ try {
725
+ const response = await fetch('/api/agreements/accept', {
726
+ method: 'POST',
727
+ headers: { 'Content-Type': 'application/json' },
728
+ body: JSON.stringify(agreementAcceptance(documents))
729
+ });
730
+ const data = await response.json().catch(() => ({}));
731
+ if (!response.ok) {
732
+ // 409: a document changed while the dialog was open; show the new text.
733
+ error.textContent = data.detail || ('Request failed (' + response.status + ')');
734
+ error.hidden = false;
735
+ if (response.status === 409) {
736
+ overlay.remove();
737
+ resolve(await ensureAgreements());
738
+ return;
739
+ }
740
+ accept.disabled = !box.checked;
741
+ return;
742
+ }
743
+ overlay.remove();
744
+ resolve(true);
745
+ } catch (failure) {
746
+ error.textContent = 'Could not reach the server: ' + failure.message;
747
+ error.hidden = false;
748
+ accept.disabled = !box.checked;
749
+ }
750
+ });
751
+ });
752
+ }
753
+
754
+ async function adoptSession() {
755
+ const stored = localStorage.getItem('authToken');
756
+ if (stored && stored !== SESSION_MARKER) {
757
+ try {
758
+ await fetch('/api/auth/session', {
759
+ method: 'POST',
760
+ headers: { 'Authorization': `Bearer ${stored}` }
761
+ });
762
+ } catch (error) {
763
+ console.warn('Could not move the session into a cookie:', error);
764
+ }
765
+ localStorage.removeItem('authToken');
766
+ }
767
+ return verifyToken();
768
+ }
769
+
770
+ function showSection(sectionId) {
771
+ const contentSections = document.querySelectorAll('.content-section');
772
+ contentSections.forEach(section => {
773
+ section.classList.remove('active');
774
+ });
775
+
776
+ const targetSection = document.getElementById(sectionId);
777
+ if (targetSection) {
778
+ targetSection.classList.add('active');
779
+ }
780
+ }
781
+
782
+ function openGoodsModule() {
783
+ appRouter.navigate('/selfcare/modules/goods');
784
+ }
785
+
786
+ window.openGoodsModule = openGoodsModule;
787
+
788
+ async function loadModules() {
789
+ try {
790
+ const token = localStorage.getItem('authToken');
791
+ const response = await fetch('/api/modules', {
792
+ headers: {
793
+ 'Authorization': `Bearer ${token}`
794
+ }
795
+ });
796
+
797
+ if (response.ok) {
798
+ const data = await response.json();
799
+ await initializeModules(data.modules);
800
+ return data.modules; // Return the modules
801
+ }
802
+ return [];
803
+ } catch (error) {
804
+ return [];
805
+ }
806
+ }
807
+
808
+ const AppEventTarget = new EventTarget();
809
+ const MODULES_LOADED_EVENT = 'app:modules:loaded';
810
+
811
+ window.AppEventTarget = AppEventTarget;
812
+ window.AppEvents = {
813
+ MODULES_LOADED: MODULES_LOADED_EVENT,
814
+ AUTH_CHANGED: 'app:auth:changed',
815
+ ROUTE_CHANGED: 'app:route:changed'
816
+ };
817
+
818
+ async function initializeModules(modules) {
819
+ if (!modules || modules.length === 0) {
820
+ console.log('No modules available to load');
821
+ return;
822
+ }
823
+
824
+ loadedModules = modules;
825
+
826
+ console.log('Loading modules:', modules);
827
+
828
+ try {
829
+ // First load the CSS
830
+ modules.forEach(module => {
831
+ if (module.css) {
832
+ const link = document.createElement('link');
833
+ link.rel = 'stylesheet';
834
+ link.href = moduleAssetUrl(module.css, module.version);
835
+ document.head.appendChild(link);
836
+ }
837
+ });
838
+
839
+ // Then load the modules' JS sequentially
840
+ for (const module of modules) {
841
+ if (module.js) {
842
+ try {
843
+ await loadScript(moduleAssetUrl(module.js, module.version));
844
+ console.log('Module loaded:', module.js);
845
+ } catch (error) {
846
+ console.error('Failed to load JS module:', module.js, error);
847
+ }
848
+ }
849
+ }
850
+
851
+ // Initialize modules and register their routes
852
+ modules.forEach(module => {
853
+ if (module.initFunction && typeof window[module.initFunction] === 'function') {
854
+ try {
855
+ console.log('Initializing module:', module.initFunction);
856
+ window[module.initFunction]();
857
+
858
+ // Register the module's route if specified
859
+ if (module.routePath && module.sectionId) {
860
+ console.log(`Registering module route: ${module.routePath} -> ${module.sectionId}`);
861
+ appRouter.registerRoute(module.routePath, () => {
862
+ console.log(`Router: Handling module route ${module.routePath}`);
863
+ if (window[module.handlerFunction]) {
864
+ window[module.handlerFunction]();
865
+ }
866
+ });
867
+ }
868
+ } catch (error) {
869
+ console.error('Failed to initialize module:', module.initFunction, error);
870
+ }
871
+ } else {
872
+ console.warn('Initialization function not found:', module.initFunction);
873
+ }
874
+ });
875
+ const event = new CustomEvent(MODULES_LOADED_EVENT, {
876
+ detail: {
877
+ modules: loadedModules,
878
+ count: loadedModules.length,
879
+ timestamp: new Date().toISOString()
880
+ },
881
+ bubbles: false,
882
+ cancelable: true
883
+ });
884
+
885
+ AppEventTarget.dispatchEvent(event);
886
+ window.frontendModulesloaded = true;
887
+ } catch (error) {
888
+ console.error('Failed to initialize modules:', error);
889
+ }
890
+ }
891
+
892
+ function handleRouteAfterModulesLoaded() {
893
+ const currentPath = window.location.pathname;
894
+
895
+ setTimeout(() => {
896
+ appRouter.handleUrlChange();
897
+ }, 100);
898
+ }
899
+
900
+ // Module version in its file addresses.
901
+ //
902
+ // The browser caches module.css and module.js under the usual rules, and
903
+ // after editing a module the user kept seeing the old version until a hard
904
+ // reload: CSS from one version with a script from another produced, for
905
+ // example, buttons under the canvas. The version from the module catalogue
906
+ // makes the address new as soon as the module is updated.
907
+ function moduleAssetUrl(path, version) {
908
+ if (!path || !version) return path;
909
+ return path + (path.includes('?') ? '&' : '?') + 'v=' + encodeURIComponent(version);
910
+ }
911
+
912
+ function loadScript(src) {
913
+ return new Promise((resolve, reject) => {
914
+ const script = document.createElement('script');
915
+ script.src = src;
916
+ script.onload = resolve;
917
+ script.onerror = reject;
918
+ document.head.appendChild(script);
919
+ });
920
+ }
921
+
922
+ function updateNavigationWithModules() {
923
+ const container = document.getElementById('modules-nav-container');
924
+ if (!container) {
925
+ return;
926
+ }
927
+
928
+ container.innerHTML = '';
929
+
930
+ loadedModules.forEach(module => {
931
+ const navItem = document.createElement('a');
932
+ navItem.href = '#';
933
+ navItem.className = 'nav-item';
934
+ navItem.setAttribute('data-target', `${module.id}-section`);
935
+
936
+ navItem.innerHTML = `
937
+ <i data-feather="users" class="w-5 h-5"></i>
938
+ <span class="nav-text">${module.name}</span>
939
+ `;
940
+
941
+ container.appendChild(navItem);
942
+ });
943
+
944
+ setupNavigation();
945
+ feather.replace();
946
+ }
947
+
948
+ // Authentication check
949
+ function checkAuth() {
950
+ const token = localStorage.getItem('authToken');
951
+ if (!token) {
952
+ showAuthModal();
953
+ return false;
954
+ }
955
+ verifyToken();
956
+ return true;
957
+ }
958
+
959
+ function showAuthModal() {
960
+ const authBlock = document.getElementById('authBlock');
961
+ authBlock.classList.remove('hidden');
962
+
963
+ document.getElementById('loginTabContent').classList.add('active');
964
+ document.getElementById('registerTabContent').classList.remove('active');
965
+ document.getElementById('loginTab').classList.add('border-blue-600', 'text-blue-600');
966
+ document.getElementById('registerTab').classList.remove('border-blue-600', 'text-blue-600');
967
+
968
+ applyPublicConfig();
969
+ }
970
+
971
+ // What this deployment offers before anybody has signed in: whether accounts
972
+ // can be created here at all, and the terms a person is asked to agree to.
973
+ let publicConfigPromise = null;
974
+
975
+ function loadPublicConfig() {
976
+ if (!publicConfigPromise) {
977
+ publicConfigPromise = fetch('/api/public/config')
978
+ .then(response => (response.ok ? response.json() : null))
979
+ .catch(() => null);
980
+ }
981
+ return publicConfigPromise;
982
+ }
983
+
984
+ async function applyPublicConfig() {
985
+ const config = await loadPublicConfig();
986
+ const registerTab = document.getElementById('registerTab');
987
+
988
+ // Registration closed is the default, so the tab stays out of sight unless
989
+ // the server says otherwise: a form that creates accounts nobody activates
990
+ // contradicts the landing page, which sends people to the bot.
991
+ if (registerTab) {
992
+ registerTab.hidden = !(config && config.self_registration);
993
+ }
994
+
995
+ const terms = document.getElementById('termsContent');
996
+ if (terms && config && config.terms) {
997
+ terms.textContent = config.terms;
998
+ terms.classList.add('terms-plain');
999
+ }
1000
+ }
1001
+
1002
+ function closeAuthModal() {
1003
+ const authBlock = document.getElementById('authBlock');
1004
+ authBlock.classList.add('hidden');
1005
+ }
1006
+
1007
+ function setupNavigation() {
1008
+ const navItems = document.querySelectorAll('.nav-item');
1009
+ navItems.forEach(item => {
1010
+ item.removeEventListener('click', handleNavigation);
1011
+ });
1012
+
1013
+ navItems.forEach(item => {
1014
+ item.addEventListener('click', handleNavigation);
1015
+ });
1016
+
1017
+ document.addEventListener('click', function(e) {
1018
+ if (e.target.closest('.nav-item')) {
1019
+ handleNavigation.call(e.target.closest('.nav-item'), e);
1020
+ }
1021
+ });
1022
+ }
1023
+
1024
+ const appSections = {
1025
+ sections: new Map(),
1026
+
1027
+ registerSection(targetId, routePath, handler) {
1028
+ this.sections.set(targetId, { routePath, handler });
1029
+
1030
+ if (window.appRouter) {
1031
+ window.appRouter.registerRoute(routePath, handler);
1032
+ }
1033
+ },
1034
+
1035
+ getSection(targetId) {
1036
+ return this.sections.get(targetId);
1037
+ },
1038
+
1039
+ getRoutePath(targetId) {
1040
+ const section = this.sections.get(targetId);
1041
+ return section ? section.routePath : '/selfcare';
1042
+ },
1043
+
1044
+ getSections() {
1045
+ return Array.from(this.sections.keys());
1046
+ }
1047
+ };
1048
+
1049
+ window.appSections = appSections;
1050
+
1051
+ function setupAuthForms() {
1052
+ const loginTab = document.getElementById('loginTab');
1053
+ const registerTab = document.getElementById('registerTab');
1054
+ const loginTabContent = document.getElementById('loginTabContent');
1055
+ const registerTabContent = document.getElementById('registerTabContent');
1056
+
1057
+ if (loginTab && registerTab) {
1058
+ loginTab.addEventListener('click', function() {
1059
+ loginTab.classList.add('border-blue-600', 'text-blue-600');
1060
+ registerTab.classList.remove('border-blue-600', 'text-blue-600');
1061
+ registerTab.classList.add('text-gray-500');
1062
+
1063
+ loginTabContent.classList.add('active');
1064
+ registerTabContent.classList.remove('active');
1065
+ });
1066
+
1067
+ registerTab.addEventListener('click', function() {
1068
+ registerTab.classList.add('border-blue-600', 'text-blue-600');
1069
+ loginTab.classList.remove('border-blue-600', 'text-blue-600');
1070
+ loginTab.classList.add('text-gray-500');
1071
+
1072
+ registerTabContent.classList.add('active');
1073
+ loginTabContent.classList.remove('active');
1074
+ });
1075
+ }
1076
+
1077
+ // Forgot password (task 272): the link leads to the bot, and the reset is
1078
+ // issued by it. The bot's name comes from the server -- it differs between
1079
+ // the stand and production, and hardcoding it into the markup would mean
1080
+ // keeping two truths. If the server doesn't answer, the link stays a hint
1081
+ // with no destination, rather than a broken address.
1082
+ applyForgotPasswordLink();
1083
+
1084
+ // Updated sign-in form handler
1085
+ document.getElementById('loginForm').addEventListener('submit', function (e) {
1086
+ e.preventDefault();
1087
+ const username = document.getElementById('loginUsername').value;
1088
+ const password = document.getElementById('loginPassword').value;
1089
+ login(username, password);
1090
+ });
1091
+
1092
+ document.getElementById('registerForm').addEventListener('submit', function (e) {
1093
+ e.preventDefault();
1094
+ const username = document.getElementById('registerUsername').value;
1095
+ const password = document.getElementById('registerPassword').value;
1096
+ const passwordConfirm = document.getElementById('registerPasswordConfirm').value;
1097
+ const email = document.getElementById('registerEmail').value;
1098
+ const phone = document.getElementById('registerPhone').value;
1099
+ const fullName = document.getElementById('registerFullName').value;
1100
+ const agreeTerms = document.getElementById('registerAgreeTerms').checked;
1101
+
1102
+ if (password !== passwordConfirm) {
1103
+ showAuthMessage('Passwords do not match', 'error');
1104
+ return;
1105
+ }
1106
+
1107
+ if (!agreeTerms) {
1108
+ showAuthMessage('You must agree to the terms of use', 'error');
1109
+ return;
1110
+ }
1111
+
1112
+ register(username, password, email, phone, fullName, agreeTerms);
1113
+ });
1114
+ }
1115
+
1116
+ function registerAppSections() {
1117
+
1118
+ appSections.registerSection(
1119
+ 'upload-section',
1120
+ '/selfcare/upload',
1121
+ () => {
1122
+ showSection('upload-section');
1123
+ loadXmlSources();
1124
+ }
1125
+ );
1126
+
1127
+ appSections.registerSection(
1128
+ 'dashboard-section',
1129
+ '/selfcare',
1130
+ () => {
1131
+ showSection('dashboard-section');
1132
+ }
1133
+ );
1134
+ }
1135
+
1136
+ // The token lives a day and expires silently: without this the panel simply
1137
+ // starts getting refusals in the middle of the work. The server tells how long
1138
+ // it has at login, and the session is exchanged an hour before the end -- while
1139
+ // the token is still valid, which is the only time the exchange is allowed.
1140
+ const SESSION_REFRESH_LEAD_SECONDS = 3600;
1141
+ let sessionRefreshTimer = null;
1142
+
1143
+ function scheduleSessionRefresh(expiresInSeconds) {
1144
+ if (sessionRefreshTimer) {
1145
+ clearTimeout(sessionRefreshTimer);
1146
+ sessionRefreshTimer = null;
1147
+ }
1148
+ if (!expiresInSeconds) {
1149
+ return;
1150
+ }
1151
+ // Never sooner than a minute: a token that short is about to be replaced
1152
+ // by a login anyway, and a tight timer would spin.
1153
+ const delay = Math.max(60, expiresInSeconds - SESSION_REFRESH_LEAD_SECONDS);
1154
+ sessionRefreshTimer = setTimeout(refreshSession, delay * 1000);
1155
+ }
1156
+
1157
+ async function refreshSession() {
1158
+ if (!localStorage.getItem('authToken')) {
1159
+ return;
1160
+ }
1161
+ try {
1162
+ const response = await fetch('/api/auth/refresh', { method: 'POST' });
1163
+ if (!response.ok) {
1164
+ // Nothing to do about it here: the next request will be refused and
1165
+ // the panel asks for a login as before.
1166
+ console.warn('Failed to refresh session:', response.status);
1167
+ return;
1168
+ }
1169
+ const data = await response.json();
1170
+ if (data.access_token) {
1171
+ // The renewed session is already in the cookie; the body's token
1172
+ // is for agents and is not kept.
1173
+ scheduleSessionRefresh(data.expires_in);
1174
+ }
1175
+ } catch (error) {
1176
+ console.warn('Failed to refresh session:', error);
1177
+ }
1178
+ }
1179
+
1180
+ async function login(username, password) {
1181
+ try {
1182
+ const response = await fetch('/api/auth/login', {
1183
+ method: 'POST',
1184
+ headers: {
1185
+ 'Content-Type': 'application/json'
1186
+ },
1187
+ body: JSON.stringify({ username, password })
1188
+ });
1189
+
1190
+ const data = await response.json();
1191
+
1192
+ if (response.ok) {
1193
+ localStorage.setItem('authToken', SESSION_MARKER);
1194
+ scheduleSessionRefresh(data.expires_in);
1195
+ const userResponse = await fetch('/api/auth/me');
1196
+
1197
+ if (userResponse.ok) {
1198
+ const userData = await userResponse.json();
1199
+ currentUser = userData;
1200
+ updateUIAfterAuth();
1201
+ closeAuthModal();
1202
+ if (!(await ensureAgreements())) {
1203
+ return;
1204
+ }
1205
+ await loadModules();
1206
+ refreshEntireUI();
1207
+
1208
+ closeAuthModal();
1209
+ showAuthMessage('Signed in successfully!', 'success');
1210
+ } else {
1211
+ showAuthMessage('Failed to get user data', 'error');
1212
+ }
1213
+ } else {
1214
+ showAuthMessage(data.detail || 'Sign-in failed', 'error');
1215
+ }
1216
+ } catch (error) {
1217
+ showAuthMessage('Network error: ' + error, 'error');
1218
+ }
1219
+ }
1220
+
1221
+ function togglePasswordVisibility(inputId) {
1222
+ const passwordInput = document.getElementById(inputId);
1223
+ const toggleButton = document.getElementById(inputId + 'Toggle');
1224
+
1225
+ if (passwordInput.type === 'password') {
1226
+ passwordInput.type = 'text';
1227
+ toggleButton.innerHTML = '<i data-feather="eye-off" class="w-4 h-4"></i>';
1228
+ } else {
1229
+ passwordInput.type = 'password';
1230
+ toggleButton.innerHTML = '<i data-feather="eye" class="w-4 h-4"></i>';
1231
+ }
1232
+ feather.replace();
1233
+ }
1234
+
1235
+
1236
+ async function register(username, password, email = null, phone = null, fullName = null, agreeTerms = false) {
1237
+ try {
1238
+ const registerData = {
1239
+ username: username.trim(),
1240
+ password: password,
1241
+ agree_terms: agreeTerms
1242
+ };
1243
+
1244
+ // Add optional fields only if present
1245
+ if (email && email.trim()) {
1246
+ registerData.email = email.trim();
1247
+ }
1248
+
1249
+ if (phone && phone.trim()) {
1250
+ // Strip formatting from the phone number
1251
+ const cleanedPhone = phone.replace(/\D/g, '');
1252
+ if (cleanedPhone) {
1253
+ registerData.phone = cleanedPhone;
1254
+ }
1255
+ }
1256
+
1257
+ if (fullName && fullName.trim()) {
1258
+ registerData.full_name = fullName.trim();
1259
+ }
1260
+
1261
+ console.log('Registration data being sent:', registerData);
1262
+
1263
+ const response = await fetch('/api/auth/register', {
1264
+ method: 'POST',
1265
+ headers: {
1266
+ 'Content-Type': 'application/json'
1267
+ },
1268
+ body: JSON.stringify(registerData)
1269
+ });
1270
+
1271
+ const responseText = await response.text();
1272
+ console.log('Server response (text):', responseText);
1273
+
1274
+ let data;
1275
+ try {
1276
+ data = JSON.parse(responseText);
1277
+ } catch (e) {
1278
+ console.error('Failed to parse JSON response:', e);
1279
+ showAuthMessage('Server error: invalid response format', 'error');
1280
+ return;
1281
+ }
1282
+
1283
+ if (response.status === 422) {
1284
+ // Handle validation errors
1285
+ const errorMessage = handleValidationError(data);
1286
+ showAuthMessage(`Error: ${errorMessage}. Please check the entered data.`, 'error');
1287
+ return;
1288
+ }
1289
+
1290
+ if (response.ok && data.success) {
1291
+ showAuthMessage('Registration successful! Wait for administrator activation.', 'success');
1292
+
1293
+ // Reset the registration form
1294
+ resetRegistrationForm();
1295
+
1296
+ // Switch to the sign-in tab after 2 seconds
1297
+ setTimeout(() => {
1298
+ document.getElementById('loginTab').click();
1299
+ }, 2000);
1300
+ } else {
1301
+ // Generic handling of other errors
1302
+ const errorMsg = data.detail || data.message || `Registration error (status: ${response.status})`;
1303
+ showAuthMessage(errorMsg, 'error');
1304
+ }
1305
+ } catch (error) {
1306
+ console.error('Registration error:', error);
1307
+ showAuthMessage('Network error: ' + error.message, 'error');
1308
+ }
1309
+ }
1310
+
1311
+ function handleValidationError(data) {
1312
+ if (!data || !data.detail) {
1313
+ return 'Unknown validation error';
1314
+ }
1315
+
1316
+ const detail = data.detail;
1317
+
1318
+ // If this is an array of errors (FastAPI's standard 422 format)
1319
+ if (Array.isArray(detail)) {
1320
+ const messages = [];
1321
+
1322
+ detail.forEach(err => {
1323
+ let fieldName = 'unknown field';
1324
+ let errorMsg = err.msg || 'Error';
1325
+
1326
+ // Extract the field name from loc
1327
+ if (err.loc && err.loc.length > 1) {
1328
+ fieldName = err.loc[err.loc.length - 1];
1329
+
1330
+ // Convert field names into a readable form
1331
+ const fieldMap = {
1332
+ 'username': 'Username',
1333
+ 'password': 'Password',
1334
+ 'email': 'Email',
1335
+ 'phone': 'Phone',
1336
+ 'full_name': 'Full name',
1337
+ 'agree_terms': 'Agreement to the terms'
1338
+ };
1339
+
1340
+ fieldName = fieldMap[fieldName] || fieldName;
1341
+ }
1342
+
1343
+ // Convert error messages into a readable form
1344
+ const errorMap = {
1345
+ 'field required': 'required field',
1346
+ 'Invalid email format': 'invalid email format',
1347
+ 'Phone number must be at least 10 digits': 'the number must contain at least 10 digits',
1348
+ 'You must agree to the terms of use': 'you must agree to the terms'
1349
+ };
1350
+
1351
+ errorMsg = errorMap[errorMsg] || errorMsg;
1352
+
1353
+ messages.push(`${fieldName}: ${errorMsg}`);
1354
+ });
1355
+
1356
+ return messages.join('. ');
1357
+ }
1358
+
1359
+ // If this is a string
1360
+ if (typeof detail === 'string') {
1361
+ return detail;
1362
+ }
1363
+
1364
+ // If this is an object
1365
+ if (typeof detail === 'object') {
1366
+ const messages = [];
1367
+ for (const [field, msg] of Object.entries(detail)) {
1368
+ messages.push(`${field}: ${msg}`);
1369
+ }
1370
+ return messages.join('. ');
1371
+ }
1372
+
1373
+ return 'Data validation error';
1374
+ }
1375
+
1376
+
1377
+ async function logout() {
1378
+ // The server ends the session first: forgetting it only in this browser
1379
+ // would leave a copied token working.
1380
+ try {
1381
+ await fetch('/api/auth/logout', { method: 'POST' });
1382
+ } catch (error) {
1383
+ console.warn('Could not end the session on the server:', error);
1384
+ }
1385
+ localStorage.removeItem('authToken');
1386
+ localStorage.removeItem('auth_token');
1387
+ currentUser = null;
1388
+ updateUIAfterAuth();
1389
+ showAuthModal();
1390
+ hideVersionPanel();
1391
+ }
1392
+
1393
+ async function verifyToken() {
1394
+ try {
1395
+ const response = await fetch('/api/auth/verify', { method: 'GET' });
1396
+
1397
+ const data = await response.json();
1398
+
1399
+ if (data.success) {
1400
+ localStorage.setItem('authToken', SESSION_MARKER);
1401
+ currentUser = data.user;
1402
+ updateUIAfterAuth();
1403
+ return true;
1404
+ } else {
1405
+ localStorage.removeItem('authToken');
1406
+ currentUser = null;
1407
+ updateUIAfterAuth();
1408
+ return false;
1409
+ }
1410
+ } catch (error) {
1411
+ localStorage.removeItem('authToken');
1412
+ currentUser = null;
1413
+ updateUIAfterAuth();
1414
+ return false;
1415
+ }
1416
+ }
1417
+
1418
+ function updateUIAfterAuth() {
1419
+ const authBlock = document.getElementById('authBlock');
1420
+
1421
+ if (currentUser) {
1422
+ authBlock.classList.add('hidden');
1423
+
1424
+ document.getElementById('usernameDisplay').textContent = currentUser.username;
1425
+
1426
+ // Update the display of optional fields if present
1427
+ if (currentUser.email) {
1428
+ const emailElement = document.getElementById('userEmail');
1429
+ if (emailElement) {
1430
+ emailElement.textContent = currentUser.email;
1431
+ emailElement.parentElement.style.display = 'block';
1432
+ }
1433
+ }
1434
+
1435
+ if (currentUser.phone) {
1436
+ const phoneElement = document.getElementById('userPhone');
1437
+ if (phoneElement) {
1438
+ phoneElement.textContent = currentUser.phone;
1439
+ phoneElement.parentElement.style.display = 'block';
1440
+ }
1441
+ }
1442
+
1443
+ if (currentUser.full_name) {
1444
+ const fullNameElement = document.getElementById('userFullName');
1445
+ if (fullNameElement) {
1446
+ fullNameElement.textContent = currentUser.full_name;
1447
+ fullNameElement.parentElement.style.display = 'block';
1448
+ }
1449
+ }
1450
+
1451
+ const userStatus = document.getElementById('userStatus');
1452
+ userStatus.textContent = currentUser.status === 'active' ? 'Active' : 'Blocked';
1453
+ userStatus.className = `ml-2 status-badge ${currentUser.status === 'active' ? 'status-active' : 'status-blocked'}`;
1454
+
1455
+ const userRole = document.getElementById('userRole');
1456
+ userRole.textContent = currentUser.role === ROLE_ADMIN ? 'Admin' : 'Client';
1457
+ userRole.className = `ml-2 role-badge ${currentUser.role === ROLE_ADMIN ? 'role-admin' : 'role-client'}`;
1458
+
1459
+ document.getElementById('userInfo').style.display = 'block';
1460
+
1461
+ const adminItems = document.querySelectorAll('.admin-only');
1462
+ adminItems.forEach(item => {
1463
+ if (currentUser.role === ROLE_ADMIN) {
1464
+ item.classList.remove('hidden');
1465
+ } else {
1466
+ item.classList.add('hidden');
1467
+ }
1468
+ });
1469
+ updateVersionPanelVisibility();
1470
+ } else {
1471
+ authBlock.classList.remove('hidden');
1472
+ document.getElementById('userInfo').style.display = 'none';
1473
+ hideVersionPanel();
1474
+ }
1475
+ }
1476
+
1477
+ function resetRegistrationForm() {
1478
+ const form = document.getElementById('registerForm');
1479
+ if (form) {
1480
+ form.reset();
1481
+ }
1482
+ }
1483
+
1484
+ function showAuthMessage(text, type) {
1485
+ const messageDiv = document.getElementById('authMessage');
1486
+ messageDiv.textContent = text;
1487
+ messageDiv.className = 'mt-4 p-3 rounded-lg text-sm break-words';
1488
+
1489
+ if (type === 'success') {
1490
+ messageDiv.classList.add('bg-green-50', 'text-green-800', 'border', 'border-green-200');
1491
+ } else {
1492
+ messageDiv.classList.add('bg-red-50', 'text-red-800', 'border', 'border-red-200');
1493
+ }
1494
+
1495
+ messageDiv.classList.remove('hidden');
1496
+
1497
+ // Auto-hide after 10 seconds for errors, 5 for success
1498
+ const timeout = type === 'success' ? 5000 : 10000;
1499
+ setTimeout(() => {
1500
+ if (messageDiv.parentElement) {
1501
+ messageDiv.classList.add('hidden');
1502
+ }
1503
+ }, timeout);
1504
+ }
1505
+
1506
+ function findHeaderByText(headerRow, text) {
1507
+ const headers = headerRow.querySelectorAll('th');
1508
+ for (let header of headers) {
1509
+ if (header.textContent.trim() === text) {
1510
+ return header;
1511
+ }
1512
+ }
1513
+ return null;
1514
+ }
1515
+
1516
+ // Variable tracking the collapsed/expanded state
1517
+ let isGlobalDeductionExpanded = true;
1518
+
1519
+ // Initialize on load
1520
+ document.addEventListener('DOMContentLoaded', function() {
1521
+ feather.replace();
1522
+ });
1523
+
1524
+
1525
+ // Initialize the phone mask on load
1526
+ document.addEventListener('DOMContentLoaded', function() {
1527
+ const phoneInput = document.getElementById('registerPhone');
1528
+ if (phoneInput) {
1529
+
1530
+ phoneInput.addEventListener('keydown', function(e) {
1531
+ // Allow: backspace, delete, tab, escape, enter
1532
+ if ([46, 8, 9, 27, 13].indexOf(e.keyCode) !== -1 ||
1533
+ // Allow: Ctrl+A
1534
+ (e.keyCode === 65 && e.ctrlKey === true) ||
1535
+ // Allow: home, end, left, right
1536
+ (e.keyCode >= 35 && e.keyCode <= 39)) {
1537
+ return;
1538
+ }
1539
+
1540
+ // Block everything except digits
1541
+ if ((e.keyCode < 48 || e.keyCode > 57) && (e.keyCode < 96 || e.keyCode > 105)) {
1542
+ e.preventDefault();
1543
+ }
1544
+ });
1545
+ }
1546
+ });
1547
+
1548
+ // Pagination handlers
1549
+ const prevPageBtn = document.getElementById('prevPage');
1550
+ const nextPageBtn = document.getElementById('nextPage');
1551
+
1552
+ if (prevPageBtn) {
1553
+ prevPageBtn.addEventListener('click', () => {
1554
+ if (currentPage > 1) {
1555
+ currentPage--;
1556
+ displayProducts(filteredProducts);
1557
+
1558
+ // Add a small animation
1559
+ prevPageBtn.classList.add('transform', 'scale-95');
1560
+ setTimeout(() => {
1561
+ prevPageBtn.classList.remove('transform', 'scale-95');
1562
+ }, 150);
1563
+ }
1564
+ });
1565
+ }
1566
+
1567
+ if (nextPageBtn) {
1568
+ nextPageBtn.addEventListener('click', () => {
1569
+ const totalPages = Math.ceil(filteredProducts.length / itemsPerPage);
1570
+ if (currentPage < totalPages) {
1571
+ currentPage++;
1572
+ displayProducts(filteredProducts);
1573
+
1574
+ // Add a small animation
1575
+ nextPageBtn.classList.add('transform', 'scale-95');
1576
+ setTimeout(() => {
1577
+ nextPageBtn.classList.remove('transform', 'scale-95');
1578
+ }, 150);
1579
+ }
1580
+ });
1581
+ }
1582
+
1583
+ // Helper function for showing notifications
1584
+ function showNotification(message, type = 'info') {
1585
+ const notification = document.createElement('div');
1586
+ notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${type === 'success' ? 'bg-green-100 text-green-800 border border-green-200' :
1587
+ type === 'error' ? 'bg-red-100 text-red-800 border border-red-200' :
1588
+ 'bg-blue-100 text-blue-800 border border-blue-200'
1589
+ }`;
1590
+ notification.innerHTML = `
1591
+ <div class="flex items-center">
1592
+ <i data-feather="${type === 'success' ? 'check-circle' : type === 'error' ? 'alert-circle' : 'info'}"
1593
+ class="w-5 h-5 mr-2"></i>
1594
+ <span>${message}</span>
1595
+ <button onclick="this.parentElement.parentElement.remove()"
1596
+ class="ml-4 text-gray-500 hover:text-gray-700">
1597
+ <i data-feather="x" class="w-4 h-4"></i>
1598
+ </button>
1599
+ </div>
1600
+ `;
1601
+ document.body.appendChild(notification);
1602
+
1603
+ // Refresh feather icons
1604
+ feather.replace();
1605
+
1606
+ // Auto-hide after 5 seconds
1607
+ setTimeout(() => {
1608
+ if (notification.parentElement) {
1609
+ notification.remove();
1610
+ }
1611
+ }, 5000);
1612
+ }
1613
+
1614
+ // The showNotification() notification style is the only thing the shell
1615
+ // declares here. The button rules of one application's section that used to
1616
+ // stand nearby left together with the code that set them: a section carries
1617
+ // its own styles (keepup-27).
1618
+ const additionalStyles = `
1619
+ .notification {
1620
+ transition: all 0.3s ease;
1621
+ }
1622
+ `;
1623
+
1624
+ // Add the styles to the document
1625
+ const styleSheet = document.createElement('style');
1626
+ styleSheet.textContent = additionalStyles;
1627
+ document.head.appendChild(styleSheet);
1628
+
1629
+
1630
+ document.addEventListener('DOMContentLoaded', function() {
1631
+ initializeApp();
1632
+ checkAuth();
1633
+ });
1634
+
1635
+
1636
+ // Handler for messages from the payment window
1637
+ window.addEventListener('message', function(event) {
1638
+ if (event.data.type === 'payment_success') {
1639
+ showNotification('Payment successful! Plan activated.', 'success');
1640
+ // Reload the plans data
1641
+ setTimeout(() => {
1642
+ loadTariffsData();
1643
+ }, 1000);
1644
+ }
1645
+ });
1646
+
1647
+ /**
1648
+ * Event system for bulk markup application
1649
+ */
1650
+ const markupEventSystem = {
1651
+ listeners: new Map(),
1652
+ addListener(shopType, callback) {
1653
+ if (!this.listeners.has(shopType)) {
1654
+ this.listeners.set(shopType, []);
1655
+ }
1656
+ this.listeners.get(shopType).push(callback);
1657
+ },
1658
+ removeListener(shopType, callback) {
1659
+ if (this.listeners.has(shopType)) {
1660
+ const listeners = this.listeners.get(shopType);
1661
+ const index = listeners.indexOf(callback);
1662
+ if (index > -1) {
1663
+ listeners.splice(index, 1);
1664
+ }
1665
+ }
1666
+ },
1667
+ async dispatchEvent(shopType, eventData) {
1668
+ if (this.listeners.has(shopType)) {
1669
+ const listeners = this.listeners.get(shopType);
1670
+ const results = [];
1671
+
1672
+ for (const listener of listeners) {
1673
+ try {
1674
+ const result = await listener(eventData);
1675
+ results.push(result);
1676
+ } catch (error) {
1677
+ console.error(`Error in ${shopType} markup listener:`, error);
1678
+ results.push({ success: false, error: error.message });
1679
+ }
1680
+ }
1681
+
1682
+ return results;
1683
+ }
1684
+ return [];
1685
+ },
1686
+ getRegisteredShopTypes() {
1687
+ return Array.from(this.listeners.keys());
1688
+ }
1689
+ };
1690
+
1691
+ // Make it globally accessible for modules
1692
+ window.markupEventSystem = markupEventSystem;
1693
+
1694
+ // Periodic payment status check while the tariffs section is open
1695
+ function startPaymentStatusPolling() {
1696
+ setInterval(async () => {
1697
+ const tariffsSection = document.getElementById('tariffs-section');
1698
+ if (tariffsSection && tariffsSection.classList.contains('active')) {
1699
+ // Logic for checking pending payments could be added here
1700
+ }
1701
+ }, 30000);
1702
+ }
1703
+
1704
+ window.tableEvents = {
1705
+ listeners: [],
1706
+
1707
+ addListener(callback) {
1708
+ this.listeners.push(callback);
1709
+ },
1710
+
1711
+ notifyTableRendered(articles) {
1712
+ this.listeners.forEach(listener => {
1713
+ try {
1714
+ listener(articles);
1715
+ } catch (error) {
1716
+ console.error('Error in table event listener:', error);
1717
+ }
1718
+ });
1719
+ }
1720
+ };
1721
+
1722
+ // region application version handling
1723
+
1724
+ // Function for loading version information
1725
+ async function loadVersionInfo() {
1726
+ try {
1727
+ const token = localStorage.getItem('authToken');
1728
+ const response = await fetch('/api/version', {
1729
+ headers: {
1730
+ 'Authorization': `Bearer ${token}`
1731
+ }
1732
+ });
1733
+
1734
+ if (response.ok) {
1735
+ const versionData = await response.json();
1736
+ return versionData;
1737
+ }
1738
+ return null;
1739
+ } catch (error) {
1740
+ console.error('Failed to load version information:', error);
1741
+ return null;
1742
+ }
1743
+ }
1744
+
1745
+ // Function for displaying the version panel
1746
+ async function showVersionPanel() {
1747
+ const versionPanel = document.getElementById('versionPanel');
1748
+ if (!versionPanel) return;
1749
+
1750
+ // Check the user's role
1751
+ if (currentUser && currentUser.role === ROLE_ADMIN) {
1752
+ const versionData = await loadVersionInfo();
1753
+ if (versionData) {
1754
+ // Fill in the data
1755
+ document.getElementById('versionProject').textContent = versionData.project || '-';
1756
+ document.getElementById('versionRelease').textContent = versionData.version || '-';
1757
+ document.getElementById('versionBuildNumber').textContent = versionData.build_number || '-';
1758
+ document.getElementById('versionBuildDate').textContent = versionData.build_date || '-';
1759
+
1760
+ // Show the panel
1761
+ versionPanel.classList.remove('hidden');
1762
+
1763
+ // Refresh Feather icons
1764
+ feather.replace();
1765
+ }
1766
+ }
1767
+ }
1768
+
1769
+ // Function for hiding the version panel
1770
+ function hideVersionPanel() {
1771
+ const versionPanel = document.getElementById('versionPanel');
1772
+ if (versionPanel) {
1773
+ versionPanel.classList.add('hidden');
1774
+ }
1775
+ }
1776
+
1777
+ // Function for checking and updating the version panel's visibility
1778
+ function updateVersionPanelVisibility() {
1779
+ const versionPanel = document.getElementById('versionPanel');
1780
+ if (!versionPanel) return;
1781
+
1782
+ if (currentUser && currentUser.role === ROLE_ADMIN) {
1783
+ showVersionPanel();
1784
+ } else {
1785
+ hideVersionPanel();
1786
+ }
1787
+ }
1788
+
1789
+ // endregion
1790
+
1791
+ // Function for opening the terms-of-use modal
1792
+ function openTermsModal() {
1793
+ const modal = document.getElementById('termsModal');
1794
+ applyPublicConfig();
1795
+ modal.classList.remove('hidden');
1796
+ modal.classList.add('active');
1797
+ document.body.style.overflow = 'hidden';
1798
+
1799
+ // Initialize feather icons
1800
+ if (typeof feather !== 'undefined') {
1801
+ feather.replace();
1802
+ }
1803
+ }
1804
+
1805
+ // Function for closing the terms-of-use modal
1806
+ function closeTermsModal() {
1807
+ const modal = document.getElementById('termsModal');
1808
+ modal.classList.remove('active');
1809
+
1810
+ // Small delay before hiding, for a smooth animation
1811
+ setTimeout(() => {
1812
+ modal.classList.add('hidden');
1813
+ document.body.style.overflow = '';
1814
+ }, 300);
1815
+ }
1816
+
1817
+ // Close on click outside the content
1818
+ document.addEventListener('DOMContentLoaded', function() {
1819
+ const modal = document.getElementById('termsModal');
1820
+ if (modal) {
1821
+ modal.addEventListener('click', function(e) {
1822
+ if (e.target === this) {
1823
+ closeTermsModal();
1824
+ }
1825
+ });
1826
+ }
1827
+
1828
+ // Close on Escape
1829
+ document.addEventListener('keydown', function(e) {
1830
+ if (e.key === 'Escape') {
1831
+ const modal = document.getElementById('termsModal');
1832
+ if (modal && !modal.classList.contains('hidden')) {
1833
+ closeTermsModal();
1834
+ }
1835
+ }
1836
+ });
1837
+ });
1838
+
1839
+ /**
1840
+ * The "forgot password" link leads to the bot: the reset is issued by it,
1841
+ * not this page (task 272). The bot's name is known to the server; without
1842
+ * a response the link stays plain text.
1843
+ */
1844
+ function applyForgotPasswordLink() {
1845
+ const link = document.getElementById('forgotPasswordLink');
1846
+ if (!link) return;
1847
+ loadPublicConfig().then(config => {
1848
+ // The whole address comes from the server: building it here would mean
1849
+ // hardcoding someone else's domain into a panel that loads nothing of
1850
+ // its own. Where it comes from is the application's business: for one
1851
+ // it's a Telegram bot, for another its own page, for a third there's
1852
+ // no reset at all, and then the link stays plain text. Before task
1853
+ // keepup-27 the shell asked for the address directly at the bot's
1854
+ // route, meaning the framework knew about the bot (keepup-27).
1855
+ const url = config && config.password_reset_url;
1856
+ if (!url) return;
1857
+ link.href = url;
1858
+ link.target = '_blank';
1859
+ link.rel = 'noopener noreferrer';
1860
+ }).catch(() => { /* without an address the sign-in page works as before */ });
1861
+ }