underpost 2.8.872 → 2.8.873

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 (56) hide show
  1. package/.env.development +2 -1
  2. package/.env.production +2 -1
  3. package/.env.test +2 -1
  4. package/.github/workflows/ghpkg.ci.yml +1 -1
  5. package/.github/workflows/npmpkg.ci.yml +1 -1
  6. package/.github/workflows/pwa-microservices-template-page.cd.yml +1 -1
  7. package/.github/workflows/pwa-microservices-template-test.ci.yml +1 -1
  8. package/.github/workflows/release.cd.yml +2 -4
  9. package/README.md +22 -2
  10. package/bin/build.js +4 -0
  11. package/bin/deploy.js +4 -0
  12. package/cli.md +3 -2
  13. package/manifests/deployment/dd-default-development/deployment.yaml +2 -2
  14. package/manifests/deployment/dd-test-development/deployment.yaml +138 -0
  15. package/manifests/deployment/dd-test-development/proxy.yaml +26 -0
  16. package/package.json +5 -1
  17. package/src/api/core/core.router.js +2 -1
  18. package/src/api/default/default.controller.js +6 -1
  19. package/src/api/default/default.router.js +6 -2
  20. package/src/api/default/default.service.js +10 -1
  21. package/src/api/file/file.router.js +2 -1
  22. package/src/api/test/test.router.js +1 -1
  23. package/src/api/user/postman_collection.json +216 -0
  24. package/src/api/user/user.controller.js +25 -60
  25. package/src/api/user/user.model.js +29 -7
  26. package/src/api/user/user.router.js +6 -3
  27. package/src/api/user/user.service.js +80 -32
  28. package/src/cli/baremetal.js +33 -3
  29. package/src/cli/cloud-init.js +11 -0
  30. package/src/cli/deploy.js +5 -2
  31. package/src/cli/index.js +1 -0
  32. package/src/cli/lxd.js +7 -0
  33. package/src/cli/run.js +17 -5
  34. package/src/cli/ssh.js +20 -6
  35. package/src/client/components/core/AgGrid.js +28 -6
  36. package/src/client/components/core/Auth.js +98 -55
  37. package/src/client/components/core/LogIn.js +16 -23
  38. package/src/client/components/core/LogOut.js +5 -1
  39. package/src/client/components/core/Pagination.js +202 -9
  40. package/src/client/components/core/Router.js +30 -3
  41. package/src/client/components/core/SignUp.js +1 -2
  42. package/src/client/components/default/LogInDefault.js +0 -6
  43. package/src/client/components/default/LogOutDefault.js +0 -16
  44. package/src/client/services/core/core.service.js +5 -1
  45. package/src/client/services/default/default.management.js +115 -18
  46. package/src/client/services/default/default.service.js +9 -4
  47. package/src/client/services/user/user.management.js +6 -0
  48. package/src/client/services/user/user.service.js +11 -4
  49. package/src/index.js +24 -2
  50. package/src/runtime/lampp/Lampp.js +89 -2
  51. package/src/runtime/xampp/Xampp.js +48 -1
  52. package/src/server/auth.js +518 -155
  53. package/src/server/conf.js +19 -1
  54. package/src/server/runtime.js +62 -228
  55. package/src/server/ssr.js +85 -0
  56. package/src/server/valkey.js +2 -1
@@ -24,8 +24,9 @@ const LogIn = {
24
24
  Event: {},
25
25
  Trigger: async function (options) {
26
26
  const { user } = options;
27
- await Webhook.register({ user });
28
27
  for (const eventKey of Object.keys(this.Event)) await this.Event[eventKey](options);
28
+ if (!user || user.role === 'guest') return;
29
+ await Webhook.register({ user });
29
30
  if (s(`.session`))
30
31
  htmls(
31
32
  `.session`,
@@ -72,19 +73,18 @@ const LogIn = {
72
73
  imageSrc,
73
74
  };
74
75
  }
76
+ htmls(
77
+ `.action-btn-profile-log-in-render`,
78
+ html`<div class="abs center top-box-profile-img-container">
79
+ <img
80
+ class="abs center top-box-profile-img"
81
+ ${this.Scope.user.main.model.user.profileImage
82
+ ? `src="${this.Scope.user.main.model.user.profileImage.imageSrc}"`
83
+ : ``}
84
+ />
85
+ </div>`,
86
+ );
75
87
  }
76
-
77
- htmls(
78
- `.action-btn-profile-log-in-render`,
79
- html`<div class="abs center top-box-profile-img-container">
80
- <img
81
- class="abs center top-box-profile-img"
82
- ${this.Scope.user.main.model.user.profileImage
83
- ? `src="${this.Scope.user.main.model.user.profileImage.imageSrc}"`
84
- : ``}
85
- />
86
- </div>`,
87
- );
88
88
  },
89
89
  Render: async function () {
90
90
  setTimeout(async () => {
@@ -103,13 +103,7 @@ const LogIn = {
103
103
  if ('model' in inputData) body[inputData.model] = s(`.${inputData.id}`).value;
104
104
  }
105
105
  const result = await UserService.post({ id: 'auth', body });
106
- if (result.status === 'success') {
107
- await Auth.sessionIn(result);
108
- setTimeout(() => {
109
- if (s(`.modal-log-in`)) s(`.btn-close-modal-log-in`).click();
110
- if (s(`.modal-sign-up`)) s(`.btn-close-modal-sign-up`).click();
111
- });
112
- }
106
+
113
107
  if (result.status === 'error' && result.message.match('attempts')) {
114
108
  htmls(`.login-attempt-warn-value`, result.message.split(':')[1]);
115
109
  s(`.login-attempt-warn-container`).classList.remove('hide');
@@ -119,6 +113,8 @@ const LogIn = {
119
113
  htmls(`.login-attempt-warn-value0`, result.message.split(':')[1]);
120
114
  s(`.login-attempt-warn-container0`).classList.remove('hide');
121
115
  } else s(`.login-attempt-warn-container0`).classList.add('hide');
116
+
117
+ if (result.status === 'success') await Auth.sessionIn(result);
122
118
  NotificationManager.Push({
123
119
  html: result.status === 'success' ? Translate.Render(`${result.status}-user-log-in`) : result.message,
124
120
  status: result.status,
@@ -189,9 +185,6 @@ const LogIn = {
189
185
  </form>
190
186
  `;
191
187
  },
192
- cleanMainUser: () => {
193
- LogIn.Scope.user.main.model.user = {};
194
- },
195
188
  };
196
189
 
197
190
  export { LogIn };
@@ -4,11 +4,11 @@ import { LogIn } from './LogIn.js';
4
4
  import { Translate } from './Translate.js';
5
5
  import { htmls, s } from './VanillaJs.js';
6
6
  import { Webhook } from './Webhook.js';
7
+ import { NotificationManager } from './NotificationManager.js';
7
8
 
8
9
  const LogOut = {
9
10
  Event: {},
10
11
  Trigger: async function (options) {
11
- LogIn.cleanMainUser();
12
12
  await Webhook.unregister();
13
13
  for (const eventKey of Object.keys(this.Event)) await this.Event[eventKey](options);
14
14
  if (s(`.session`))
@@ -41,6 +41,10 @@ const LogOut = {
41
41
  s('.btn-log-out').onclick = async (e) => {
42
42
  e.preventDefault();
43
43
  await Auth.sessionOut();
44
+ NotificationManager.Push({
45
+ html: Translate.Render(`success-logout`),
46
+ status: 'success',
47
+ });
44
48
  };
45
49
  });
46
50
  // Translate.Render('confirm-logout')
@@ -1,14 +1,207 @@
1
- const Pagination = {
2
- Render: async ({ id }) => {
3
- return html`
1
+ import { getQueryParams, setQueryParams } from './Router.js';
2
+
3
+ class AgPagination extends HTMLElement {
4
+ constructor() {
5
+ super();
6
+ this.attachShadow({ mode: 'open' });
7
+ this._gridId = null;
8
+ const queryParams = getQueryParams();
9
+ this._currentPage = parseInt(queryParams.page, 10) || 1;
10
+ this._limit = parseInt(queryParams.limit, 10) || 10;
11
+ this._totalPages = 1;
12
+ this._totalItems = 0;
13
+ this.handlePageChange = this.handlePageChange.bind(this);
14
+ this.handleLimitChange = this.handleLimitChange.bind(this);
15
+ }
16
+
17
+ static get observedAttributes() {
18
+ return ['grid-id', 'current-page', 'total-pages', 'total-items', 'limit'];
19
+ }
20
+
21
+ attributeChangedCallback(name, oldValue, newValue) {
22
+ switch (name) {
23
+ case 'grid-id':
24
+ this._gridId = newValue;
25
+ break;
26
+ case 'current-page':
27
+ this._currentPage = parseInt(newValue, 10) || this._currentPage;
28
+ break;
29
+ case 'total-pages':
30
+ this._totalPages = parseInt(newValue, 10) || 1;
31
+ break;
32
+ case 'total-items':
33
+ this._totalItems = parseInt(newValue, 10) || 0;
34
+ break;
35
+ case 'limit':
36
+ this._limit = parseInt(newValue, 10) || this._limit;
37
+ break;
38
+ }
39
+ this.update();
40
+ }
41
+
42
+ connectedCallback() {
43
+ this.render();
44
+ this.addEventListeners();
45
+ this.update();
46
+ }
47
+
48
+ disconnectedCallback() {
49
+ // Event listeners on shadow DOM are garbage collected with the component
50
+ }
51
+
52
+ handlePageChange(newPage) {
53
+ if (newPage < 1 || newPage > this._totalPages || newPage === this._currentPage) {
54
+ return;
55
+ }
56
+ this._currentPage = newPage;
57
+ setQueryParams({ page: newPage, limit: this._limit });
58
+ this.dispatchEvent(new CustomEvent('page-change', { detail: { page: newPage } }));
59
+ }
60
+
61
+ handleLimitChange(event) {
62
+ const newLimit = parseInt(event.target.value, 10);
63
+ if (newLimit === this._limit) {
64
+ return;
65
+ }
66
+ this._limit = newLimit;
67
+ this._currentPage = 1; // Reset to first page on limit change
68
+ setQueryParams({ page: 1, limit: newLimit });
69
+ this.dispatchEvent(new CustomEvent('limit-change', { detail: { limit: newLimit } }));
70
+ }
71
+
72
+ update() {
73
+ if (!this.shadowRoot.querySelector('#page-info')) return;
74
+
75
+ const isFirstPage = this._currentPage === 1;
76
+ const isLastPage = this._currentPage === this._totalPages;
77
+
78
+ this.shadowRoot.querySelector('#first-page').disabled = isFirstPage;
79
+ this.shadowRoot.querySelector('#prev-page').disabled = isFirstPage;
80
+ this.shadowRoot.querySelector('#next-page').disabled = isLastPage;
81
+ this.shadowRoot.querySelector('#last-page').disabled = isLastPage;
82
+
83
+ const startItem = this._totalItems > 0 ? (this._currentPage - 1) * this._limit + 1 : 0;
84
+ const endItem = Math.min(this._currentPage * this._limit, this._totalItems);
85
+
86
+ this.shadowRoot.querySelector('#summary-info').textContent = `${startItem} - ${endItem} of ${this._totalItems}`;
87
+ this.shadowRoot.querySelector('#page-info').textContent = `Page ${this._currentPage} of ${this._totalPages}`;
88
+
89
+ const limitSelector = this.shadowRoot.querySelector('#limit-selector');
90
+ if (limitSelector.value != this._limit) {
91
+ limitSelector.value = this._limit;
92
+ }
93
+
94
+ this.renderPageButtons();
95
+ }
96
+
97
+ renderPageButtons() {
98
+ const pageButtonsContainer = this.shadowRoot.querySelector('#page-buttons');
99
+ pageButtonsContainer.innerHTML = '';
100
+
101
+ const maxButtons = 5;
102
+ let startPage = Math.max(1, this._currentPage - Math.floor(maxButtons / 2));
103
+ let endPage = Math.min(this._totalPages, startPage + maxButtons - 1);
104
+
105
+ if (endPage - startPage + 1 < maxButtons) {
106
+ startPage = Math.max(1, endPage - maxButtons + 1);
107
+ }
108
+
109
+ for (let i = startPage; i <= endPage; i++) {
110
+ const button = document.createElement('button');
111
+ button.textContent = i;
112
+ button.disabled = i === this._currentPage;
113
+ if (i === this._currentPage) {
114
+ button.classList.add('active');
115
+ }
116
+ button.addEventListener('click', () => this.handlePageChange(i));
117
+ pageButtonsContainer.appendChild(button);
118
+ }
119
+ }
120
+
121
+ addEventListeners() {
122
+ this.shadowRoot.querySelector('#first-page').addEventListener('click', () => this.handlePageChange(1));
123
+ this.shadowRoot
124
+ .querySelector('#prev-page')
125
+ .addEventListener('click', () => this.handlePageChange(this._currentPage - 1));
126
+ this.shadowRoot
127
+ .querySelector('#next-page')
128
+ .addEventListener('click', () => this.handlePageChange(this._currentPage + 1));
129
+ this.shadowRoot
130
+ .querySelector('#last-page')
131
+ .addEventListener('click', () => this.handlePageChange(this._totalPages));
132
+ this.shadowRoot.querySelector('#limit-selector').addEventListener('change', this.handleLimitChange);
133
+ }
134
+
135
+ render() {
136
+ this.shadowRoot.innerHTML = html`
4
137
  <style>
5
- .pagination-container-${id} {
138
+ :host {
139
+ display: flex;
140
+ align-items: center;
141
+ justify-content: center;
142
+ padding: 8px;
143
+ font-family: sans-serif;
144
+ font-size: 14px;
145
+ gap: 8px;
146
+ }
147
+ button {
148
+ border: 1px solid #ccc;
149
+ background-color: #f0f0f0;
150
+ padding: 6px 12px;
151
+ cursor: pointer;
152
+ border-radius: 4px;
153
+ }
154
+ button:disabled {
155
+ cursor: not-allowed;
156
+ opacity: 0.5;
157
+ }
158
+ button.active {
159
+ border-color: #007bff;
160
+ background-color: #007bff;
161
+ color: white;
162
+ }
163
+ #page-info {
164
+ min-width: 80px;
165
+ text-align: center;
166
+ }
167
+ #page-buttons {
168
+ display: flex;
169
+ gap: 4px;
170
+ }
171
+ .summary-panel,
172
+ .page-summary-panel {
173
+ display: flex;
174
+ align-items: center;
175
+ gap: 8px;
176
+ }
177
+ #limit-selector {
178
+ border: 1px solid #ccc;
179
+ background-color: #f0f0f0;
180
+ padding: 6px 12px;
181
+ border-radius: 4px;
6
182
  }
7
183
  </style>
8
-
9
- <div class="in pagination-container-${id}">test pagination</div>
184
+ <div class="summary-panel">
185
+ <span id="summary-info"></span>
186
+ </div>
187
+ <button id="first-page">First</button>
188
+ <button id="prev-page">Previous</button>
189
+ <div class="page-summary-panel">
190
+ <div id="page-buttons"></div>
191
+ <span id="page-info"></span>
192
+ </div>
193
+ <button id="next-page">Next</button>
194
+ <button id="last-page">Last</button>
195
+ <select id="limit-selector">
196
+ <option value="10">10</option>
197
+ <option value="20">20</option>
198
+ <option value="50">50</option>
199
+ <option value="100">100</option>
200
+ </select>
10
201
  `;
11
- },
12
- };
202
+ }
203
+ }
204
+
205
+ customElements.define('ag-pagination', AgPagination);
13
206
 
14
- export { Pagination };
207
+ export { AgPagination };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Vanilla JavaScript module for manipulating the DOM.
2
+ * Router module for handling routing in a PWA application.
3
3
  * @module src/client/components/core/Router.js
4
4
  * @namespace PwaRouter
5
5
  */
@@ -245,7 +245,8 @@ const closeModalRouteChangeEvent = (options = {}) => {
245
245
 
246
246
  for (const event of Object.keys(closeModalRouteChangeEvents)) closeModalRouteChangeEvents[event]();
247
247
  if (topModalId) Modal.setTopModalCallback(topModalId);
248
- setPath(`${getProxyPath()}${Modal.Data[topModalId]?.options?.route || 'home'}`);
248
+ setPath(`${getProxyPath()}${Modal.Data[topModalId]?.options?.route ?? ''}`);
249
+ setDocTitle(Modal.Data[topModalId]?.options?.route ?? '');
249
250
  };
250
251
 
251
252
  /**
@@ -255,7 +256,7 @@ const closeModalRouteChangeEvent = (options = {}) => {
255
256
  * @param {string} options.route - The route associated with the modal view.
256
257
  * @memberof PwaRouter
257
258
  */
258
- const handleModalViewRoute = (options = { route: 'home' }) => {
259
+ const handleModalViewRoute = (options = { route: '' }) => {
259
260
  const { route } = options;
260
261
  if (!route) return;
261
262
 
@@ -270,6 +271,31 @@ const handleModalViewRoute = (options = { route: 'home' }) => {
270
271
  }
271
272
  };
272
273
 
274
+ /**
275
+ * Sets or updates query parameters in the URL.
276
+ * It preserves the existing path, hash, and other query parameters.
277
+ *
278
+ * @param {Object.<string, string|number>} newParams - An object of query parameters to set or update.
279
+ * If a value is `null` or `undefined`, the parameter will be removed.
280
+ * @param {object} [options={ replace: true }] - Options for history manipulation.
281
+ * @param {boolean} [options.replace=true] - If true, uses `history.replaceState` instead of `history.pushState`.
282
+ * @memberof PwaRouter
283
+ */
284
+ const setQueryParams = (newParams, options = { replace: true }) => {
285
+ const url = new URL(window.location.href);
286
+ Object.entries(newParams).forEach(([key, value]) => {
287
+ if (value === null || value === undefined) {
288
+ url.searchParams.delete(key);
289
+ } else {
290
+ url.searchParams.set(key, value);
291
+ }
292
+ });
293
+
294
+ const newPath = url.pathname + url.search + url.hash;
295
+
296
+ history.pushState(history.state, '', newPath);
297
+ };
298
+
273
299
  export {
274
300
  RouterEvents,
275
301
  closeModalRouteChangeEvents,
@@ -284,4 +310,5 @@ export {
284
310
  getQueryParams,
285
311
  getProxyPath,
286
312
  setPath,
313
+ setQueryParams,
287
314
  };
@@ -53,8 +53,7 @@ const SignUp = {
53
53
  status: result.status,
54
54
  });
55
55
  if (result.status === 'success') {
56
- await Auth.sessionOut();
57
- await Auth.signUpToken(result);
56
+ await Auth.sessionIn(result);
58
57
  s(`.btn-close-${options.idModal}`).click();
59
58
  }
60
59
  });
@@ -1,17 +1,11 @@
1
- import { UserService } from '../../services/user/user.service.js';
2
1
  import { Auth } from '../core/Auth.js';
3
2
  import { LogIn } from '../core/LogIn.js';
4
- import { s } from '../core/VanillaJs.js';
5
3
  import { ElementsDefault } from './ElementsDefault.js';
6
4
 
7
5
  const LogInDefault = async function () {
8
6
  LogIn.Event['LogInDefault'] = async (options) => {
9
7
  const { token, user } = options;
10
8
  ElementsDefault.Data.user.main.model.user = user;
11
- s(`.main-btn-log-in`).style.display = 'none';
12
- s(`.main-btn-sign-up`).style.display = 'none';
13
- s(`.main-btn-log-out`).style.display = null;
14
- s(`.main-btn-account`).style.display = null;
15
9
  };
16
10
  const { user } = await Auth.sessionIn();
17
11
  ElementsDefault.Data.user.main.model.user = user;
@@ -1,25 +1,9 @@
1
- import { Auth } from '../core/Auth.js';
2
1
  import { LogOut } from '../core/LogOut.js';
3
- import { NotificationManager } from '../core/NotificationManager.js';
4
- import { Translate } from '../core/Translate.js';
5
- import { s } from '../core/VanillaJs.js';
6
2
  import { ElementsDefault } from './ElementsDefault.js';
7
3
 
8
4
  const LogOutDefault = async function () {
9
5
  LogOut.Event['LogOutDefault'] = async (result = { user: { _id: '' } }) => {
10
6
  ElementsDefault.Data.user.main.model.user = result.user;
11
-
12
- s(`.main-btn-log-out`).style.display = 'none';
13
- s(`.main-btn-account`).style.display = 'none';
14
- s(`.main-btn-log-in`).style.display = null;
15
- s(`.main-btn-sign-up`).style.display = null;
16
- if (s(`.modal-log-out`)) s(`.btn-close-modal-log-out`).click();
17
- if (s(`.modal-account`)) s(`.btn-close-modal-account`).click();
18
-
19
- NotificationManager.Push({
20
- html: Translate.Render(`success-logout`),
21
- status: 'success',
22
- });
23
7
  };
24
8
  };
25
9
 
@@ -33,7 +33,11 @@ const getWsBaseUrl = (options = { id: '', endpoint: '', wsBasePath: '' }) =>
33
33
  }${options?.endpoint ? options.endpoint : ''}${options?.id ? `/${options.id}` : ''}`;
34
34
 
35
35
  const headersFactory = (headerId = '') => {
36
- const headers = { Authorization: Auth.getJWT() }; // , mode: 'no-cors'
36
+ const headers = {
37
+ Authorization: Auth.getJWT(),
38
+ withCredentials: true,
39
+ credentials: 'include', // no cors: 'same-origin'
40
+ };
37
41
  switch (headerId) {
38
42
  case 'file':
39
43
  return headers;
@@ -7,6 +7,7 @@ import { loggerFactory } from '../../components/core/Logger.js';
7
7
  import { Modal } from '../../components/core/Modal.js';
8
8
  import { NotificationManager } from '../../components/core/NotificationManager.js';
9
9
  import { Translate } from '../../components/core/Translate.js';
10
+ import { getQueryParams, RouterEvents, setQueryParams } from '../../components/core/Router.js';
10
11
  import { s } from '../../components/core/VanillaJs.js';
11
12
  import { DefaultService } from './default.service.js';
12
13
 
@@ -47,19 +48,48 @@ const columnDefFormatter = (obj, columnDefs, customFormat) => {
47
48
 
48
49
  const DefaultManagement = {
49
50
  Tokens: {},
51
+ loadTable: async function (id, options = { reload: true }) {
52
+ const { serviceId, columnDefs, customFormat } = this.Tokens[id];
53
+ const result = await this.Tokens[id].ServiceProvider.get({
54
+ page: this.Tokens[id].page,
55
+ limit: this.Tokens[id].limit,
56
+ id: this.Tokens[id].serviceOptions?.get?.id ?? undefined,
57
+ });
58
+ if (result.status === 'success') {
59
+ const { data, total, page, totalPages } = result.data;
60
+ this.Tokens[id].total = total;
61
+ this.Tokens[id].page = page;
62
+ this.Tokens[id].totalPages = totalPages;
63
+ const rowDataScope = data.map((row) => columnDefFormatter(row, columnDefs, customFormat));
64
+ if (options.reload) AgGrid.grids[this.Tokens[id].gridId].setGridOption('rowData', rowDataScope);
65
+ const paginationComp = s(`#ag-pagination-${this.Tokens[id].gridId}`);
66
+ paginationComp.setAttribute('current-page', this.Tokens[id].page);
67
+ paginationComp.setAttribute('total-pages', this.Tokens[id].totalPages);
68
+ paginationComp.setAttribute('total-items', this.Tokens[id].total);
69
+ }
70
+ },
50
71
  RenderTable: async function (options = DefaultOptions) {
51
72
  if (!options) options = DefaultOptions;
52
73
  const { serviceId, columnDefs, entity, defaultColKeyFocus, ServiceProvider, permissions } = options;
53
74
  logger.info('DefaultManagement RenderTable', options);
54
75
  const id = options?.idModal ? options.idModal : getId(this.Tokens, `${serviceId}-`);
55
76
  const gridId = `${serviceId}-grid-${id}`;
56
- this.Tokens[id] = { gridId };
77
+ const queryParams = getQueryParams();
78
+ const page = parseInt(queryParams.page) || 1;
79
+ const limit = parseInt(queryParams.limit) || 10;
80
+ this.Tokens[id] = {
81
+ ...options,
82
+ gridId,
83
+ page,
84
+ limit,
85
+ total: 0,
86
+ totalPages: 1,
87
+ };
57
88
 
89
+ setQueryParams({ page, limit });
58
90
  setTimeout(async () => {
59
91
  // https://www.ag-grid.com/javascript-data-grid/data-update-transactions/
60
92
 
61
- let rowDataScope = [];
62
-
63
93
  class RemoveActionGridRenderer {
64
94
  eGui;
65
95
  tokens;
@@ -110,6 +140,16 @@ const DefaultManagement = {
110
140
  });
111
141
  if (result.status === 'success') {
112
142
  AgGrid.grids[gridId].applyTransaction({ remove: [params.data] });
143
+ const token = DefaultManagement.Tokens[id];
144
+ // if we are on the last page and we delete the last item, go to the previous page
145
+ const newTotal = token.total - 1;
146
+ const newTotalPages = Math.ceil(newTotal / token.limit);
147
+ if (token.page > newTotalPages && newTotalPages > 0) {
148
+ token.page = newTotalPages;
149
+ }
150
+
151
+ // reload the current page
152
+ await DefaultManagement.loadTable(id, { reload: false });
113
153
  }
114
154
  },
115
155
  { context: 'modal' },
@@ -142,13 +182,14 @@ const DefaultManagement = {
142
182
  : [],
143
183
  ),
144
184
  );
145
- {
146
- const result = await ServiceProvider.get();
147
- if (result.status === 'success') {
148
- rowDataScope = result.data.map((row) => columnDefFormatter(row, columnDefs, options.customFormat));
149
- AgGrid.grids[gridId].setGridOption('rowData', rowDataScope);
150
- }
151
- }
185
+ DefaultManagement.loadTable(id);
186
+ // {
187
+ // const result = await ServiceProvider.get();
188
+ // if (result.status === 'success') {
189
+ // rowDataScope = result.data.map((row) => columnDefFormatter(row, columnDefs, options.customFormat));
190
+ // AgGrid.grids[gridId].setGridOption('rowData', rowDataScope);
191
+ // }
192
+ // }
152
193
  s(`.management-table-btn-save-${id}`).onclick = () => {
153
194
  AgGrid.grids[gridId].stopEditing();
154
195
  };
@@ -168,9 +209,13 @@ const DefaultManagement = {
168
209
  // });
169
210
  if (result.status === 'success') {
170
211
  AgGrid.grids[gridId].applyTransaction({
171
- add: [columnDefFormatter(result.data, columnDefs, options.customFormat)],
212
+ add: [columnDefFormatter(rowObj, columnDefs, options.customFormat)],
172
213
  addIndex: 0,
173
214
  });
215
+ // AgGrid.grids[gridId].applyTransaction({
216
+ // add: [columnDefFormatter(result.data, columnDefs, options.customFormat)],
217
+ // addIndex: 0,
218
+ // });
174
219
  // AgGrid.grids[gridId].applyColumnState({
175
220
  // state: [
176
221
  // // { colId: 'country', sort: 'asc', sortIndex: 1 },
@@ -244,9 +289,34 @@ const DefaultManagement = {
244
289
  status: result.status,
245
290
  });
246
291
  if (result.status === 'success') {
247
- AgGrid.grids[gridId].setGridOption('rowData', []);
292
+ DefaultManagement.loadTable(id);
248
293
  }
249
294
  });
295
+ s(`#ag-pagination-${gridId}`).addEventListener('page-change', async (event) => {
296
+ const token = DefaultManagement.Tokens[id];
297
+ token.page = event.detail.page;
298
+ await DefaultManagement.loadTable(id);
299
+ });
300
+ s(`#ag-pagination-${gridId}`).addEventListener('limit-change', async (event) => {
301
+ const token = DefaultManagement.Tokens[id];
302
+ token.limit = event.detail.limit;
303
+ token.page = 1; // Reset to first page
304
+ await DefaultManagement.loadTable(id);
305
+ });
306
+ RouterEvents[id] = async (...args) => {
307
+ const queryParams = getQueryParams();
308
+ const page = parseInt(queryParams.page) || 1;
309
+ const limit = parseInt(queryParams.limit) || 10;
310
+ const token = DefaultManagement.Tokens[id];
311
+
312
+ // Check if the pagination state in the URL is different from the current state
313
+ if (token.page !== page || token.limit !== limit) {
314
+ token.page = page;
315
+ token.limit = limit;
316
+ // Reload the table with the new pagination state from the URL
317
+ await DefaultManagement.loadTable(id);
318
+ }
319
+ };
250
320
  }, 1);
251
321
  return html`<div class="fl">
252
322
  ${await BtnIcon.Render({
@@ -274,6 +344,7 @@ const DefaultManagement = {
274
344
  <div class="in section-mp">
275
345
  ${await AgGrid.Render({
276
346
  id: gridId,
347
+ usePagination: true,
277
348
  darkTheme,
278
349
  gridOptions: {
279
350
  defaultColDef: {
@@ -327,7 +398,32 @@ const DefaultManagement = {
327
398
  status: result.status,
328
399
  });
329
400
  if (result.status === 'success') {
330
- event.data._id = result.data[entity] ? result.data[entity]._id : result.data._id;
401
+ this.Tokens[id].page = 1;
402
+ await DefaultManagement.loadTable(id);
403
+ // const newItemId = result.data?.[entity]?._id || result.data?._id;
404
+ // The `event.node.id` is the temporary ID assigned by AG Grid.
405
+ // const rowNode = AgGrid.grids[gridId].getRowNode(event.node.id);
406
+ setQueryParams({ page: 1, limit: this.Tokens[id].limit });
407
+
408
+ let rowNode;
409
+ AgGrid.grids[gridId].forEachLeafNode((_rowNode) => {
410
+ if (_rowNode.data._id === result.data._id) {
411
+ rowNode = _rowNode;
412
+ }
413
+ });
414
+ if (rowNode) {
415
+ const newRow = columnDefFormatter(result.data, columnDefs, options.customFormat);
416
+ // Add a temporary flag to the new row data.
417
+ newRow._new = true;
418
+ // Update the row data with the data from the server, which includes the new permanent `_id`.
419
+ rowNode.setData(newRow);
420
+ // The `rowClassRules` will automatically apply the 'row-new-highlight' class.
421
+ // Now, remove the flag after a delay to remove the highlight.
422
+ // setTimeout(() => {
423
+ // delete newRow._new;
424
+ // rowNode.setData(newRow);
425
+ // }, 2000);
426
+ }
331
427
  }
332
428
  } else {
333
429
  const body = event.data ? event.data : {};
@@ -336,11 +432,12 @@ const DefaultManagement = {
336
432
  html: result.status === 'error' ? result.message : `${Translate.Render('success-update-item')}`,
337
433
  status: result.status,
338
434
  });
339
- }
340
- if (result.status === 'success') {
341
- AgGrid.grids[gridId].applyTransaction({
342
- update: [event.data],
343
- });
435
+ if (result.status === 'success') {
436
+ AgGrid.grids[gridId].applyTransaction({
437
+ update: [event.data],
438
+ });
439
+ DefaultManagement.loadTable(id, { reload: false });
440
+ }
344
441
  }
345
442
  },
346
443
  },
@@ -47,9 +47,13 @@ const DefaultService = {
47
47
  return reject(error);
48
48
  }),
49
49
  ),
50
- get: (options = { id: '', body: {} }) =>
51
- new Promise((resolve, reject) =>
52
- fetch(getApiBaseUrl({ id: options.id, endpoint }), {
50
+ get: (options = { id: '', body: {}, page: 1, limit: 10 }) => {
51
+ const { id, page, limit } = options;
52
+ const url = new URL(getApiBaseUrl({ id, endpoint }));
53
+ url.searchParams.append('page', page);
54
+ url.searchParams.append('limit', limit);
55
+ return new Promise((resolve, reject) =>
56
+ fetch(url.toString(), {
53
57
  method: 'GET',
54
58
  headers: headersFactory(),
55
59
  })
@@ -64,7 +68,8 @@ const DefaultService = {
64
68
  logger.error(error);
65
69
  return reject(error);
66
70
  }),
67
- ),
71
+ );
72
+ },
68
73
  delete: (options = { id: '', body: {} }) =>
69
74
  new Promise((resolve, reject) =>
70
75
  fetch(getApiBaseUrl({ id: options.id, endpoint }), {