@haloduck/core 2.0.1 → 2.0.3

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.
@@ -0,0 +1,924 @@
1
+ import { from, switchMap, of, distinctUntilChanged, map, catchError, delay, withLatestFrom, tap, forkJoin } from 'rxjs';
2
+ import { fetchAuthSession } from 'aws-amplify/auth';
3
+ import * as i0 from '@angular/core';
4
+ import { inject, isDevMode, Pipe, Injectable, InjectionToken, Inject } from '@angular/core';
5
+ import { createFeatureSelector, createSelector, Store, createAction, props, createReducer, on } from '@ngrx/store';
6
+ import { HttpClient } from '@angular/common/http';
7
+ import { map as map$1, catchError as catchError$1, withLatestFrom as withLatestFrom$1, mergeMap, finalize } from 'rxjs/operators';
8
+ import { ComponentStore } from '@ngrx/component-store';
9
+ import { Actions, createEffect, ofType } from '@ngrx/effects';
10
+
11
+ const authGuard = (route, state) => {
12
+ return from(fetchAuthSession()).pipe(switchMap((session) => {
13
+ if (session.tokens?.idToken) {
14
+ return of(true);
15
+ }
16
+ window.location.href = '/authenticate';
17
+ return of(false);
18
+ }));
19
+ };
20
+
21
+ // deprecated
22
+ const dummyMemberIdInterceptor = (req, next) => {
23
+ const dummyMemberId = localStorage.getItem('dummyMemberId');
24
+ if (req.url.startsWith('http://localhost')) {
25
+ if (dummyMemberId) {
26
+ const clonedRequest = req.clone({
27
+ setHeaders: {
28
+ 'X-Dummy-Member-Id': dummyMemberId || '',
29
+ },
30
+ });
31
+ return next(clonedRequest);
32
+ }
33
+ }
34
+ return next(req);
35
+ };
36
+
37
+ var GlobalSelectors;
38
+ (function (GlobalSelectors) {
39
+ GlobalSelectors.selectGlobalState = createFeatureSelector('global');
40
+ GlobalSelectors.isInitiated = createSelector(GlobalSelectors.selectGlobalState, (state) => state.initiated);
41
+ GlobalSelectors.selectIsAuthenticated = createSelector(GlobalSelectors.selectGlobalState, (state) => state.isAuthenticated);
42
+ GlobalSelectors.selectProfile = createSelector(GlobalSelectors.selectGlobalState, (state) => state.profile);
43
+ GlobalSelectors.selectIsLoading = createSelector(GlobalSelectors.selectGlobalState, (state) => state.loadingReference > 0);
44
+ GlobalSelectors.selectAcl = createSelector(GlobalSelectors.selectGlobalState, (state) => state.acl);
45
+ GlobalSelectors.selectListMenuItem = createSelector(GlobalSelectors.selectGlobalState, (state) => state.listMenuItem);
46
+ GlobalSelectors.selectIsSideMenuOpen = createSelector(GlobalSelectors.selectGlobalState, (state) => state.isSideMenuOpen);
47
+ GlobalSelectors.selectLanguage = createSelector(GlobalSelectors.selectGlobalState, (state) => state.language);
48
+ GlobalSelectors.canActivate = (resource, action, shouldStripTag) => createSelector(GlobalSelectors.selectAcl, (acl) => {
49
+ const allowedActions = [];
50
+ switch (action) {
51
+ case 'delete':
52
+ allowedActions.push('delete');
53
+ break;
54
+ case 'create':
55
+ allowedActions.push('delete');
56
+ allowedActions.push('create');
57
+ break;
58
+ case 'update':
59
+ allowedActions.push('delete');
60
+ allowedActions.push('create');
61
+ allowedActions.push('update');
62
+ break;
63
+ case 'read':
64
+ allowedActions.push('delete');
65
+ allowedActions.push('create');
66
+ allowedActions.push('update');
67
+ allowedActions.push('read');
68
+ }
69
+ const result = Object.keys(acl).some((aclKey) => {
70
+ return ['delete', 'create', 'update', 'read'].some((_action) => {
71
+ if (undefined === acl[aclKey][_action]) {
72
+ return false;
73
+ }
74
+ let [_resource, _conditionsRaw] = resource.split(':');
75
+ const _conditions = _conditionsRaw ? _conditionsRaw.split('|') : [];
76
+ _resource =
77
+ shouldStripTag && _resource.includes('/')
78
+ ? _resource.split('/')[0]
79
+ : _resource;
80
+ const _resourceAclArray = acl[aclKey][_action];
81
+ return _resourceAclArray.some((_resourceAclRaw) => {
82
+ const [_resourceAcl, _conditionsAclRaw] = _resourceAclRaw.split(':');
83
+ const _conditionsAcl = _conditionsAclRaw
84
+ ? _conditionsAclRaw.split('|')
85
+ : [];
86
+ if (_resourceAcl === '*') {
87
+ return true;
88
+ }
89
+ if (_resource === _resourceAcl &&
90
+ allowedActions.includes(_action) &&
91
+ (_conditions.length === 0 ||
92
+ _conditionsAcl.some((_condition) => _conditions.includes(_condition)))) {
93
+ return true;
94
+ }
95
+ return false;
96
+ });
97
+ });
98
+ });
99
+ return result;
100
+ });
101
+ GlobalSelectors.selectCurrentGroupId = createSelector(GlobalSelectors.selectGlobalState, (state) => state.currentGroup?.id);
102
+ GlobalSelectors.selectCurrentGroup = createSelector(GlobalSelectors.selectGlobalState, (state) => state.currentGroup);
103
+ })(GlobalSelectors || (GlobalSelectors = {}));
104
+
105
+ // deprecated
106
+ const groupIdInterceptor = (req, next) => {
107
+ const store = inject((Store));
108
+ const groupId$ = store.select(GlobalSelectors.selectCurrentGroupId);
109
+ if (req.url.endsWith('/member/me'))
110
+ return next(req);
111
+ if (req.url.endsWith('/menu'))
112
+ return next(req);
113
+ if (req.url.endsWith('/acl'))
114
+ return next(req);
115
+ if (req.url.startsWith('https://api') ||
116
+ req.url.startsWith('http://localhost')) {
117
+ return groupId$.pipe(switchMap((groupId) => {
118
+ if (groupId) {
119
+ const clonedRequest = req.clone({
120
+ setHeaders: {
121
+ 'X-Group-Id': groupId || '',
122
+ },
123
+ });
124
+ return next(clonedRequest);
125
+ }
126
+ return next(req);
127
+ }));
128
+ }
129
+ return next(req);
130
+ };
131
+
132
+ const idTokenInterceptor = (req, next) => {
133
+ if (req.url.endsWith('/oauth2/token'))
134
+ return next(req);
135
+ if (req.url.startsWith('https://api')) {
136
+ return from(fetchAuthSession()).pipe(switchMap((session) => {
137
+ if (session.tokens?.idToken) {
138
+ const clonedRequest = req.clone({
139
+ setHeaders: {
140
+ Authorization: `Bearer ${session.tokens.idToken}`,
141
+ },
142
+ });
143
+ return next(clonedRequest);
144
+ }
145
+ return next(req);
146
+ }));
147
+ }
148
+ else if (req.url.startsWith('https://auth') || req.url.startsWith('https://eleven-auth')) {
149
+ return from(fetchAuthSession()).pipe(switchMap((session) => {
150
+ if (session.tokens?.accessToken) {
151
+ const clonedRequest = req.clone({
152
+ setHeaders: {
153
+ Authorization: `Bearer ${session.tokens.accessToken}`,
154
+ },
155
+ });
156
+ return next(clonedRequest);
157
+ }
158
+ return next(req);
159
+ }));
160
+ }
161
+ return next(req);
162
+ };
163
+
164
+ var SearchParams;
165
+ (function (SearchParams) {
166
+ SearchParams.SortDirectionAsc = 'asc';
167
+ SearchParams.SortDirectionDesc = 'desc';
168
+ // export interface OrderAndPage{
169
+ // size: number;
170
+ // sort: Order[];
171
+ // searchAfter?: any[];
172
+ // }
173
+ })(SearchParams || (SearchParams = {}));
174
+
175
+ function responseHandler(response) {
176
+ if (!response) {
177
+ errorHandler({
178
+ error: 'empty response',
179
+ message: 'empty response',
180
+ });
181
+ }
182
+ if (response.error != '00') {
183
+ errorHandler({
184
+ error: response.error,
185
+ message: response.message,
186
+ });
187
+ }
188
+ return response;
189
+ }
190
+ function errorHandler(err) {
191
+ isDevMode() && console.error('API Error: ', err);
192
+ throw err;
193
+ }
194
+
195
+ class DisplayNamePipe {
196
+ transform(member) {
197
+ if (!member)
198
+ return '';
199
+ return (member.nickname?.trim() ||
200
+ (member.firstName || '') + ' ' + (member.lastName || ''));
201
+ }
202
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: DisplayNamePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
203
+ static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "20.1.4", ngImport: i0, type: DisplayNamePipe, isStandalone: true, name: "displayName" });
204
+ }
205
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: DisplayNamePipe, decorators: [{
206
+ type: Pipe,
207
+ args: [{
208
+ name: 'displayName',
209
+ }]
210
+ }] });
211
+
212
+ var GlobalActions;
213
+ (function (GlobalActions) {
214
+ GlobalActions.markInitiated = createAction('[Global] Mark Initiated', props());
215
+ GlobalActions.clearAuthentication = createAction('[Global] Clear Authentication');
216
+ GlobalActions.setAuthenticated = createAction('[Global] Set Authenticated', props());
217
+ GlobalActions.setProfile = createAction('[Global] Set Profile', props());
218
+ GlobalActions.increaseLoadingReference = createAction('[Global] Increase Loading Reference');
219
+ GlobalActions.decreaseLoadingReference = createAction('[Global] Decrease Loading Reference');
220
+ GlobalActions.setAcl = createAction('[Global] Set Acl', props());
221
+ GlobalActions.setListMenuItem = createAction('[Global] Set List Menu Item', props());
222
+ GlobalActions.toggleSideMenu = createAction('[Global] Toggle Side Menu');
223
+ GlobalActions.closeSideMenu = createAction('[Global] Close Side Menu');
224
+ GlobalActions.setLanguage = createAction('[Global] Set Language', props());
225
+ GlobalActions.setCurrentGroup = createAction('[Global] Set Current Group', props());
226
+ })(GlobalActions || (GlobalActions = {}));
227
+
228
+ class AuthService {
229
+ globalStore = inject((Store));
230
+ canActivate(resource, action, shouldStripTag) {
231
+ return this.globalStore
232
+ .select(GlobalSelectors.canActivate(resource, action, shouldStripTag))
233
+ .pipe(distinctUntilChanged());
234
+ }
235
+ getProfile() {
236
+ return this.globalStore.select(GlobalSelectors.selectProfile);
237
+ }
238
+ setProfile(profile) {
239
+ return this.globalStore.dispatch(GlobalActions.setProfile({ profile }));
240
+ }
241
+ isAuthenticated() {
242
+ return this.globalStore
243
+ .select(GlobalSelectors.selectIsAuthenticated)
244
+ .pipe(distinctUntilChanged());
245
+ }
246
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: AuthService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
247
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: AuthService, providedIn: 'root' });
248
+ }
249
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: AuthService, decorators: [{
250
+ type: Injectable,
251
+ args: [{
252
+ providedIn: 'root',
253
+ }]
254
+ }] });
255
+
256
+ const defaultLanguage = { id: 'en', value: 'English' };
257
+ const supportedLanguages = [
258
+ defaultLanguage,
259
+ { id: 'ko', value: '한국어' },
260
+ ];
261
+ const HALODUCK_CORE_CONFIG = new InjectionToken('HALODUCK_CORE_CONFIG', {
262
+ providedIn: 'root',
263
+ factory: () => ({
264
+ stage: 'local',
265
+ appName: 'please-register-app-name-via-provideHaloduckCoreConfig',
266
+ defaultLanguage: defaultLanguage.id,
267
+ dateFormat: {
268
+ long: 'yyyy-MM-dd',
269
+ short: 'yyMMdd',
270
+ },
271
+ apiUrl: 'https://please-register-via-provideHaloduckCoreConfig.com',
272
+ cdnUrl: 'https://please-register-via-provideHaloduckCoreConfig.com',
273
+ map: {
274
+ mapId: 'please-register-map-id-via-provideHaloduckCoreConfig',
275
+ googleApiKey: 'please-register-google-api-key-via-provideHaloduckCoreConfig',
276
+ defaultLngLat: {
277
+ lat: 37.575971,
278
+ lng: 126.976800,
279
+ },
280
+ },
281
+ }),
282
+ });
283
+ function provideHaloduckCoreConfig(config) {
284
+ return {
285
+ provide: HALODUCK_CORE_CONFIG,
286
+ useValue: config,
287
+ };
288
+ }
289
+ class CoreService {
290
+ config = inject(HALODUCK_CORE_CONFIG);
291
+ constructor() { }
292
+ getStage() {
293
+ return this.config.stage;
294
+ }
295
+ getAppName() {
296
+ return this.config.appName;
297
+ }
298
+ getDefaultLanguage() {
299
+ return this.config.defaultLanguage;
300
+ }
301
+ getApiUrl() {
302
+ return this.config.apiUrl;
303
+ }
304
+ getCdnUrl() {
305
+ return this.config.cdnUrl;
306
+ }
307
+ getDateFormatLong() {
308
+ return this.config.dateFormat.long;
309
+ }
310
+ getDateFormatShort() {
311
+ return this.config.dateFormat.short;
312
+ }
313
+ getGoogleApiKey() {
314
+ return this.config.map.googleApiKey;
315
+ }
316
+ getMapId() {
317
+ return this.config.map.mapId;
318
+ }
319
+ getDefaultLngLat() {
320
+ return this.config.map.defaultLngLat;
321
+ }
322
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: CoreService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
323
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: CoreService, providedIn: 'root' });
324
+ }
325
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: CoreService, decorators: [{
326
+ type: Injectable,
327
+ args: [{
328
+ providedIn: 'root',
329
+ }]
330
+ }], ctorParameters: () => [] });
331
+
332
+ class BaseEntityApiService {
333
+ coreService = inject(CoreService);
334
+ http = inject(HttpClient);
335
+ apiUrl = this.coreService.getApiUrl();
336
+ parent;
337
+ createEntity(entity, parent) {
338
+ return this.http
339
+ .put(`${this.apiUrl}/${parent ? parent.name + '/' + parent.id + '/' : ''}${this.getEntityName()}`, entity)
340
+ .pipe(map((response) => responseHandler(response)), catchError((error) => errorHandler(error)));
341
+ }
342
+ getListEntity(searchParams, parent) {
343
+ const filter = JSON.stringify(searchParams.filter);
344
+ const sort = JSON.stringify(searchParams.sort);
345
+ const page = searchParams.page ? JSON.stringify(searchParams.page) : '';
346
+ return this.http
347
+ .get(`${this.apiUrl}/${parent ? parent.name + '/' + parent.id + '/' : ''}${this.getEntityName()}`, {
348
+ params: { filter, sort, page },
349
+ })
350
+ .pipe(map((response) => responseHandler(response)), catchError((error) => errorHandler(error)));
351
+ }
352
+ getEntityById(id, parent) {
353
+ return this.http
354
+ .get(`${this.apiUrl}/${parent ? parent.name + '/' + parent.id + '/' : ''}${this.getEntityName()}/${id}`)
355
+ .pipe(map((response) => responseHandler(response)), catchError((error) => errorHandler(error)));
356
+ }
357
+ updateEntityById(id, entity, parent) {
358
+ return this.http
359
+ .patch(`${this.apiUrl}/${parent ? parent.name + '/' + parent.id + '/' : ''}${this.getEntityName()}/${id}`, entity)
360
+ .pipe(map((response) => responseHandler(response)), catchError((error) => errorHandler(error)));
361
+ }
362
+ deleteEntityById(id, parent) {
363
+ return this.http
364
+ .delete(`${this.apiUrl}/${parent ? parent.name + '/' + parent.id + '/' : ''}${this.getEntityName()}/${id}`)
365
+ .pipe(map((response) => responseHandler(response)), catchError((error) => errorHandler(error)));
366
+ }
367
+ getEntityName() {
368
+ throw new Error('Method not implemented.');
369
+ }
370
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: BaseEntityApiService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
371
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: BaseEntityApiService, providedIn: 'root' });
372
+ }
373
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: BaseEntityApiService, decorators: [{
374
+ type: Injectable,
375
+ args: [{
376
+ providedIn: 'root',
377
+ }]
378
+ }] });
379
+
380
+ class CdnApiService {
381
+ coreService = inject(CoreService);
382
+ http = inject(HttpClient);
383
+ apiUrl = this.coreService.getApiUrl();
384
+ upload(file, keyPrefix) {
385
+ return this.getPresignedPutUrl(`${keyPrefix}/${file.name}`).pipe(switchMap((response) => {
386
+ const presignedUrl = response.data.url;
387
+ const key = response.data.key;
388
+ return this.uploadFile(presignedUrl, file).pipe(map(() => {
389
+ return key;
390
+ }), catchError((error) => {
391
+ console.error('Upload error:', error);
392
+ return errorHandler(error);
393
+ }));
394
+ }), catchError((error) => {
395
+ console.error('Error getting presigned URL:', error);
396
+ return errorHandler(error);
397
+ }));
398
+ }
399
+ getPresignedPutUrl(key) {
400
+ return this.http
401
+ .get(`${this.apiUrl}/tool/presignedPutUrl`, {
402
+ params: { key },
403
+ })
404
+ .pipe(map((response) => responseHandler(response)), catchError((error) => errorHandler(error)));
405
+ }
406
+ uploadFile(presignedUrl, file) {
407
+ return this.http
408
+ .put(presignedUrl, file, {
409
+ headers: { 'x-amz-tagging': 'expire1D=true' },
410
+ })
411
+ .pipe(catchError((error) => errorHandler(error)));
412
+ }
413
+ getPresignedGetUrl(key) {
414
+ return this.http
415
+ .get(`${this.apiUrl}/tool/presignedGetUrl`, {
416
+ params: { key },
417
+ })
418
+ .pipe(delay(10000), // Simulate a delay of 1 second
419
+ map((response) => responseHandler(response)), catchError((error) => errorHandler(error)), map((response) => response.data.url));
420
+ }
421
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: CdnApiService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
422
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: CdnApiService, providedIn: 'root' });
423
+ }
424
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: CdnApiService, decorators: [{
425
+ type: Injectable,
426
+ args: [{
427
+ providedIn: 'root',
428
+ }]
429
+ }] });
430
+
431
+ class GlobalApiService {
432
+ coreService = inject(CoreService);
433
+ http = inject(HttpClient);
434
+ apiUrl = this.coreService.getApiUrl();
435
+ getAcl() {
436
+ return this.http.get(`${this.apiUrl}/acl`).pipe(map((response) => responseHandler(response)), catchError((error) => errorHandler(error)));
437
+ }
438
+ getListMenuItem() {
439
+ return this.http
440
+ .get(`${this.apiUrl}/menu`)
441
+ .pipe(map((response) => responseHandler(response)), catchError((error) => errorHandler(error)));
442
+ }
443
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: GlobalApiService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
444
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: GlobalApiService, providedIn: 'root' });
445
+ }
446
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: GlobalApiService, decorators: [{
447
+ type: Injectable,
448
+ args: [{
449
+ providedIn: 'root',
450
+ }]
451
+ }] });
452
+
453
+ class GroupApiService extends BaseEntityApiService {
454
+ getEntityName() {
455
+ return 'group';
456
+ }
457
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: GroupApiService, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
458
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: GroupApiService, providedIn: 'root' });
459
+ }
460
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: GroupApiService, decorators: [{
461
+ type: Injectable,
462
+ args: [{
463
+ providedIn: 'root',
464
+ }]
465
+ }] });
466
+
467
+ class MemberApiService extends BaseEntityApiService {
468
+ getEntityName() {
469
+ return 'member';
470
+ }
471
+ getProfile() {
472
+ return this.http
473
+ .get(`${this.apiUrl}/${this.getEntityName()}/me`)
474
+ .pipe(map$1((response) => responseHandler(response)), catchError$1((error) => errorHandler(error)));
475
+ }
476
+ checkMemberByEmail(email) {
477
+ return this.http
478
+ .get(`${this.apiUrl}/${this.getEntityName()}/check/email/${email}`)
479
+ .pipe(map$1((response) => responseHandler(response)), catchError$1((error) => errorHandler(error)));
480
+ }
481
+ checkMemberByNickname(nickname) {
482
+ return this.http
483
+ .get(`${this.apiUrl}/${this.getEntityName()}/check/nickname/${nickname}`)
484
+ .pipe(map$1((response) => responseHandler(response)), catchError$1((error) => errorHandler(error)));
485
+ }
486
+ registration(member) {
487
+ return this.http
488
+ .put(`${this.apiUrl}/${this.getEntityName()}/registration`, member)
489
+ .pipe(map$1((response) => responseHandler(response)), catchError$1((error) => errorHandler(error)));
490
+ }
491
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: MemberApiService, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
492
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: MemberApiService, providedIn: 'root' });
493
+ }
494
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: MemberApiService, decorators: [{
495
+ type: Injectable,
496
+ args: [{
497
+ providedIn: 'root',
498
+ }]
499
+ }] });
500
+
501
+ const ITableStateStatusCreating = 'creating';
502
+ const ITableStateStatusCreated = 'created';
503
+ const ITableStateStatusFailedToCreate = 'failedToCreate';
504
+ const ITableStateStatusUpdating = 'updating';
505
+ const ITableStateStatusUpdated = 'updated';
506
+ const ITableStateStatusFailedToUpdate = 'failedToUpdate';
507
+ const ITableStateStatusDeleting = 'deleting';
508
+ const ITableStateStatusDeleted = 'deleted';
509
+ const ITableStateStatusFailedToDelete = 'failedToDelete';
510
+ const ITableStateStatusLoading = 'loading';
511
+ const ITableStateStatusLoaded = 'loaded';
512
+ const ITableStateStatusFailedToLoad = 'failedToLoad';
513
+ class TableStore extends ComponentStore {
514
+ initialState;
515
+ apiService;
516
+ // selectors
517
+ status$ = this.select((state) => state.status);
518
+ parent$ = this.select((state) => state.parent);
519
+ filter$ = this.select((state) => state.filter);
520
+ sort$ = this.select((state) => state.sort);
521
+ page$ = this.select((state) => state.page);
522
+ listEntity$ = this.select((state) => state.listEntity);
523
+ isLoading$ = this.select((state) => state.isLoading);
524
+ lastEvaluatedKey$ = this.select((state) => state.lastEvaluatedKey);
525
+ // effects
526
+ loadListEntity = this.effect((trigger$) => trigger$.pipe(withLatestFrom(this.listEntity$, this.filter$, this.sort$, this.page$, this.parent$), switchMap(([, listEntity, filter, sort, page, parent]) => {
527
+ this.updateStatus(ITableStateStatusLoading);
528
+ return this.apiService
529
+ .getListEntity({ filter, sort, page }, parent)
530
+ .pipe(tap((response) => {
531
+ this.patchState({
532
+ listEntity: [
533
+ ...listEntity,
534
+ ...(response.data ? response.data : []),
535
+ ],
536
+ lastEvaluatedKey: response.lastEvaluatedKey,
537
+ });
538
+ this.updateStatus(ITableStateStatusLoaded);
539
+ }), catchError(() => {
540
+ this.updateStatus(ITableStateStatusFailedToLoad);
541
+ return [];
542
+ }));
543
+ })));
544
+ createEntity = this.effect((trigger$) => trigger$.pipe(withLatestFrom(this.listEntity$, this.parent$), switchMap(([data, listEntity, parent]) => {
545
+ this.updateStatus(ITableStateStatusCreating);
546
+ return this.apiService.createEntity(data, parent).pipe(tap((response) => {
547
+ this.patchState({
548
+ listEntity: (() => {
549
+ if (response.data?.parentId) {
550
+ const updatedListEntity = listEntity.map((entity) => {
551
+ if (entity.id === response.data.parentId) {
552
+ return {
553
+ ...entity,
554
+ children: [
555
+ ...(entity.children
556
+ ? [response.data, ...entity.children]
557
+ : [response.data]),
558
+ ],
559
+ };
560
+ }
561
+ return entity;
562
+ });
563
+ const parentExists = updatedListEntity.some((entity) => entity.id === response.data.parentId);
564
+ if (!parentExists) {
565
+ return updatedListEntity.map((entity) => ({
566
+ ...entity,
567
+ children: entity.children?.map((child) => child.id === response.data.parentId
568
+ ? {
569
+ ...child,
570
+ children: [
571
+ ...(child.children
572
+ ? [response.data, ...child.children]
573
+ : [response.data]),
574
+ ],
575
+ }
576
+ : child),
577
+ }));
578
+ }
579
+ return updatedListEntity;
580
+ }
581
+ return [
582
+ ...(response.data ? [response.data] : []),
583
+ ...listEntity,
584
+ ];
585
+ })(),
586
+ });
587
+ this.updateStatus(ITableStateStatusCreated);
588
+ }), catchError(() => {
589
+ this.updateStatus(ITableStateStatusFailedToCreate);
590
+ return [];
591
+ }));
592
+ })));
593
+ getEntityById = this.effect((trigger$) => trigger$.pipe(withLatestFrom(this.listEntity$, this.parent$), switchMap(([id, listEntity, parent]) => {
594
+ this.updateStatus(ITableStateStatusLoading);
595
+ return this.apiService.getEntityById(id, parent).pipe(tap((response) => {
596
+ this.patchState({
597
+ listEntity: (() => {
598
+ if (response.data?.parentId) {
599
+ const updatedListEntity = listEntity.map((entity) => {
600
+ if (entity.id === response.data.parentId) {
601
+ return {
602
+ ...entity,
603
+ children: [
604
+ ...(entity.children ? [response.data, ...entity.children] : [response.data]),
605
+ ],
606
+ };
607
+ }
608
+ return entity;
609
+ });
610
+ const parentExists = updatedListEntity.some((entity) => entity.id === response.data.parentId);
611
+ if (!parentExists) {
612
+ return updatedListEntity.map((entity) => ({
613
+ ...entity,
614
+ children: entity.children?.map((child) => child.id === response.data.parentId
615
+ ? {
616
+ ...child,
617
+ children: [
618
+ ...(child.children ? [response.data, ...child.children] : [response.data]),
619
+ ],
620
+ }
621
+ : child),
622
+ }));
623
+ }
624
+ return updatedListEntity;
625
+ }
626
+ return listEntity.map((e) => e.id === response.data.id ? response.data : e);
627
+ })(),
628
+ });
629
+ this.updateStatus(ITableStateStatusLoaded);
630
+ }), catchError(() => {
631
+ this.updateStatus(ITableStateStatusFailedToLoad);
632
+ return [];
633
+ }));
634
+ })));
635
+ updateEntityById = this.effect((trigger$) => trigger$.pipe(withLatestFrom(this.listEntity$, this.parent$), switchMap(([data, listEntity, parent]) => {
636
+ this.updateStatus(ITableStateStatusUpdating);
637
+ return this.apiService.updateEntityById(data.id, data.entity, parent).pipe(tap((response) => {
638
+ this.patchState({
639
+ listEntity: (() => {
640
+ if (response.data?.parentId) {
641
+ const updatedListEntity = listEntity.map((entity) => {
642
+ if (entity.id === response.data.parentId) {
643
+ return {
644
+ ...entity,
645
+ children: entity.children?.map((child) => child.id === response.data.id ? response.data : child),
646
+ };
647
+ }
648
+ return entity;
649
+ });
650
+ const parentExists = updatedListEntity.some((entity) => entity.id === response.data.parentId);
651
+ if (!parentExists) {
652
+ return updatedListEntity.map((entity) => ({
653
+ ...entity,
654
+ children: entity.children?.map((child) => child.id === response.data.parentId
655
+ ? {
656
+ ...child,
657
+ children: child.children?.map((grandChild) => grandChild.id === response.data.id
658
+ ? response.data
659
+ : grandChild),
660
+ }
661
+ : child),
662
+ }));
663
+ }
664
+ return updatedListEntity;
665
+ }
666
+ return listEntity.map((e) => e.id === response.data.id ? response.data : e);
667
+ })(),
668
+ });
669
+ this.updateStatus(ITableStateStatusUpdated);
670
+ }), catchError(() => {
671
+ this.updateStatus(ITableStateStatusFailedToUpdate);
672
+ return [];
673
+ }));
674
+ })));
675
+ deleteEntityById = this.effect((trigger$) => trigger$.pipe(withLatestFrom(this.listEntity$, this.parent$), switchMap(([id, listEntity, parent]) => {
676
+ this.updateStatus(ITableStateStatusDeleting);
677
+ return this.apiService.deleteEntityById(id, parent).pipe(tap(() => {
678
+ this.patchState({
679
+ listEntity: listEntity.filter((e) => e.id !== id),
680
+ });
681
+ this.updateStatus(ITableStateStatusDeleted);
682
+ }), catchError(() => {
683
+ this.updateStatus(ITableStateStatusFailedToDelete);
684
+ return [];
685
+ }));
686
+ })));
687
+ // actions
688
+ updateEntity = this.updater((state, data) => ({
689
+ ...state,
690
+ listEntity: state.listEntity.map((e) => {
691
+ return e.id === data.id ? data : e;
692
+ }),
693
+ }));
694
+ updateStatus = this.updater((state, status) => ({
695
+ ...state,
696
+ status,
697
+ }));
698
+ setParent = this.updater((state, parent) => ({
699
+ ...state,
700
+ parent,
701
+ }));
702
+ updateSortField = this.updater((state, sort) => ({
703
+ ...state,
704
+ sort: [sort],
705
+ }));
706
+ updateFilter = this.updater((state, filter) => ({
707
+ ...state,
708
+ filter,
709
+ }));
710
+ updatePage = this.updater((state, page) => ({
711
+ ...state,
712
+ page,
713
+ }));
714
+ setExpandMode = this.updater((state, { id, mode }) => ({
715
+ ...state,
716
+ listEntity: state.listEntity.map((e) => ({
717
+ ...e,
718
+ expandMode: e.id === id ? mode : e.expandMode,
719
+ })),
720
+ }));
721
+ toggleExpanded = this.updater((state, { id }) => ({
722
+ ...state,
723
+ listEntity: state.listEntity.map((e) => ({
724
+ ...e,
725
+ isExpanded: e.id === id ? !(e.isExpanded || false) : e.isExpanded,
726
+ })),
727
+ }));
728
+ showExpanded = this.updater((state, { id }) => ({
729
+ ...state,
730
+ listEntity: state.listEntity.map((e) => ({
731
+ ...e,
732
+ isExpanded: e.id === id ? true : e.isExpanded,
733
+ })),
734
+ }));
735
+ hideExpanded = this.updater((state, { id }) => ({
736
+ ...state,
737
+ listEntity: state.listEntity.map((e) => ({
738
+ ...e,
739
+ isExpanded: e.id === id ? false : e.isExpanded,
740
+ })),
741
+ }));
742
+ toggleSelected = this.updater((state, { id }) => ({
743
+ ...state,
744
+ listEntity: state.listEntity.map((e) => ({
745
+ ...e,
746
+ isSelected: e.id === id ? !(e.isSelected || false) : e.isSelected,
747
+ })),
748
+ }));
749
+ constructor(initialState, apiService) {
750
+ super(initialState);
751
+ this.initialState = initialState;
752
+ this.apiService = apiService;
753
+ // this.loadListEntity();
754
+ }
755
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: TableStore, deps: [{ token: 'initialState' }, { token: 'apiService' }], target: i0.ɵɵFactoryTarget.Injectable });
756
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: TableStore });
757
+ }
758
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: TableStore, decorators: [{
759
+ type: Injectable
760
+ }], ctorParameters: () => [{ type: undefined, decorators: [{
761
+ type: Inject,
762
+ args: ['initialState']
763
+ }] }, { type: undefined, decorators: [{
764
+ type: Inject,
765
+ args: ['apiService']
766
+ }] }] });
767
+
768
+ class GroupStore extends TableStore {
769
+ constructor() {
770
+ super({
771
+ isLoading: false,
772
+ filter: {
773
+ dateRange: undefined,
774
+ organizationId: [],
775
+ id: [],
776
+ type: [],
777
+ active: null,
778
+ approved: null,
779
+ keyword: '',
780
+ },
781
+ sort: [
782
+ {
783
+ field: 'created_timestamp',
784
+ direction: SearchParams.SortDirectionDesc,
785
+ },
786
+ ],
787
+ page: {
788
+ limit: 10,
789
+ },
790
+ listEntity: [],
791
+ }, inject(GroupApiService));
792
+ }
793
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: GroupStore, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
794
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: GroupStore });
795
+ }
796
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: GroupStore, decorators: [{
797
+ type: Injectable
798
+ }], ctorParameters: () => [] });
799
+
800
+ class MemberStore extends TableStore {
801
+ constructor() {
802
+ super({
803
+ isLoading: false,
804
+ filter: {
805
+ dateRange: undefined,
806
+ organizationId: [],
807
+ groupId: [],
808
+ type: [],
809
+ active: null,
810
+ keyword: '',
811
+ },
812
+ sort: [
813
+ {
814
+ field: 'created_timestamp',
815
+ direction: SearchParams.SortDirectionDesc,
816
+ },
817
+ ],
818
+ page: {
819
+ limit: 10,
820
+ },
821
+ listEntity: [],
822
+ }, inject(MemberApiService));
823
+ }
824
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: MemberStore, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
825
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: MemberStore });
826
+ }
827
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: MemberStore, decorators: [{
828
+ type: Injectable
829
+ }], ctorParameters: () => [] });
830
+
831
+ class GlobalEffects {
832
+ actions$ = inject(Actions);
833
+ memberApiService = inject(MemberApiService);
834
+ globalApiService = inject(GlobalApiService);
835
+ groupApiService = inject(GroupApiService);
836
+ store = inject((Store));
837
+ setAuthenticated$ = createEffect(() => this.actions$.pipe(ofType(GlobalActions.setAuthenticated), withLatestFrom$1(this.store.select(GlobalSelectors.selectIsAuthenticated)), mergeMap(([action, isAuthenticated]) => {
838
+ if (isAuthenticated) {
839
+ this.store.dispatch(GlobalActions.increaseLoadingReference());
840
+ return forkJoin({
841
+ profile: this.memberApiService.getProfile(),
842
+ acl: this.globalApiService.getAcl(),
843
+ listMenuItem: this.globalApiService.getListMenuItem(),
844
+ }).pipe(mergeMap(({ profile, acl, listMenuItem }) => {
845
+ const groupId = profile.data.groupId;
846
+ return this.groupApiService.getEntityById(groupId).pipe(mergeMap((group) => [
847
+ GlobalActions.setProfile({ profile: profile.data }),
848
+ GlobalActions.setAcl({ acl: acl.data }),
849
+ GlobalActions.setListMenuItem({
850
+ listMenuItem: listMenuItem.data,
851
+ }),
852
+ GlobalActions.setCurrentGroup({ group: group.data }),
853
+ GlobalActions.markInitiated({ initiated: true }),
854
+ ]));
855
+ }), catchError$1(() => of(GlobalActions.clearAuthentication())), finalize(() => {
856
+ this.store.dispatch(GlobalActions.decreaseLoadingReference());
857
+ }));
858
+ }
859
+ return of(GlobalActions.clearAuthentication());
860
+ })));
861
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: GlobalEffects, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
862
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: GlobalEffects });
863
+ }
864
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.4", ngImport: i0, type: GlobalEffects, decorators: [{
865
+ type: Injectable
866
+ }] });
867
+
868
+ const initialState = {
869
+ initiated: false,
870
+ isAuthenticated: false,
871
+ loadingReference: 0,
872
+ acl: {},
873
+ listMenuItem: [],
874
+ isSideMenuOpen: false,
875
+ language: 'en', // TODO: Use a proper language management system
876
+ profile: undefined,
877
+ currentGroup: undefined,
878
+ };
879
+
880
+ const globalReducer = createReducer(initialState, on(GlobalActions.markInitiated, (state) => ({
881
+ ...state,
882
+ initiated: true,
883
+ })), on(GlobalActions.setAuthenticated, (state, { isAuthenticated }) => ({
884
+ ...state,
885
+ isAuthenticated,
886
+ })), on(GlobalActions.setProfile, (state, { profile }) => ({
887
+ ...state,
888
+ profile,
889
+ })), on(GlobalActions.increaseLoadingReference, (state) => ({
890
+ ...state,
891
+ loadingReference: state.loadingReference + 1,
892
+ })), on(GlobalActions.decreaseLoadingReference, (state) => ({
893
+ ...state,
894
+ loadingReference: Math.max(state.loadingReference - 1, 0),
895
+ })), on(GlobalActions.setAcl, (state, { acl }) => ({
896
+ ...state,
897
+ acl,
898
+ })), on(GlobalActions.setListMenuItem, (state, { listMenuItem }) => ({
899
+ ...state,
900
+ listMenuItem,
901
+ })), on(GlobalActions.toggleSideMenu, (state) => ({
902
+ ...state,
903
+ isSideMenuOpen: !state.isSideMenuOpen,
904
+ })), on(GlobalActions.closeSideMenu, (state) => ({
905
+ ...state,
906
+ isSideMenuOpen: false,
907
+ })), on(GlobalActions.setLanguage, (state, { language }) => ({
908
+ ...state,
909
+ language,
910
+ })), on(GlobalActions.setCurrentGroup, (state, { group }) => ({
911
+ ...state,
912
+ currentGroup: group,
913
+ })));
914
+
915
+ /*
916
+ * Public API Surface of core
917
+ */
918
+
919
+ /**
920
+ * Generated bundle index. Do not edit.
921
+ */
922
+
923
+ export { AuthService, BaseEntityApiService, CdnApiService, CoreService, DisplayNamePipe, GlobalActions, GlobalApiService, GlobalEffects, GlobalSelectors, GroupApiService, GroupStore, HALODUCK_CORE_CONFIG, ITableStateStatusCreated, ITableStateStatusCreating, ITableStateStatusDeleted, ITableStateStatusDeleting, ITableStateStatusFailedToCreate, ITableStateStatusFailedToDelete, ITableStateStatusFailedToLoad, ITableStateStatusFailedToUpdate, ITableStateStatusLoaded, ITableStateStatusLoading, ITableStateStatusUpdated, ITableStateStatusUpdating, MemberApiService, MemberStore, SearchParams, TableStore, authGuard, defaultLanguage, dummyMemberIdInterceptor, errorHandler, globalReducer, groupIdInterceptor, idTokenInterceptor, initialState, provideHaloduckCoreConfig, responseHandler, supportedLanguages };
924
+ //# sourceMappingURL=haloduck-core.mjs.map